text:
Q: maximize $\tbinom{500}{x}\times\tbinom{500}{900-3x}$
2 fair coins A and B, for A, tossing H gets 3 dollars; for B, tossing H gets 1 dollar. Now toss A and B 500 times each, finally we get 900 dollars. Estimate the most likely number of times of H for A and B (you are not necessary to calculate the exact value, just give the best possible bound).

It is equivalent to find the x to maximize:
$$f(x)=\tbinom{500}{x}\times\tbinom{500}{900-3x},$$
here $134\leq x \leq 500.$ Even I use the fact that the optimal $x^*$ meets:
$$f(x^*)\geq f(x^*+1)\ and\ f(x^*)\geq f(x^*-1).$$
I still can hardly solve $x^*.$

A: Using algebra, the problem is not too bad.
Go from  binomial coefficients to the gamma function.
$$\binom{500}{x}\times\binom{500}{900-3x}=\frac{\Gamma (501)^2}{\Gamma (x+1)\,\, \Gamma (501-x)\,\, \Gamma (901-3 x) \,\,\Gamma (3x-399)}$$ which implies that you want to minimize
$$g(x)=\Gamma (x+1)\,\, \Gamma (501-x)\,\, \Gamma (901-3 x) \,\,\Gamma (3x-399)$$ or, much better, its logarithm. Using derivative
$$\frac{g'(x)}{g(x)}=3 H_{3 x-400}-H_{500-x}-3 H_{900-3 x}+H_x$$ and you want it to be equal to $0$. This is a nice and smooth function and you look for the solution between $134$ and $299$. Make an expansion to $O(x^2)$ around the midpoint and solve for $x$. You will obtain $x=220.0138$ while the "exact" solution given by Newton method is $220.0128$.
I think that we have the good approximation. Just try three points $(219,220,221)$ and you will see which is the one giving the maximum value of the initial expression.


text:
Q: Do Java compilers commonly precompute hashcodes of final fields? I have a HashMap-intensive Java program in which several classes have hashcodes computed from final fields. For example:
public class Foo {
    private final int bar;
    private final String zot;

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + bar;
        result = prime * result + zot.hashCode();
        return result;
    }
}

It's possible for the compiler to observe that the hashcode cannot change after object initialization, and precompute it into an additional private final field. Do current Java compilers do this, like the one in Oracle JDK 7? I could disassmble the .class file, but then the JIT may also do this kind of optimization at runtime and I would not see it there. Anyway, I'm interested in other cases besides this one, so it would be great to find a general approach for identifying any optimizations the compiler does automatically.

A:
Do current Java compilers do this, like the one in Oracle JDK 7?

The javac does almost no optimisations.

I could disassmble the .class file,

You might not like what you see in terms of optimisations. ;)

but then the JIT may also do this kind of optimization at runtime and I would not see it there.

If the JIT did optimise this, you wouldn't see it and in fact it doesn't do this.  This is why String caches it's hashCode() at runtime, explicitly in code.

A: No, compilers do not do this. However, it wouldn't be hard to store the hash code yourself in a field, and refer to that instead of computing anew all the time:
private int hash = -1;

public int hashCode() {
    if (hash == -1) {
        // compute hash, assign it to the hash variable, and return it
    } else {
        return hash;
    }
}

This approach is actually taken by the String class, which you can see if you inspect its source:
121  /** Cache the hash code for the string */
122  private int hash; // Default to 0

A: It's possible for the compiler to do that for any suitable method, not just hashCode(), but it doesn't. You can see for yourself via javap -p whether there are any added fields, and you can also see the bytecode with javap -c.
However the method you have posted isn't a suitable candidate. The implementation of String.hashCode() at runtime could be different from the one available to the compiler. The compiler can't assume it isn't.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Does git pull --recurse-submodule really pulls latest commit in submodule? This thread's  (Easy way to pull latest of all git submodules)  answer states that when running:
$ git pull --recurse-submodules

will pull the latest commits in the submodules. But when trying it, it doesn't seem to work.
I have a demo repo with a demo submodule called "tinyXml" (It's not the real tinyXml, just a demo). Take a look at the following shell interaction:
PS D:\DemoProject> cd .\tinyXml
PS D:\DemoProject\tinyXml> git status
HEAD detached at 9101c63
nothing to commit, working tree clean
PS D:\DemoProject\tinyXml> cd ..
PS D:\DemoProject> git pull --recurse-submodules
Fetching submodule tinyXml
Already up to date.
PS D:\DemoProject> cd .\tinyXml\
PS D:\DemoProject\tinyXml> git status
HEAD detached at 9101c63
nothing to commit, working tree clean
PS D:\DemoProject\tinyXml> cd ..
PS D:\DemoProject> git submodule update --remote
Submodule path 'tinyXml': checked out 'e249788ed10afbdff043f758f46add75b81d522a'

So you see that git submodule update --remote works, but git pull --recurse-submodules didn't pull the latest commit in the submodule.
My git version - 2.32.0

A: The short answer is no.  That's because submodules are not supposed to use the latest commit.
The intent of a submodule is that the superproject repository specifies which commit is to be used in the submodule.  The superproject repository does not list a branch name to be used in the submodule; that's not reliable.  So instead, the superproject repository lists the raw hash ID to be used in the submodule, as this is reliable.
The submodules are therefore checked out as "detached HEAD"s.  This is by design.
Remember that each submodule is a separate Git repository.  It is not part of the superproject.  The superproject repository simply lists the URL for cloning the submodule, so that Git can run git clone, plus the path (so that the superproject knows where to put the submodule) and the correct hash ID (so that the superproject knows which commit to use as the detached HEAD).
What you want instead
Now, there is a way, from the superproject repository, to make a request to the superproject Git to do something different in the submodule.  That way is not to run git pull.  Instead, you want git submodule update, with specific flags.  The specific flags you want include, but are not necessarily limited to, --remote.
I said above that the superproject does not list a branch for each submodule.  That's only partly true.  The superproject can list a branch name for each submodule.  But remember this: a branch name is just a way to say "get some particular commit".  Which particular commit is that?  Well, that's the tricky part, because each Git repository has its own branch names.  Your superproject Git has its own branch names, and each submodule that you've cloned has its own branch names, and the repositories from which each repository is cloned have their own branch names, and so on.
This gets very confusing, because at this point there are an absolute minimum of four Git repositories involved here:

*

*You have your own clone of the superproject, as your repository R.

*Your R has an origin from which you get commits.

*Your R has some submodule S, which your Git creates by running git clone.

*Your S has an origin from which it gets commits.

When you clone some Git repository, you get all of their commits and none of their branches.  Your Git then creates one branch in your own local repository.  Your Git takes their branch names and changes them, transforming them into your own Git's remote-tracking names: their main or master becomes your origin/main or origin/master, for instance.
This is also true for each of your submodules.  When your superproject Git runs git clone url path/to/submodule to clone some other repository as the submodule living in path/to/submodule, that submodule Git repository that this git clone command copies ... well, this is just like any other git clone.  Git copies, from that URL, all of their commits and none of their branches.  So a branch name is actually not useful here.  The "branch name" that your superproject repository R is allowed, but not required, to store for submodule S is not your branch name at all—since that's not useful—but rather a branch name in S's origin.
Your superproject Git will, in R, run, in effect:
(cd path/to/S; git fetch)

This will make your Git-that-controls-S use git fetch to obtain commits from S's origin.  This will update S's remote-tracking names, such as S's origin/main and origin/feature and so on.
If R says that S should use "branch feature", this really means that your Git, operating in R, should run:
(cd path/to/S; git fetch)

followed by:
(cd path/to/S; git rev-parse origin/feature)

This git rev-parse running inside S will obtain the commit hash ID for origin/feature as found in S, which was just updated by the git fetch that your Git ran in S, to get the raw hash ID.
This is what the --remote in git submodule update --remote means: after running git fetch in the submodule, use the branch name stored in R to construct the remote-tracking name that will be found in S to obtain the commit hash ID for a commit to look for in S.
The rest of the git submodule update command determines what to do with this hash ID.  With --checkout, the operation to do with this hash ID is a git checkout of a detached HEAD using that hash ID.
Hence:
git submodule update --recurse --checkout --remote

will enter each submodule S of your repository R and run git fetch and git rev-parse and do a detached-HEAD checkout in S as appropriate and will recurse inside S to update any submodules that S has.
You might not want --checkout though.  What you do want depends, on too many factors to really go into here.  The one thing I will note is that, once the submodules are on the commits you want them to be on, you need to make new superproject commits to record these hash IDs in the superproject(s).  This, too, can be painful.
This is insanely complicated.  Why is Git so hard?
Yes, it is.  I can't answer the "why", other than to note that this is, fundamentally, a hard problem.
This isn't what I want to do.  Why can't Git do _____ instead?
Someone is probably working on that right now.  There are projects underway to improve submodules.  It's ... hard.
This is what there is today.  Don't use git pull; it is not up to the job.  Even git submodule update may not be up to your job, whatever that is.

A: As you can see by your log, some of your submodules are not on a branch, but in a detached state.
You should enter each submodule and checkout the right branch, the go back and issue again the git pull --recurse-submodules command.


text:
Q: Create COM object I want to test creating a COM object. Normally I use Excel or Word VBA and add a reference to the DLL I want to test. However I am on a Windows 2008 server without these programs and only the basic software installed that comes with Windows, plus IIS. How can I create a COM object easily and call its properties and methods?

A: You could use Powershell.
For example, this creates new Word App com object:
$word = new-object -com Word.Application
If you use PS 3+ ISE, it also includes handy Intellisense:

Full reference here: https://technet.microsoft.com/en-us/library/Hh849885.aspx
And usage here: https://technet.microsoft.com/en-us/%5Clibrary/Dd347574.aspx


text:
Q: Obtain google-services.json externally I have an Android app that receives push notifications sent via Firebase. My project includes the google-services.json generated from Firebase with my account.
I would like to know if there's a way to avoid putting the google-services.json inside the project and obtain this info externally, from a server of mine for example, once the APK is built and installed in the device.
The main goal is to be able to choose which Firebase account the app uses from my server web app.
Thanks!

A: No. There is no such option. The whole point is to bind your app with one Google Service doing the same thing (like push notifications). You can use multiple files/services for different things though - i.e. one for real time database and another for push notification.


text:
Q: The ratio of number of edges to the sum of vertices and edges of a graph. The ratio of number of edges to the number of vertices of a graph is called its beta index (it is a measure of the graph  connectivity).  Now, i want to use a term which is the ratio of number of edges to the sum of vertices and edges of a graph (is this ratio has a name already?). As per my observations, the numerical value of this ratio of a graph $G$ is always less than or equal to its subgraphs. My questions are:

What is call this ratio?

Is my observation of the numerical value of this ratio of a graph $G$ being always less than or equal to its subgraphs correct?

Edit: Discrete graph, empty graph and null graph are excluded here.

A: Nope, this does not always hold. We can find graphs where your ratio is arbitrarily close to $1$: for example, a complete graph with $n$ vertices has a ratio of
$$
   \frac{\binom n2}{n + \binom n2} = \frac{n-1}{n+1} = 1 - \frac2{n+1}.
$$
On the other hand, you can take a subgraph consisting of, for example, two adjacent vertices and the edge between them. Here, the ratio is just $\frac{1}{2+1} = \frac13$.

Your ratio does not have a name, but it's a function of your "beta index": if a graph has $v$ vertices, $e$ edges, and beta index $\beta = \frac ev$, then the ratio $\frac{e}{v+e}$ is equal to $\frac{\beta}{\beta+1}$. It can also be found in terms of a more well-known quantity, the average degree: if a graph has average degree $d$, then it has beta index $\frac12d$, so your ratio is $\frac{d}{d+2}$.
In particular, it's an increasing function of both values, so if you take any graph $G$ and a subgraph $H$ with a smaller average degree, then the same relation will hold between their ratios: we'll have $\frac{e(G)}{v(G)+e(G)} > \frac{e(H)}{v(H) + e(H)}$.


text:
Q: Java service wrapper and additional application command line parameters I'm currently using java service wrapper to wrap a java application that I've developed.  I'm needing to ability to pass in additional command line parameters to my application through the java service wrapper.
Pretend my app is called myapp and I've setup java service wrapper so that the script I run to start is called myapp.  I'd like to be able to do something like this:
./myapp start Parameter1 parameter2
and have those additional parameters get passed into my application.  Any ideas how to do this? I'm finding that googling and looking at the documentation is only pulling up how to use command line arguments to setup java service wrapper. I've had difficulty finding anything about passing command line arguments to your application except for having them hard coded in your wrapper.conf file.
Right now I feel like my option is to take the additional command line parameters, set them to environment variables and have those hard coded in the wrapper.conf. I'd prefer not to go down that road though and am hoping I've overlooked something.

A: in the 3.5.2 release of the wrapper, we added a possibility to achieve what you are asking for, by using "--" to precede parameters to the java application:
https://sourceforge.net/tracker/?func=detail&aid=3017567&group_id=39428&atid=425190
this is basically working for calling the binary of the wrapper directly, but for shell script you can easily achieve the same by modifying it a bit:
open the script and in the console(), start() ( and optionally launchdinternally()) set the command_line to the following:
    COMMAND_LINE="$CMDNICE \"$WRAPPER_CMD\" \"$WRAPPER_CONF\" wrapper.syslog.ident=\"$APP_NAME\" wrapper.pidfile=\"$PIDFILE\" wrapper.name=\"$APP_NAME\" wrapper.displayname=\"$APP_LONG_NAME\" $ANCHORPROP $STATUSPROP $LOCKPROP $@"

note the $@ at the end.
now, go to quite the end of the script, where it decides what function it should call (console, start, stop, restart, etc.)
in the 'console', 'start' (and 'launchdinternal') set a shift and pass over the parameters from the commandline to the function:
'console')
    checkUser touchlock $1
    shift
    console $@
    ;;

'start')
    if [ "$DIST_OS" = "macosx" -a -f "/Library/LaunchDaemons/${APP_PLIST}" ] ; then
        macosxstart
    else
        checkUser touchlock $1
        shift
        start $@
    fi
    ;;

..
    'launchdinternal')
    shift
    launchdinternal $@
    ;;

after that, you can call the script like this:
./script start|console -- para1 para2 ...
hope this helps you out.
cheers,
christian

A: Jake,
Quick followup.  In version 3.5.5 of the Java Service Wrapper's shell script, we added a new PASS_THROUGH option towards the top which now makes passing command line arguments through to the JVM work out of the box.
The script makes use of the "--" command line parameter that Christian mentioned back in August.
Cheers,
Leif

A: Can you post an example of what the "myapp" script looks like? Not the whole thing but it'd be useful to see what the part that launches the java process looks like.
What you want to accomplish should be as simple as making sure that $@ is passed into the java process by the script. In Bash, $@ is an array that contains all of the arguments passed into the script. If the wrapper produced by java service wrapper needs you to pass in "start" as one of the arguments, then you might have to add a bit of scripting to pass all of the arguments but the first to the java process.


text:
Q: ingresar elementos en una lista, que no sean iguales a los existentes. C# Como contexto: El programa es un ejemplo de listas a través de una pizzería, cuando se agrega una pizza se pregunta por la cantidad de ingredientes (sólo puede ser de 2 ingredientes o más). al momento de la captura SÓLAMENTE se puede capturar el mismo ingrediente una sola vez, es decir, un mismo ingrediente no se puede repetir para la misma pizza. ¿Cómo puedo lograr esto? Adjunto código.
Tengo distintas clases para el programa, van en este orden:
Clase Program:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Pizzeria
{
    class Program
    {
        static void Main(string[] args)
        {
            Menu menu = new Menu();

            menu.MenuPizza();

            Console.ReadKey();
        }

    }
}

Después clase Menú, aqui hago la mayoría de las acciones, básicamente declaro los objetos para llamar las clases. Intuyo que podría ser directamente en la opción 1 del menú, cuando estoy insertando los ingredientes, buscar en la lista de ingredientes existentes y ver si hay el mismo que se está intentando insertar para de esa forma pedir que inserte otro.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Pizzeria
{
    class Menu
    {

        public void MenuPizza()
        {

            Cocina cocinaObj = new Cocina();
            Pizza pizzaObj = new Pizza();
            Ingredientes ingredientesObj = new Ingredientes();
            int costopizzatotal = 0;
            int costopizzabase = 100;
            int costoTotalPizzaDia = 0;
            int opc = 0;
            string nombrePizzaAux = null;

            do
            {
                Console.WriteLine("Elige una opcion\n" +
                "\n1.- Agregar una nueva Pizza." +
                "\n2.- Mostrar listado de Pizzas preparadas." +
                "\n3.- Mostrar ingredientes de alguna pizza preparada." +
                "\n4.- Mostrar el costo de todas las pizzas preparadas en el día hasta este momento.");

                opc = Convert.ToInt32(Console.ReadLine());

                switch (opc)
                {
                    case 1:

                        //Añadir pizza
                        pizzaObj = CapturarPizza();
                        cocinaObj.AgregarPizza(pizzaObj);

                        //Crear ingrediente y agregarlo a la pizza
                        do
                        {
                            try
                            {
                                Console.WriteLine("¿Cuántos ingredientes desea?");
                                pizzaObj.cantIngredientes = Convert.ToInt32(Console.ReadLine());
                            }
                            catch (Exception errorCaptura)
                            {
                                Console.WriteLine(errorCaptura.Message);
                            }
                        } while (pizzaObj.cantIngredientes <= 1);

                        for (int i = 0; i < pizzaObj.cantIngredientes; i++)
                        {
                            ingredientesObj = CapturarIngrediente();
                            cocinaObj.AgregarIngredienteAPizza(pizzaObj.Nombre_Pizza, ingredientesObj);
                        }

                        List<Ingredientes> IngredienteDePizzaCosto = new List<Ingredientes>();
                        IngredienteDePizzaCosto = cocinaObj.ListadoDeIngredientesEnPIzza(pizzaObj.Nombre_Pizza);
                        foreach (Ingredientes ingrediente in IngredienteDePizzaCosto)
                        {
                            Console.WriteLine("Nombre del ingrediente: {0} -\tCosto: {1} -\tCantidad en gramos: {2}",
                                ingrediente.Nombre_Ingrediente, ingrediente.Costo, ingrediente.Cantidad);

                            costopizzatotal += ingrediente.Costo;

                        }
                        costopizzatotal += costopizzabase;

                        costoTotalPizzaDia = costoPizzasDia(costoTotalPizzaDia, costopizzatotal);

                        Console.WriteLine("El costo total de la pizza es: " + costopizzatotal);

                        costopizzatotal = 0;

                        ingredientesObj = null;
                        pizzaObj = null;
                        break;

                    case 2:

                        //Listado de pizzas
                        List<Pizza> lstPizzaAux = new List<Pizza>();
                        lstPizzaAux = cocinaObj.ListarPizzas();
                        foreach (Pizza c in lstPizzaAux)
                        {
                            Console.WriteLine("Nombre: {0} - \t Tamaño: {1}",
                          c.Nombre_Pizza,
                          c.Tamaño);
                        }

                        break;

                    case 3:

                        //Listado de Ingredientes de una pizza
                        List<Ingredientes> IngredienteDePizza = new List<Ingredientes>();

                        Console.WriteLine("Escriba el nombre de la pizza de la cuál desea saber sus ingredientes:");
                        nombrePizzaAux = Console.ReadLine();
                        IngredienteDePizza = cocinaObj.ListadoDeIngredientesEnPIzza(nombrePizzaAux);
                        foreach (Ingredientes ingrediente in IngredienteDePizza)
                        {
                            Console.WriteLine("Nombre del ingrediente: {0} -\tCosto: {1} -\tCantidad en gramos: {2}",
                                ingrediente.Nombre_Ingrediente, ingrediente.Costo, ingrediente.Cantidad);

                        }

                        break;

                    case 4:

                        Console.WriteLine("El costo del total de pizzas es: " + costoTotalPizzaDia);

                        break;

                }
            } while (opc != 5);

        }

        //Capturas
        public static Ingredientes CapturarIngrediente()
        {
            Ingredientes ingredientes = new Ingredientes();

            Console.WriteLine("Nombre del ingrediente: ");
            ingredientes.Nombre_Ingrediente = Console.ReadLine();
            Console.Write("Cantidad: ");
            ingredientes.Cantidad = Convert.ToInt32(Console.ReadLine());
            Console.Write("Costo: ");
            ingredientes.Costo = Convert.ToInt32(Console.ReadLine());

            return ingredientes;

        }
        public static Pizza CapturarPizza()
        {
            Pizza pizza = new Pizza();

            Console.WriteLine("Nombre de la pizza: ");
            pizza.Nombre_Pizza = Console.ReadLine();
            Console.Write("Tamaño: ");
            pizza.Tamaño = Console.ReadLine();

            return pizza;

        }

        public int costoPizzasDia(int costdia, int costpizza)
        {
            int costototal = costdia + costpizza;

            return costototal;
        }

    }
}

Después, a través de la clase del menú pasa a la clase cocina, donde genero la lista de pizzas y agrego pizzas a lstPizza y de la misma forma los ingredientes que corresponden a cierta pizza que previamente se inserta en la opcion 1 del menú:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Pizzeria
{
    class Cocina
    {
        private List<Pizza> lstPizza;

        public Cocina()
        {
            this.lstPizza = new List<Pizza>();
        }

        public void AgregarPizza(Pizza pizza)
        {
            lstPizza.Add(pizza);
        }

        public void AgregarIngredienteAPizza(string nombre_Pizza, Ingredientes ingredientes)
        {

            foreach (Pizza p in this.lstPizza)
            {
                if (p.Nombre_Pizza == nombre_Pizza)
                {
                    p.AgregarIngrediente(ingredientes);

                }
            }
        }

        //Listados
        public List<Pizza> ListarPizzas()
        {
            List<Pizza> pizzas = new List<Pizza>();

            foreach (Pizza p in this.lstPizza)
            {
                pizzas.Add(new Pizza
                {
                    Nombre_Pizza = p.Nombre_Pizza,
                    Tamaño = p.Tamaño
                }

              );

            }

            return pizzas;
        }

        public List<Ingredientes> ListadoDeIngredientesEnPIzza(String nombre_Pizza)
        {

            List<Ingredientes> IngredientesXPizza = new List<Ingredientes>();

            foreach (Pizza p in this.lstPizza)
            {
                if (p.Nombre_Pizza == nombre_Pizza)
                {
                    IngredientesXPizza = p.ListadoDeIngredientes();
                }
            }
            return IngredientesXPizza;
        }

    }
}

Después, de la misma forma que asigno la pizza, incluyo los ingredientes en mi clase Pizza a través de lstingredientes, es aquí donde pongo la restricción a través del atributo cant_ingredientes para que sean 2 o más.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Pizzeria
{
    class Pizza
    {

        private string nombre_Pizza;
        private string tamaño;
        private int cant_ingredientes;

        public int cantIngredientes
        {
            get { return cant_ingredientes; }
            set
            {
                cant_ingredientes = value;
                if (cant_ingredientes <= 1)
                {
                    throw new Exception("Debe capturar al menos 2 ingredientes.");
                }
            }
        }
        private List<Ingredientes> lstIngredientes;

        public string Nombre_Pizza { get => nombre_Pizza; set => nombre_Pizza = value; }

        public string Tamaño { get => tamaño; set => tamaño = value; }

        public Pizza()
        {
            this.lstIngredientes = new List<Ingredientes>();

        }

        public void AgregarIngrediente(Ingredientes ingredientes)
        {
            this.lstIngredientes.Add(ingredientes);

        }

        public List<Ingredientes> ListadoDeIngredientes()
        {
            List<Ingredientes> lstAuxIngredientes = new List<Ingredientes>();
            lstAuxIngredientes = this.lstIngredientes;

            return lstAuxIngredientes;

        }
    }
}

Por último la clase ingredientes donde solo coloco atributos.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Pizzeria
{
    class Ingredientes
    {
        private string nombre_Ingrediente;
        private int cantidad;
        private int costo;

        public string Nombre_Ingrediente { get => nombre_Ingrediente; set => nombre_Ingrediente = value; }

        public int Cantidad { get => cantidad; set => cantidad = value; }

        public int Costo { get => costo; set => costo = value; }
    }
}

A: Prueba esto:
public void AgregarIngrediente(ingrediente)
{
    var contIngredientes = (from i in listaIngredientes
    where i.NombreIngrediente == ingrediente.NombreIngrediente
    select i).Count();

    if (contIngrediente == 0)
    {
        listaIngredientes.Add(ingrediente);
    }

Lo que se hace aqui es una consulta Linq, que va a contar todos los elementos de la lista que son iguales al nuevo ingrediente que quieres añadir, si ese conteo da cero quiere decir que ese elemento no existe en la lista, por tanto puedes añadirlo, si ese conteo da un numero mayor a cero quiere decir que ese elemento ya existe por lo que no se va a añadir ya que estaria duplicado.
Para usar Linq debes poner en los usings:
using System.Linq;


text:
Q: How to get Android WebView font-size config from typescript side What is the correct way to determine the font-size configuration that a user has chosen in the OS settings (from within the typescript code inside the WebView)?
We have an app that is running inside an Android WebView (we're using Capacitor, Ionic and Angular, although this might be irrelevant and the info can be obtained regardless of frameworks in use). In order to provide the user a better experience we'd like to increase the size of certain elements in the screen according to the font-size setting they are using for the whole phone.
I think that the setting affects the value returned by webView.getSettings().getTextZoom() but that would need to be called from the Native Java/Kotlin side.
I'm wondering if the setting is somehow available in a property of window or document for the HTML?
We're happy to let the user choose the text size of their preference, and adjust certain elements to match that choice. We're not trying to block it nor force a size.
We're trying to achieve the opposite of this question: WebView stop using device font setting and use style specified in the HTML


text:
Q: Pascal's Triangle Problem? Guys I have been trying to solve this problem for a long time but cant seem to come up with anything. Problem is essentially a Pascal triangle but I cant figure out how to sum up a column for a specific time, t. Please help. Following is the problem:
Consider a bacterial cell constrained to a one-dimensional environment (some sort of tube, for example). This bacteria reproduce by binary fission: Every hour, each cell divides into two equal daughter cells. Immediately after the division, two daughter cells move away from each other and stop at points x + 1 and x − 1, where x is the original position of their parent cell before the fission.
The process starts with a single cell located at x = 0. We set the clock to t = 0 in the beginning of the experiment. After one hour, at time t = 1, there are two cells: at x = −1 and at x = 1, respectively. The process continues indefinitely.
Let N(t,x) be the number of cells at the position x at the time t. Derive a formula for N(t,x).
Thanks for any help !

A: It's clear that $N(t,x)=N(t,-x)$ for all $t\ge 0$ and all $x$. The recurrence is straightforward:
$$N(t+1,x)=N(t,x-1)+N(t,x+1)\;,$$
with initial value $N(0,0)=1$ and $N(0,x)=0$ for $x\ne 0$. The first few values:
$$\begin{array}{c|cccc}
t\backslash x&-4&-3&-2&-1&0&+1&+2&+3&+4\\ \hline
0&&&&&1\\
1&&&&1&0&1\\
2&&&1&0&2&0&1\\
3&&1&0&3&0&3&0&1\\
4&1&0&4&0&6&0&4&0&1
\end{array}$$
Empirically it's clear that this is just Pascal's triangle with zeroes inserted between the entries and the horizontal indexing shifted. Fix $t\ge 0$: as $x$ runs from $-t$ to $t$ in steps of $2$, we get the binomial coefficients $\binom{t}k$ for $k=0,\ldots,t$. In other words, we can see that
$$N(t,-t+2k)=\binom{t}k$$
for $k=0,\ldots,t$ and that $N(t,x)=0$ for all other values of $x$. This can be rephrased a bit more nicely: since you get $k$ from $-t+2k$ by adding $t$ and dividing by $2$, we can see that
$$N(t,x)=\begin{cases}
\binom{t}{\frac{x+t}2},&\text{if }x+t\text{ is even}\\\\
0,&\text{otherwise}\;.
\end{cases}$$
To finish the problem, you need only prove by induction on $t$ that this is actually correct.


text:
Q: Does Child Class Inherited their parent class prototype in the following example (JS) the follwoing code:
class Rectangle {
    constructor(w, h) {
        this.w = w;
        this.h = h;
    }
}

Rectangle.prototype.area = function () {
  return (this.w * this.h);
};

class Square extends Rectangle {
    constructor(w, h) {
        super(w,  h);
        // this.w = w;
        // this.h = h;
    }
}

Do I have problems with my inheritance?
I'm trying to use:
const rec = new Rectangle(3, 4);

const sqr = new Square(3);

console.log(rec.area());

console.log(sqr.area());

rec prints the correct answer but sqr print's out: NaN
I also tried maybe adding a Square prototype:
Square.prototype.area = function () {
  return (this.w * this.w);
};

but the output is:
-1
-1

so this also affected area for rec.area()

A: Since the Square constructor will be called with only one argument (since its size is equal at all sides), you need to "translate" this to a Rectangle constructor call that needs 2 arguments (width and height). Since both are equal for the square, you need to pass that single argument twice to the Rectangle constructor:

class Rectangle {
    constructor(w, h) {
        this.w = w;
        this.h = h;
    }
    area() { // Use this notation for prototype methods
        return this.w * this.h;
    }
};

class Square extends Rectangle {
    constructor(w) { // One argument...
        super(w, w); // ...Two arguments, but width == height
    }
}

let square = new Square(10);
console.log(square.area());


text:
Q: How to block multiple logins using Spring-security? When the same user log in using different browsers/machines concurrently,user is allowed to login by same credential
With Spring security concurrent session control this can be easily handled by the following configuration in security.xml file:
<concurrent-session-control max-sessions="1" exception-if-maximum-exceeded="true"/>

Problem: After successful login, user shall be blocked to login again from any other browser/machine, if he close the browser window without clicking logout button. He may be restricted for an session timeout interval.

A:
After successful login, user shall be blocked to login again from any other browser/machine, if he close the browser window without clicking logout button

Yes. This is what the <concurrent-session-control max-sessions="1" does.
If you don't want the user to be locked out you need to set max-sessions="2".
Or.
On a successful login you can set a cookie which lives forever and identifies the user browser. So when you get a login request with a different cookie but same username you can invalidate the previous user session and let the new user in.


text:
Q: Most performant way to load textures from a Spritekit texture atlas I cannot figure out how to load my textures in a brief few seconds. It is taking a monster 20+ seconds.
Initially I had my animations in separate texture atlases. They are named something like sprite_002@2x~iphone.png. When they were separate I used code similar to that in the Apple documentation:
SKTextureAtlas *atlas = [SKTextureAtlas atlasNamed:@"monster"];
SKTexture *f1 = [atlas textureNamed:@"monster-walk1.png"];
SKTexture *f2 = [atlas textureNamed:@"monster-walk2.png"];
SKTexture *f3 = [atlas textureNamed:@"monster-walk3.png"];
SKTexture *f4 = [atlas textureNamed:@"monster-walk4.png"];
NSArray *monsterWalkTextures = @[f1,f2,f3,f4];

My code was:
let names = myAtlas.textureNames as [String];
for name in names {
   myTextureArray.append(myAtlas.textureNamed(name as String));
}

For 6 animations in 6 different texture atlases w/ 250 frames each, it took about 6 seconds to load.
I was able to eliminate 60-70% of those frames and cram everything into a single texture atlas, but now I cannot get it to load in a reasonable time frame.
I have been trying code along these lines:
    for i in 1...124 {
        let name = String(format: "sprite_%03d", i);
        let texture = imagesAtlas.textureNamed(name);
        spriteTextures.append(texture);
    }

Most games iPhone games don't have a 20 second load time, so I know I am doing something wrong here.

A: Your load time will be dependent upon the size of your atlases. So if you happen to have a large number of them and they are large, it will take some time.
I've seen variations of this type of question here before.
My suggestion would be to actually change your approach to the problem. This is breaking apart the workload and doing it in the background over time. This is why many games have loading screens.
Depending on your game, you may be able to be extra sneaky and load textures (or any asset for that matter) in the background while the game is playing. More often than not, you don't need to load all your textures at the start of a game.
When I make my games, one of the first things I do is create a background loader, if I don't already have one. I then build the game around the premise of async loading of assets.
20 seconds is pretty long. But based on your description, it sounds like it would take a non trivial amount of time.


text:
Q: Send Message To Group of Tokens in Firebase I have Created a Chat App and I need to Send Notification when group messages receives,i can send notification to one device but i don't know what to do with group notification.
any idea?

A: You need to subscribe these token and send notification to that topic.
Subscribe to a topic
var registrationTokens = []
db.collection('room').document({roomId}).get().then(result => {
    registrationTokens = result.data().usersTokens // get user tokens in that chat room
})

// Subscribe the devices corresponding to the registration tokens to the
// topic.
admin.messaging().subscribeToTopic(registrationTokens, topic)
  .then(function(response) {
    // See the MessagingTopicManagementResponse reference documentation
    // for the contents of response.
    console.log('Successfully subscribed to topic:', response);
  })
  .catch(function(error) {
    console.log('Error subscribing to topic:', error);
  });

Now you can send to specific group like this
// The topic name can be optionally prefixed with "/topics/".
var topic = 'highScores';

// See documentation on defining a message payload.
var message = {
  data: {
    score: '850',
    time: '2:45'
  },
  topic: topic
};

// Send a message to devices subscribed to the provided topic.
admin.messaging().send(message)
  .then((response) => {
    // Response is a message ID string.
    console.log('Successfully sent message:', response);
  })
  .catch((error) => {
    console.log('Error sending message:', error);
  });


text:
Q: Bluetooth Headset - Windows 10 - appearing as Bluetooth hands-free I recently bough the following product from Amazon:
https://www.amazon.co.uk/gp/product/B019ZEHA36/ref=oh_aui_detailpage_o00_s00?ie=UTF8&psc=1
Essentially it works in terms of connecting etc and bonding via Bluetooth.
The issue lies with windows picking this up as a Bluetooth hands-free device, see icon below.
Hands-free ICON
This I think is part of the problem, furthermore, under sound control there is the following options, Stereo and Hands-free.
Playback devices
Please for the time being ignore that the headset is disconnected.
Under recording devices its the following: Recording devices
Putting all of this together I have the following options:

*

*use the Handsfree option but suffer with low quality sound through headset (channel 1)

*Use the Stereo as default - which means good quality sound (channel 2) - but also means that the device no longer has any Mic associated with it.

Furthermore, searching across the web, it was noted to disable hands free "under services, under device manager". However this just means that it defaults to the Stereo every time and the hands free (which includes a Mic) does not work.
I have also connected a USB blutooth device (running V10) as supposed to the internal, but still not luck. I have re-installed the device multiple times with reboots and removing it from devices.
Please can someone help here with any suggestion, I am very close to just returning this item as its not working properly...


text:
Q: Writing regular expression in PHP to wrap  with  I want to make it so that any occurance of an image gets wrapped with a link to the image source
How can I write a pattern, in PHP so that I can find these variations, which are scattered throughout text coming from the database:

In all cases, I want them to appear within an  link.

A: May I recommend using jQuery and use this snippet instead, it should be easier (and we all love jQuery to brute-force any problem ;] )
$('img').wrap( function(){ return ''; });

or is it
$('img').wrap( function(){ return ''; });

Anyways, fun times to be had, using jQuery to manipulate the DOM clientside ;)

A: preg_replace("{}ims", '', $str)
handles all non-practical cases

A: My I recommend the PHP DOM with loadHTML() instead of regex?
http://php.net/dom
http://php.net/domdocument.loadhtml


text:
Q: opening a list of .csv files and do something I have a list of 25 .csv files.  I am trying to open each file, remove the first 10 lines and then have the rest of the lines merge into one file.
I have the following code:
Files = glob.glob("filepath-*.csv")
for file in Files:

    line = open(file, 'r')
    lines = line.readlines()[10:]
    print lines

however when I try to open the file it says it has no attributes to it..
How do you open a file from a list???

A: You can use itertools.islice to write all but the first ten lines of each csv to a new file:
from itertools import islice

files = glob.iglob("filepath-*.csv")
with open("joined.csv","w") as joined:
    for f in files:
        with open(f) as temp:
            joined.writelines(islice(temp,10,None))

There is nothing in your own code that would throw an error however inefficient it may be bar you have assigned line to something else before you call readlines.


text:
Q: Why this CSS code is not working properly in all devices? I have attached 2 pictures. The iPhone 6 picture is the correct one which should be displayed in all devices. Every page should display the page as in the 1st image (that of iPhone6). It is getting distorted in iPhone 5 (image attached), android devices and in tablets
HTML Code ( using AngularJS and ionic)
<ion-view >
<ion-nav-title>

Trips

</ion-nav-title>

<ion-content class="aaaaa">

    <ion-tabs class="tabs-striped tabs-top tabs-background-dark tabs-color-energized">

        <ion-tab title="PAST TRIPS" ui-sref="previous" on-select="onPreviousTabSelected()">
        <ion-nav-view name="previous"></ion-nav-view>
        </ion-tab>

        <ion-tab title="UPCOMING TRIPS" ui-sref="future" on-select="onFutureTabSelected()">
            <ion-nav-view name="future"></ion-nav-view>
        </ion-tab>

    </ion-tabs>

{{item.starRating}}, {{item.tripDate}}

Booking Id :

{{item.tripId}}

{{item.tripStartTime}}

{{item.sourceLocation}}

{{item.destinationLocation}}

</ion-content>

CSS Code
.view-container .scroll-content.ionic-scroll.has-header.aaaaa {
  background-color: #ffffff;
}

.cartrip{
  max-width: 40px !important;
  margin-top: 15px;
  margin-left: 20px;
}

.triprepeat{
  background-color: #f1f1f1;
  border-bottom: solid 1.5px #B2B2B2;
  margin-left: 15px;
  margin-right: 15px;
  margin-top: 10px;
  margin-bottom: 10px;
}

.date-trip{
  margin-left: 80px;
  margin-right: auto;
  margin-top: -50px;
  font-size: 12px;
  color: #000000;
}

.div-box-trip{
  height: 120px;
  width: auto;
}

.bookingidtitle-trip{
  margin-left: 80px;
  margin-top: 8px;
  font-size: 11px;
  color: #A9A9A9;
}

.bookingid-trip{
  margin-left: 160px;
  margin-right: auto;
  margin-top: -20px;
  font-size: 12px;
  color: #000000;
}

.starttime-trip{
  margin-left: 250px;
  margin-right: auto;
  margin-top: -48px;
  font-size: 12px;
}

.arrowright-trip{
  height: 15px;
  width: auto;
  position: absolute;
  margin-top: -18px;
  margin-left: 315px;
}

.source-trip{
  margin-left: 80px;
  margin-top: 40px;
  font-size: 12px;
  color: #000000;
}

.dest-trip{
  margin-left: 280px;
  margin-top: -32px;
  font-size: 12px;
  color: #000000;
}

.greencircle-trip{
  height: 15px;
  width: 15px;
  margin-left: 85px;
}

.redcircle-trip{
 height: 15px;
  width: 15px;
 margin-left: 295px;
}

.dashtrip{
  border-top: dotted 1px;
  width: 170px;
}

.dashed-trip{
  margin-left: 110px;
  margin-top: -10px;
}

I am showing through two pictures how the page is getting distorted for some devices, say for example the code is working perfect for iPhone 6 but getting distorted for say iPhone5. This page should work in all mobile and tablet devices
iPhone 6
iPhone 5
I have to make it work for all devices like iPhone6 where it is working perfect. Since this page is mobile only I have not used @Media query.

A: Consider using the ionic 2 grid system which is specifically created for developing responsive grid layouts.
In your case you would need something like
<ion-grid>
   <ion-row>
      <ion-col col-2>
          Left Side
      </ion-col>

      <ion-col col-10>
         Right side
      </ion-col>
   </ion-row>
</ion-grid>

For additional margin and padding you can add some of the ionic 2 css utilities instead of writing up your own css.
 <ion-col col-10 margin-right no-padding>


text:
Q: Changing MySQL Table based on Date Using PHP Is It Possible To Change MySQL Table Column Based On Date Using PHP
For Example
I Want To Change yearsold = 19 to yearsold = 20 After 1 Year
So When It Reach 2016 yearsold become 20
Thanks :D
EDIT: I Need It To Work Automatically not Having To Visit The Page Over and Over

A: You could do 1 of 2 things.  First would be save the birthdate and calculate it every time you load the object.
The second would be to create a view that calculates the age as a column in the view, so that every time you select from the view the age is "updated" and displayed correctly.  You can check out the documentation for mysql views here.


text:
Q: Some examples of an inversion 1) Only Larry sleeps under that tree. - a standard word order
The right way to rebuild this sentence using the inversion would be
2) Under that tree sleeps only Larry.
Now I wonder whether this one is also acceptable?
3) Under that tree only Larry sleeps.
Is 3 also an acceptable inversion or is it wrong?

A: (1) is the most common word order.
(2) is comprehensible, but clumsy.
(3) is an improvement on (2).
Note that there is a context for (2), however, in a narrative register often seen in stories:

In that castle lived an evil king.
On that day began an adventure that would take him to the ends of the
  earth.


text:
Q: VStack children to fill (not expand) its parent i am trying to to make the button of an alert view fit the parent VStack. But I can only see two options:

*

*button width as is, no frame modifier. that is not ideal as the button is not wide enough

*set the frame modifier to .frame(maxWidth: .infinity). that is not ideal, because it not also fills its parent, but also makes it extend to the edges of the screen.

What I actually want is, that the VStack stays at its width and the button just fills up to the edges. No extending of the VStack. The size of the VStack is defined by the title and message, not by the button. Is this possible to achieve with SwiftUI?
Code:
Color.white
    .overlay(
        ZStack {
            Color.black.opacity(0.4)
                .edgesIgnoringSafeArea(.all)

            VStack(spacing: 15) {
                Text("Alert View")
                    .font(.headline)
                Text("This is just a message in an alert")
                Button("Okay", action: {})
                    .padding()
                    .frame(maxWidth: .infinity)
                    .background(Color.yellow)
            }
            .padding()
            .background(Color.white)
        }
    )

A: As alluded to in the comments, if you want the width to be tied to the message size, you'll have to use a PreferenceKey to pass the value up the view hierarchy:
struct ContentView: View {

    @State private var messageWidth: CGFloat = 0

    var body: some View {
        Color.white
            .overlay(
                ZStack {
                    Color.black.opacity(0.4)
                        .edgesIgnoringSafeArea(.all)

                    VStack(spacing: 15) {
                        Text("Alert View")
                            .font(.headline)
                        Text("This is just a message in an alert")
                            .background(GeometryReader {
                                Color.clear.preference(key: MessageWidthPreferenceKey.self,
                                                       value: $0.frame(in: .local).size.width)
                            })
                        Button("Okay", action: {})
                            .padding()
                            .frame(width: messageWidth)
                            .background(Color.yellow)
                    }
                    .padding()
                    .background(Color.white)
                }
                .onPreferenceChange(MessageWidthPreferenceKey.self) { pref in
                    self.messageWidth = pref
                }
            )
    }

    struct MessageWidthPreferenceKey : PreferenceKey {
        static var defaultValue: CGFloat { 0 }
        static func reduce(value: inout Value, nextValue: () -> Value) {
            value = value + nextValue()
        }
    }
}

I'd bet that there are scenarios where you would also want to set a minimum width (like if the alert message were one word long), so a real-world application of this would probably use max(minValue, messageWidth) or something like that to account for short messages.


text:
Q: Does mongoose allow for multiple database requests concurrently? I read that Mongoose will only open one connection at maximum per collection, and there's no option to change this.
Does this mean that a slow mongo query will make all subsequent queries wait?
I know everything in node.js is non-blocking, but I'm wondering whether a slow query will delay the execution of all subsequent queries. And whether there is a way to change this.

A: It does only use one connection, if you use the default method where you do mongoose.connect(). To get around this, you can create multiple connections, and then tie a model pointing to the same schema to that connection.
Like so:
var conn = mongoose.createConnection('mongodb://localhost/test');
var conn2 = mongoose.createConnection('mongodb://localhost/test');
var model1 = conn.model('Model', Schema);
var model2 = conn2.model('Model', Schema);
model1.find({long query}, function() {
   console.log("this will print out last");
});
model2.find({short query}, function() {
   console.log("this will print out first");
});

Hope that helps.
Update
Hey, that does work. Updating from the comments, you can create a connection pool using createConnection. It lets you do multiple queries from the same model concurrently:
var conn = mongoose.createConnection('mongodb://localhost/test', {server:{poolSize:2}});
var model = conn.model('Model', Schema);
model.find({long query}, function() {
   console.log("this will print out last");
});
model.find({short query}, function() {
   console.log("this will print out first");
});

Update 2 -- Dec 2012
This answer may be slightly outdated now--I noticed I've been continuing to get upvotes, so I thought I would update it. The mongodb-native driver that mongoose wraps now has a default connection pool size of 5, so you probably don't need to explicitly specify it in mongoose.


text:
Q: How to access Child component state and lifecycle methods and validate in React with Jest+Enzyme? Need help with enzyme for testing. I have checked here but it did not help: How does one access state on a nested React component wrapped by an HOC?
Here is my problem:
How can I check function called or not and state of Child component? I also need to check lifecycle, so I used mount of parent component, but haven't done that yet.
I used below when I rendered one component:
expect(searchWrapper.find('select [selected]').val()).to.equal('someId'),
but with mount, this is not working, as it complains searchWrapper.find(...).val is not a function which I believe is a cheer IO and it worked with render only. So what will be the proper way for me?
What I intend to do: On child select change, check (and/or match):

*

*child func is called once

*parent func is called once (called inside 1.)

*parent state

*child state

*lifecyle methods like componentWillReceiveProps and componentDidMount etc

*Result rendered output validation, also including some of the above.

Component is like

class ParentWrapper {
    // state and other functions and lifecycle methods
    render(){
        ....
        <SearchWrapper {...props}/>
        <ResultWrapper {...props}/>
    }
}

class SearchWrapper {
    // state
    // lifecycle methods
    // functions
}

and same for ResultWrapper.
Summarizing it again with some code:
I want to access state and other objects of Child node, just like we can do with root. Also access rendered objects like selected option from the select menu, for example.

// state is not a function, as it has to be called for root only, then whats the alternative
expect(parentWrapper.find(SearchWrapper).state().searchId).to.equal('someValue');

// Below also did not work, it worked when I tested SearchWrapper individually using render()
// which is a CheerIO function, but I need to use mount of parent for whole component testing
// and inter-component interactions

searchWrapper.find('.form1 select').simulate('change', {target : {value : 'someValue'}});
// sinon spy on change is triggered

expect(searchWrapper.render().find('select [selected]').val()).to.equal('someValue');
// AssertionError: expected undefined to equal 'someValue'


text:
Q: How to maximize microcontroller temperature? I need to test how hot a specific microcontroller can get in different situations. The goal is to have the microcontroller heat up as much as possible just by using it.
I was thinking I'd need to

*

*make the microcontroller calculate something very expensive, maybe the factorial of a million or something like that.

*maximize load on output pins (without exceeding specifications of the controller). Maybe just simple resistors connected to ground?

Does this work? Is there anything else I need to consider in order to maximize the temperature? Thank you!

A: *

*Frequency:
You should run your microcontroller at the maximum allowed frequency. Most losses occur while switching a FET.

*Voltage:
You should run at maximum voltage

*Peripherals:
Turn on and run all peripherals, like UART, SPI, ADC

*Power output:
Either drive all remaining pins high, or switch them as fast as possible. You'll have to test what consumes more power.
Either way limit the current via a resistor

*Co Processors:
Keep all of them busy, if any are available. Like Floating Point Units

*RAM:
Read and Write data to RAM and Flash
7.ALU:
Keep the ALU busy, this is easy as long as you don't use any sleep states

A: For microcontrollers power consumption, thus heat, is generally most dependant on peripherals, clock and voltage. It is dependant a little bit on what instructions the CPU is performing, but it will be very hard to make any correlation. For example, I run a small test of a PIC16F690 (just applying power to the chip with internal FRC 8MHz oscillator) and measured the current consumption of these 2 main loops:
while(1);

0.783mA @ 3.3V no optimizer
uint8_t i = 0;
while(1) { i++; }

0.735mA @ 3.3V no optimizer
0.857mA @ 3.3V with optimizer
What I take from this is that the i++; instruction does consume more power than branching, but some other instructions may not (as the non optimized version has 2 bogus MOV instructions following the add). Therefore it's a highly empirical process in determining what calculation is really 'heavy' electrically as it's very architecture dependent.
Therefore, the following tips I can give are the opposite of what is applied for lower power consumption (e.g. battery operated devices):
1) Run the MCU at the highest clock speed & disable any sleep/idle systems (if applicable)
2) Run the MCU at the highest allowed voltage (like 3.6V)
3) Enable all peripherals at the highest clock possible
4) Have your GPIO system drive currents at the maximum current specification. The drivers of a microcontroller aren't that strong. At e.g. 4mA the output-high voltage may be down by as much as 0.3V or more. If you have 30 I/Os driving 4mA laods, it will add up to 36mW.
Obviously the worst-case is a GPIO short (e.g. 20mA short circuit current at 3.6V = 72mW), but that may not be realistic and damage the MCU or I/O pin at some point.
5) Increase ambient temperature as much as possible (e.g. the ambient temperature limit for your product). Generally electronics will consume more current at +85C than at +20C. The difference can easily be in the order of 10% across temperature range.
You may want to look up  the specific electrical specs for your microcontroller. Many vendors will have very comprehensive details what affects power consumption, because generally you will want to look up those facts in order to lower the power consumption for battery applications.


text:
Q: Remove background from sprite sheet after splitting I am using libgdx to implement a Parallax background. Now I need to show some animated object over the background. I downloaded a sprite sheet(with images of objects on white background), and split it using TextureRegion.split() method. But when I draw the objects to screen, white background is shown along with the object as in this image:
I tried using batch.enableBlending() but it didn't work. Is there any way to resolve this issue? Or should I code only using individual sprites with transparent background? Here is a brief code snippet :
public class Animator extends Actor{
        int FRAME_COLS = 3, FRAME_ROWS = 3;

        Animation<TextureRegion> eagleAnimation;
        Texture eagleSheet;
        float stateTime;

        Animator(Texture sheet) {
            eagleSheet = sheet;
            TextureRegion[][] tmp = TextureRegion.split(eagleSheet, eagleSheet.getWidth()/FRAME_COLS,
                    eagleSheet.getHeight()/FRAME_ROWS);
            TextureRegion[] eagleFrames = new TextureRegion[FRAME_COLS*FRAME_ROWS];

            int index = 0;
            for(int i = 0; i < FRAME_ROWS; i++) {
                for(int j = 0; j < FRAME_COLS; j++) {
                    eagleFrames[index++] = tmp[i][j];
                }
            }

            eagleAnimation = new Animation<TextureRegion>(0.09f, eagleFrames);
            stateTime = 0f;
        }

        @Override
        public void draw(Batch batch, float parentAlpha) {
            stateTime += Gdx.graphics.getDeltaTime();

            TextureRegion currentFrame = eagleAnimation.getKeyFrame(stateTime, true);
            batch.enableBlending(); // doesn't work
            batch.draw(currentFrame, 250, 250, 264, 264);

        }

    }

This is where I call above class from :
    public class GameScreen implements Screen {

        MyGdxGame game;

        Texture eagleSheet;
        OrthographicCamera camera;
        Array<Texture> layers;
        Stage stage;

        public GameScreen(MyGdxGame game) {
            this.game = game;
            stage = new Stage(new ScreenViewport());
            camera = (OrthographicCamera) stage.getViewport().getCamera();

            layers = new Array<Texture>();

            for(int i = 1 ; i <= 6; i++) {
                layers.add(new Texture(Gdx.files.internal("parallax/img" + i + ".png")));
            }
            ParallaxBackground parallaxBackground = new ParallaxBackground(layers);
            parallaxBackground.setSpeed(1);
            parallaxBackground.setSize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
            stage.addActor(parallaxBackground);

            eagleSheet = new Texture(Gdx.files.internal("eagle.png"));
            Animator animator = new Animator(eagleSheet);
            animator.setSize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
            stage.addActor(animator);

        }

        @Override
        public void render (float delta) {
            Gdx.gl.glClearColor(1, 0, 0, 1);
            Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

            stage.act();
            stage.draw();

        }

        @Override
        public void dispose () {
            stage.dispose();
        }

        @Override
        public void show() {}

        @Override
        public void hide(){}

        @Override
        public void resume(){}

        @Override
        public void resize(int x, int y){}

        @Override
        public void pause(){}

    }

A: Best and easiest way is to use an image editor to make its background transparent before using the image in the game.
I use GIMP for that.


text:
Q: Type of first parameter in object of methods I have a type like this
type d = {
  (e: 'edit', value: boolean): void;
  (e: 'download', value: boolean): void;
  (e: 'delete', value: boolean): void;
}

I want to set the type of a function, which will accept only 'edit' | 'download' | 'delete' i.e. all the e values of type d.
e.g.
function myFunc(e: ??what type??) {
}
myFunc('edit'); // valid type
myFunc('some') // invalid type

A: Try constructing your callback type by using the Actions instead.
type Action = "edit" | "download" | "delete";
type Callback = (e: Action, value: boolean) => void;

Now you can assign the type
function myFunc(e: Action) { ... }

A: The problem here is that d is an overloaded function type. Normally, you could use the Parameters utility type to get the type of parameters of a function easily. But Parameters only returns the type of the last overload.
But we can work around this limitation by creating our own utility type which supports N overloads.
type OverloadedParameters<T> =
    T extends { (...args: infer R1) : any; (...args: infer R2) : any; (...args: infer R3) : any ; (...args: infer R4) : any } ? [R1, R2, R3, R4] :
    T extends { (...args: infer R1) : any; (...args: infer R2) : any; (...args: infer R3) : any } ? [R1, R2, R3] :
    T extends { (...args: infer R1) : any; (...args: infer R2) : any } ? [R1, R2] :
    T extends (...args: infer R) => any ? [R] : any

OverloadedParameters accepts up to 4 overloads. You can expand it to as many overloads as you want. Just follow the pattern.
We now get a tuple containing all the parameter types of the overloaded function d. All that's left to do is to index it with number to get a union of all the parameters and then index it with 0 to get the first element of each union element.
function myFunc(e: OverloadedParameters<d>[number][0]) {}

myFunc('edit') // ok
myFunc('some') // Error

Playground


text:
Q: Laravel doesn't import/read public source files (css/js) I'm working on an external project. The application is already written and I need to add some functionalities. That's why I can't edit the way they import CSS and js files in the code. Unfortunately, I can't access the js and CSS files at my localhost
Importing like:
<script type="text/javascript" src="{{ asset('js/search-form/range-slider.js') }}"></script>
<script type="text/javascript" src="{{ asset('js/provider-search.js') }}"></script>
<script type="text/javascript" src="{{ asset('js/search-form/show-detail.js') }}"></script>
<link rel="stylesheet" href="{{ asset('css/slider-custom.css') }}">
<script src="{{asset('/js/scripts.js')}}"></script>

In my browser I see following errors:
GET http://127.0.0.1:8000/js/tooltipster.bundle.min.js net::ERR_ABORTED 404 (Not Found)

and that for every js/css file.. all my files are located at
public/css/name.css
public/js/name.js
public/js/init/name.js
public/js/search-form/name.js

The links to the sources seem right, so I think it's something to do with authorities but I'm very new in Laravel.

A: try this:
<link rel="stylesheet" src="{{ URL::asset('css/name.css')}}"></link>
<script src="{{ URL::asset('js/name.js')}}"></script>
<script src="{{ URL::asset('js/init/name.js')}}"></script>
<script src="{{ URL::asset('js/search-form/name.js')}}"></script>

A: For Javascript:
<script type="text/javascript" src="{{ URL::asset('js/search-form/range-slider.js') }}"></script>
<script type="text/javascript" src="{{ URL::asset('js/provider-search.js') }}"></script>
<script type="text/javascript" src="{{ URL::asset('js/search-form/show-detail.js') }}"></script>
<script type="text/javascript" src="{{ URL::asset('js/scripts.js') }}"></script>

Make your directory structure is like this for JS:
/public/js/search-form/range-slider.js
/public/js/provider-search.js
/public/js/search-form/show-detail.js
/public/js/scripts.js

For CSS:
<link href="{{ asset('css/slider-custom.css') }}" rel="stylesheet" type="text/css" >

Make your directory structure is like this for CSS: /public/css/slider-custom.css


text:
Q: How do you learn a new skill/framework/technology? I need to be able to contribute to a relatively large Adobe AIR project and I'm starting from scratch with this technology. What's the best way to go about it?
I usually get a good book/tutorial and work my way through it but this time it seems there's just too much to learn for this to be feasible within a reasonable time frame. I would need books on Actionscript, FLEX, etc...
Do you know of any good resources that might be useful for this particular case?
How would you go about it if you were in my shoes?

A: I just had to do something similar.  If you can afford it (or, get your company to pay for it), try doing a training class.  I did one by Figleaf software a couple months ago and it really helped.
As for books, I hear the Essential Actionscript 3 book is good (I have the one for AS2 and it's quite good).  Flex is really just the SDK.  You'll be doing most of your work in AS3 and MXML.
Another really good thing to do is download the SDK and start playing with it.  Think of a couple small apps to do, then write them in Flex.  I did this at work (wrote a couple util Apps in Flex to learn it).  I find the best way to learn is to do it, and the SDK is free so there shouldn't be anything stopping you.

A: Hello World for AIR, then progressively add detail.
Aggressively use any communities out there.
Blog about your experience.  One day you will help someone else.
Today you are learning, tomorrow you are teaching.

A: *

*I download samples from the Internet, and run them, mess with them, try to change them and understand how they work.

*I subscribe to blogs on the topic and do samples, try to understan the stuff people write about.

*And I do samples :)
So I basically learn from the top - down. First I get the general sense of the technology, and then I drill down with the samples to the parts that I find interesting. Works pretty well. :)

A: I usually find online tutorials are the best way to go. They are more to the point than books, so it's usually quicker to get up to speed. And don't limit yourself to a single resource. I've never had problems finding enough tutorials through our friend google.
I have no knowledge about Adobe AIR though. I assume your customer knows you're a noob too? ;D

A: I'm a big advocate of active learning, which is described in detail, here. Essentially, when you are trying to learn a new technology: read about it, discuss it with your peers, teach it to people who are even newer to the technology, and most importantly, get your hands dirty.
A perfect example of how you can learn new things is by getting involved with a community such as stackoverflow, or a discussion forum based around what you would like to learn (http://www.adobe.com/devnet/air/), or even by contributing to an open-source project.
Of course, none of the above is as effective as trying new things out. In order to learn new technologies (in my honest opinon), it is best to dive in "head-first" and try things out.


text:
Q: Warning thrown by Python with inheritance of TestCase - 'Need more values to unpack' In Django unittest, I am inheriting from a custom class to provide some generic helper functions for all TestCases. The custom class then inherits from TestCase (from django.test). Code look like this:
class APITest(TestManager):

    def setUp(self):
        self.User, self.api_client = super(APITest, self).setUp()

Test Manager looks like this:
class TestManager(TestCase):
    def setUp(self):
        # do some stuff

Warning is shown on the call to super(APITest, self).setUp()- Need more values to unpack
The goal of having TestManager inherit from TestCase as well is to give it access to TestCase assert methods (to collect a bit more information on test results).
The code still runs fine, yet this warning makes me worry if this implementation is correct or can be improved. Also i dont understand the error, since the call to super still works and returns 2 values.
NOTE: Initially, TestManager did not inherit from TestCase and no warning was shown.
So it's really a 2 part question: Why is this error occuring? Is there a design flaw present here which can be improved?

A: If you want to make a generic setup to your tests, you could add a class method to your TestManager called setUpClass like this:
class TestManager(TestCase):
    @classmethod
    def setUpClass(cls):
        # generic setup here.

class APITest(TestManager):
    def setUp(self):
        # specific (and additional) setup here.

the same logic works for tearDown and tearDownClass.
Regerding your design ...
Just inherit APITest from TestManager:
class APITest(TestManager):
    def setUp(self):
        # do some stuff

In the end, that's the purpose of TestManager, right?  Make its functions available to the other tests.
The class APITest will have the methods from TestCase too, since TestManager inherits from it.


text:
Q: How should we add an instantiation to an existing variable? I have written an Analyzer that correctly detects uninstantiated collections. Now I'm writing the appropriate CodeFixProvider that will give the option to instantiate it.
When I execute my code and look at the provided fix, it would simply remove the identifier and only keep the type. Where did I go wrong in my approach?

public async Task<IEnumerable<CodeAction>> GetFixesAsync(Document document, TextSpan span, IEnumerable<Diagnostic> diagnostics, CancellationToken cancellationToken)
{
    var root = await document.GetSyntaxRootAsync(cancellationToken);
    var token = root.FindToken(span.Start);
    document.TryGetSemanticModel(out var semanticModel);
    var statement = token.Parent.Parent as VariableDeclarationSyntax;

    // Construct variable declaration
    var declarator = new SeparatedSyntaxList<VariableDeclaratorSyntax>();
    var identifier = statement.Variables[0].Identifier;
    var newType = semanticModel.GetTypeInfo(statement.Type).Type;
    var newObject = SyntaxFactory.ObjectCreationExpression(type: SyntaxFactory.ParseTypeName(newType.Name));
    var equalsClause = SyntaxFactory.EqualsValueClause(newObject);
    declarator.Add(SyntaxFactory.VariableDeclarator(identifier, null, equalsClause));

    var newStatement = SyntaxFactory.VariableDeclaration(statement.Type, declarator);
    var newRoot = root.ReplaceNode(statement, newStatement);

    return new[]
    {
        CodeAction.Create("Instantiate collection variable", document.WithSyntaxRoot(newRoot))
    };
}

A: You have to remember that all types in Roslyn are immutable. That means that even operations like Add() don't actually modify the object they're called on, they return the modified object.
This means that after Add(), you have to work with the returned value, not the original object.
If you modify your code to the following, it will work:
declarator = declarator.Add(SyntaxFactory.VariableDeclarator(identifier, null, equalsClause));


text:
Q: Android SDK Zip - Windows 64bit Home Variable I'm using the android_sdk.zip version, since I don't feel comfortable using installers on Windows systems. However, I understand that I need to set the Home variable in order for the SDKManager.exe to run properly. I tried another method posted on stackoverflow, but if I do that, then both Eclipse and Netbeans, won't find Java anymore.
"C:\Program Files\Java\jdk1.6.0_25\bin';'"
Any ideas?
Thanks!

A: I believe there may be a bug in the installer for Windows, as I haven't seen it work properly at detecting a JDK on Windows 7 at all.
If you are planning on developing in Eclipse, it isn't even required.  You'll save yourself a lot of time and headache if you just download and install the SDK zip file (instead of the installer EXE).

*

*Download and unpack this file somewhere on your machine

*Install the ADT plugin into Eclipse

*Point ADT to the location you unzipped the SDK in Preferences

HTH


text:
Q: Running D3 in node.js, what am I missing? Selecting an item with d3.select('#chart') doesn't work, even if I create the globals window and document.
Selecting it manually with document.querySelector('#chart') seems to work somehow.
jsdom = require('jsdom').jsdom
document = jsdom('

')
window = document.parentWindow

d3 = require('d3')
data = [4, 8, 15, 16, 23, 42]

x = d3.scale.linear().domain([0, d3.max(data)]).range([0, 420])

//works
chartDiv = document.querySelector('#chart')
d3.select(chartDiv).selectAll("div").data(data).enter().append("div").style("width",(d) -> x(d) + "px").text((d) -> d)

//doesn't work
d3.select('#chart').selectAll("div").data(data).enter().append("div").style("width",(d) -> x(d) + "px").text((d) -> d)

Is there something missing? :\

A: It seems logical that d3.select('#chart') does not work in your case, because the div you're aiming at is not on the current page.
You're loading some html as a string with jsdom, and try to replace the window variable to point at this new page.
But changing the window variable in your scope doesn't affect the d3 internal selectors. That's why you achieve to select your div with document.querySelector('#chart') and not directly d3.select('#chart')
As referenced in this post, you can make a selection on body, and then use subselections:
{jsdom} = require('jsdom')
d3 = require('d3')

# make a d3 selection on the new page body
document = d3.select(jsdom("""

  """).body)

data = [4, 8, 15, 16, 23, 42]

x = d3.scale.linear().domain([0, d3.max(data)]).range([0, 420])

# make a subselection within the body
d3.select('#chart')
  .selectAll("div")
  .data(data)
  .enter()
  .append("div")
  .style("width",(d) -> x(d) + "px")
  .text((d) -> d))


text:
Q: How to set a cardview drawable background? How to solve this question?
holder.cardView.setBackgroundResource(R.drawable.in_message_bg);

A: Try this
card.setCardBackgroundColor(R.drawable.circle)

or You could try via xml
 <android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        card:cardBackgroundColor="#ff00ff"
        card:cardElevation="4dp">

Hope this works.


text:
Q: .Net MAUI WinUI push notification opening new instance Every click on a push notification received opens a new instance of the app.
The documentation and many other samples that I found use the following code:
protected override void OnLaunched(LaunchActivatedEventArgs e)
    {
        Frame rootFrame = Window.Current.Content as Frame;

        // Do not repeat app initialization when the Window already has content,
        // just ensure that the window is active.
        if (rootFrame == null)
        {
            // Create a Frame to act as the navigation context and navigate to the first page.
            rootFrame = new Frame();

            rootFrame.NavigationFailed += OnNavigationFailed;

            if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
            {
                //TODO: Load state from previously suspended application.
            }

            // Place the frame in the current Window.
            Window.Current.Content = rootFrame;
        }

        if (rootFrame.Content == null)
        {
            // When the navigation stack isn't restored navigate to the first page,
            // configuring the new page by passing required information as a navigation
            // parameter.
            rootFrame.Navigate(typeof(MainPage), e.Arguments);
        }

        // Ensure the current window is active.
        Window.Current.Activate();
    }

But this is not working for me. The following line is causing a NullReferenceException on Window.Current.Content.
Frame rootFrame = Window.Current.Content as Frame;

I also noticed that my App class is inheriting from MauiWinUIApplication, and I think this is the point. Maybe this MauiWinUIApplication has a different way to deal with this problem but I can't find:
public partial class App : MauiWinUIApplication

How to prevent opening new instance every time a push notification is clicked?
I'm using:
Visual Studio Community 2022 17.4.0,
Maui .Net 6
Thanks!

A: The default behavior of WinUI in .Net Maui is to allow multiple instances of your app to run which will give us a lot of problems for various reasons such as a SQLite database, or deep linking etc. And this is known issue that's being tracked in Simplify and make more robust the process for Single-instance WinUI apps.
As an alternative workaround, you can refer to Making the app single-instanced  on how to make the app single-instanced which will prevent opening new instance every time a push notification is clicked.


text:
Q: Loading a block from a controller in magento, cache issue? I have two methods inside my controller i call to get html for various ajax updates.
    protected function _getDemoShippingMethodsHtml()
    {
        $layout = $this->getLayout();
        $update = $layout->getUpdate();
        $update->load('checkout_onepage_demoshippingmethod');
        $layout->generateXml();
        $layout->generateBlocks();
        $output = $layout->getOutput();

        return $output;
    }

    protected function _getSelectedDealerHtml()
    {
        $layout = $this->getLayout();
        $update = $layout->getUpdate();
        $update->load('checkout_onepage_selecteddealer');
        $layout->generateXml();
        $layout->generateBlocks();
        $output = $layout->getOutput();

        return $output;
    }

During one request to my controller if i call only one of these methods it loads the block as expected. The problem comes in where i try to call both of these function during one request. Which ever method is called first outputs the expected html, and the second method call outputs the exact same html as the first.

A: In your block class that is used create an empty pseudo-constructor
protected function _construct() {}

A: try use clean cache programatically
Mage::app()->cleanCache();
Clear Magento cache


text:
Q: npm formidable install - getting errror trying to install formidable JS library but having some install trouble,
it seems like  https://registry.npmjs.org/formidable is down, and using isup.me, the registry site seems to be down completely = can anyone else confirm this as the problem or is it something that I am doing wrong on my side?
THanks! here is the error log from console
  ^C[~/Documents/Projects/moocs/starup engnineering/nodetutorial]$npm install formidable
    npm http GET https://registry.npmjs.org/formidable
    npm http GET https://registry.npmjs.org/formidable
    npm http GET https://registry.npmjs.org/formidable
    npm ERR! Error: connect ECONNREFUSED
    npm ERR!     at errnoException (net.js:878:11)
    npm ERR!     at Object.afterConnect [as oncomplete] (net.js:869:19)
    npm ERR!  { [Error: connect ECONNREFUSED]
    npm ERR!   code: 'ECONNREFUSED',
    npm ERR!   errno: 'ECONNREFUSED',
    npm ERR!   syscall: 'connect' }
    npm ERR!
    npm ERR! If you are behind a proxy, please make sure that the
    npm ERR! 'proxy' config is set properly.  See: 'npm help config'

    npm ERR! System Darwin 12.4.0
    npm ERR! command "/usr/local/Cellar/node/0.10.3/bin/node" "/usr/local/bin/npm" "install" "formidable"
    npm ERR! cwd /Users/TheGiantSpider/Documents/Projects/moocs/starup engnineering/nodetutorial
    npm ERR! node -v v0.10.3
    npm ERR! npm -v 1.2.17
    npm ERR! syscall connect
    npm ERR! code ECONNREFUSED
    npm ERR! errno ECONNREFUSED
    npm ERR! stack Error: connect ECONNREFUSED
    npm ERR! stack     at errnoException (net.js:878:11)
    npm ERR! stack     at Object.afterConnect [as oncomplete] (net.js:869:19)
    npm ERR!
    npm ERR! Additional logging details can be found in:
    npm ERR!     /Users/TheGiantSpider/Documents/Projects/moocs/starup engnineering/nodetutorial/npm-debug.log
    npm ERR! not ok code 0

A: Try this:
npm config set registry="http://registry.npmjs.org/"

It worked for me.


text:
Q: url("#{resource[...]}") in CSS files do not work in JSF 1.2 I am trying to add font-awesome to a JSF 1.2 project.
I edited all fonts in the font-awesome css files to be like
@font-face {
    font-family: 'FontAwesome';
    src: url("#{resource['fonts/fontawesome-webfont.eot']}?v=4.3.0");
    src: url("#{resource['fonts/fontawesome-webfont.eot']}?#iefix&v=4.3.0")
        format('embedded-opentype'),
        url("#{resource['fonts/fontawesome-webfont.woff2']}?v=4.3.0") format('woff2'),
        url("#{resource['fonts/fontawesome-webfont.woff']}?v=4.3.0") format('woff'),
        url("#{resource['fonts/fontawesome-webfont.ttf']}?v=4.3.0")
        format('truetype'),
        url("#{resource['fonts/fontawesome-webfont.svg']}?v=4.3.0#fontawesomeregular")
        format('svg');
    font-weight: normal;
    font-style: normal
}

But it's not working. I did the same to a JSF 2.2 project and it's working fine. Am I accessing the resources folder correctly, and if yes, what could be the problem?

A: JSF 1.2 doesn't support <h:outputStylesheet> nor #{resource}. Those are JSF 2.x only.
Use <link> and hardcode the url() paths.

Beware: many many things were done differently and awkwardly in the jurassic JSF 1.x. If possible, migrate it to JSF 2.x as soon as possible. See also Migrating from JSF 1.2 to JSF 2.0. If not possible, make sure that you consult specifically JSF 1.x resources and not JSF 2.x ones while looking for answers.


text:
Q: A word or phrase to describe events that happen alongside major historical events I am looking for a word or phrase that could be used to describe events that happen in at the same time as major historical events.  Examples include the darkness that occurred during the crucifixion of Jesus Christ, and the comet that appeared in the sky after the assassination of Julius Caesar.  The best I could come up with is omen, but I don't think that is correct.
EDIT: After reading a comment, I see that I failed to describe that I am looking for a word in the context of these events being perceived to be related, as if the comet was some sort of a way to show the importance of what had just happened.

A: They are coincident events.
From MW dictionary:

Simple Definition of coincident : happening at the same time
the hard economic times and the
coincident increase in crime were a double strain on the city's social
services

Common synonyms are simultaneous and synchronous. Also, contemporary, though a synonym, is more of an approximation.

A: The fact that two events are coincident or concomitant doesn't mean anything per se, your question, as far as I can understand, is about the relationship between the main event (Ceaser's death for instance) and the minor accompanying event (the appearance of a Comet).
Crucifixion darkness and  Caesar's Comet are symbolic events in the sense that they help highlight the historical/religious  importance of the main events they are related to:

*

*representing things by means of symbols or of attributing symbolic meanings or significance to objects, events, or relationships. (Wikipedia)

For instance:

*

*The Comet became a powerful symbol in the political propaganda that launched the career of Caesar's great-nephew (and adoptive son) Augustus.

A recent symbolic event,
Lightning bolt hit Vatican  after Pope Benedict XVI 's shock resignation

A: To me omen precedes the event associated with it.
When something happens alongside or immediately following an important event otherwise would be a symbol of the import.
Additionally, the event following or extending the duration could also mark, validate, endorse, authenticate, manifest, and indicate.

A: concomitant
Merriam-Webster

Simple Definition of concomitant: happening at the same time as something else
Full Definition of concomitant:  accompanying especially in a subordinate or incidental way

Cambridge dictionary

something that happens with something else and is connected with it

Oxford dictionaries

A phenomenon that naturally accompanies or follows something

A: Portent (noun) : prophetic indication or significance (Merriam-Webster) —this definition is referring to the abstracted process, although the word is often used as a concrete noun (for instance, in the language of describing beliefs in medieval Christianity, among other religious belief systems, and actually Halley's Comet is a prime example of how portents were used to reinforce the authenticity of imbuing coincidentally synchronous events with symbolic meaning—look up the symbolic interpretation of Halley's Comet in the death of England's King Harold II during the Norman conquest of 1066, about which the Anglo-Saxon Chronicle states: the comet was "a portent such as men had never seen before was seen in the heavens." -https://www.history.com/news/a-brief-history-of-halleys-comet-sightings
Hope this helps!


text:
Q: Sveltekit: Have '@' symbol in route name without using named layouts I have a route in my src/routes folder called [user]@[server]
After upgrading sveltekit it throws an error: 'Named layouts not allowed in directories'.
The syntax for using named layouts uses the '@' symbol, but I want to have a literal '@' symbol in my route, that the user has to type into their url bar in the browser. Is there any way to do that in the newest version of sveltekit?

A: For it to work it needs to be url encoded.
So @ becomes %40
In your case the file's name might be something like: [user]%40[server].svelte


text:
Q: Data not being sent via JQuery/AJAX i am trying to send the contents of an input box to a php file via JQuery/AJAX. When the script runs, all seems well, however, I receive nothing back. The following is my ajax call;
$(document).ready(function(){

$("#kinaseEntry").change(function ()    {

    var kinaseEntry = $("#kinaseEntry").val();
    var dataString = "kinaseEntry=" + kinaseEntry;

    $("#waiting").show(500);
    $("#message").hide(0);
    alert(kinaseEntry);

    //Fetch list from database
    $.ajax({
        type : "GET",
        url : "post.php",
        datatype: "json",
        data:   dataString,
        success : function(datas)   {
            $("#message").show(500);
            $("#message").html(datas);
            alert(datas);
        }
    });
    return false;
});
});

I get the following result in the address bar after the script has run;

http://www.someaddress.com/test/?kinaseEntry=#

Any help will be greatly appreciated, I am only starting to familiarize with JSON.
This is the results form testing the php file
{"kinaseSKU":"ABL1","url":"https:\/\/products.beta.invitrogen.com\/ivgn\/en\/US\/adirect\/invitrogen?cmd=catProductDetail&showAddButton=true&productID=P3049","molecularWeight":"125.4 kDa","tracerSKU":"","antiSKU1":"","antiSKU2":"","bufferSKU":"","tracerConc":"","assayConc":""}

The input form looks like;
<form id="form" action="#">

To begin, start typing a Kinase:

<input type="text" size="25" name="kinaseEntry" id="kinaseEntry" />
</form>

A: var dataString = "kinaseEntry=" + kinaseEntry;

Since the problem is that you didn't receive feedback from the action url, you may want to check your post.php. Also if you are using datatype json make sure you do the following:
header("Content-type:application/json");
echo json_encode($variable); //where variable is your result

JQuery is strict on content type being received if you specify json as the datatype

A: From the docs:

The data option can contain either a query string of the form
  key1=value1&key2=value2, or a map of the form {key1: 'value1', key2:
  'value2'}. If the latter form is used, the data is converted into a
  query string using jQuery.param() before it is sent. This processing
  can be circumvented by setting processData to false. The processing
  might be undesirable if you wish to send an XML object to the server;
  in this case, change the contentType option from
  application/x-www-form-urlencoded to a more appropriate MIME type.

You are just sending a plain string, not a key/value pair. Try adding an = to your string or use a map.

A: Try this one:
$(document).ready(function(){
    $("#kinaseEntry").change(function ()    {
        $("#waiting").show(500);
        $("#message").hide(0);

        //Fetch list from database
        $.getJSON("post.php", {
            kinaseEntry : $(this).val()
        }, function (datas) {
            $("#message").html(datas);
        })

        return false;
    });
});

Seems easier for me... =] Hope this helps.. =]