text:
Q: C++ new operator Let's say I have a
class A
{
  int A1;
  void Af();
};

Then I do:
A  hA;
A* pA = new A();

now, hA is an object in the stack; I can use
hA.A1 = 52 // for example

but pA just points to class A, how is that useful or handy? (any examples please?)
second issue:
when I did A* pA = new A(); did I allocate anything in the heap? was there any malloc() in the background? if not, then why not? and how come int *p_array = new int[5] will allocate memory in the heap of 5 ints and not A* pA = new A()?

A: A  hA = new A();

leads to a compiler error. The correct way of defining a variable "on the stack" is
A ha;

but pA just points to class A, how is that useful or handful (any examples please?)

In some place in the memory, you have an object of type A, and pa points to it. If you want to set the A1 member of that object to 52, you write
pA->A1 = 52;

The why is it useful part is not a real question.

when I did A* pA = new A(); did I allocate anything in the heap?

Yes, you did. new does two things: it allocates memory and invokes the constructor.

was there any malloc() in the background?

That is unspecified, but in many implementations new is implemented via malloc

and how come int[] A = A[42] will allocate memory in the heap of 42 ints and not A pA = new A() ?

This, sir, is also a compiler error. What you meant was
int* A = new A[42];

This is the operator new[] which allocates arrays on the heap and calls constructors if necessary (in case of ints it isn't).

A: Once use for pointers to objects is when the capacity or the data quantity is unknown at compile-time.  A good example is receiving text from a User.
Will the user enter 5 characters, 10, 1k?
If my program allocates 1k and the user never enters more than 32 characters, this is a waste of space.
Another use for dynamic memory allocation is passing information between objects:
Object 1 creates a book, but is not responsible for destroying it.
Object 2 proofreads the book, generates a list of corrections, but doesn't destroy the book.
Object 3 Adds tables to the book, still doesn't destroy it.
Object 4 Saves the book, then destroys it.
Please read the "C++ FAQ" for fast answers to common C++ Questions.

A:
but pA just points to class A, how is that useful or handy? (any examples please?)

That's not the case. pA points to an A object, so *pA is an object just like hA is an object:
(*pA).A1 = 52 // for example

When you do A* pA = new A(), yes a dynamic allocation occurs. Not necessarily a call to malloc(), but something. (Ignoring uses of user defined operator new which can do anything you like)
new A() does two main things. It allocates space for the object somewhere. And if that succeeds then it constructs an object of the type you requested at that location. If the object is constructed successfully then it simply returns a pointer to the object.

A:
but pA just points to class A, how is that useful or handy? (any examples please?)

It's useful and handy because now you have the address of an instance of class A that does not exsist on the stack, but on the heap.  So it will survive if you fall out of scope(return from a function ect).  You can pass the pointer around all over the place and you instance remains

when I did A* pA = new A(); did I allocate anything in the heap? was there any malloc() in the background?

Yes Yes and yes, this is the point of the new operator.


text:
Q: Question on altenative axiom system for set theory I hope this question is not a duplicate of the following question (however it is related):
Does equality of sets follow not only from what they contain but also from what they are contained by?
Consider the following axiom:
$\forall x\forall y(\forall z \forall w (z \in x \Leftrightarrow z \in y \wedge(x \in w \Leftrightarrow  y \in z)) \Rightarrow x=y ) \quad (\overline{Extensionality})$
Does ZFC-Extenionality+$(\overline{Extensionality})$ prove Extensionality?

A: I really don't understand the intuition behind this statement.
Nevertheless, $\overline{Extensionality}$ is actually provable from ZFC - Extensionality.
Suppose we have $x, y$. Suppose that for all $z$ and $w$, $z \in x$ if and only if both $z \in y$ and also $(x \in w \iff y \in z)$.
Suppose we have some $z \in x$. By the axiom of pairing, take $w$ such that $x \in w$.
Now because $z \in x$, we see that $z \in y$ and also $(x \in w \iff y \in z)$. Because we picked $w$ such that $x \in w$, we have $y \in z$.
So $z \in y$ and also $y \in z$. Again citing pairing, take $a$ such that $y \in a$ and also $z \in a$. By separation, take $a'$ such that for all $b$, $(b \in a' \iff (b \in a \land (b = z \lor b = y)))$.
By the axiom of regularity, take $c$ such that $c \in a'$ and for all $d$, $\neg (d \in c \land d \in a')$. Since $c \in a'$, either $c = z$ or $c = y$. If $c = z$, then $y \in c$ and $y \in a'$; contradiction. If $c = y$, then $z \in c$ and $z \in a'$; contradiction. So we've reached a contradiction.
From here, it follows that $x = y$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: AttributeError: 'builtin_function_or_method' object has no attribute 'writerow i'm trying to edit only a specific set of columns of a row in a csv file for a school project but not having much luck, and am now running into the error when trying to see if using dictwriter will work as I need the last two columns im not wanting to be edited to still exist:
Traceback (most recent call last):
  File "C:\Users\nikit\PycharmProjects\C0027838_csc1034_project2_2021\main.py", line 104, in <module>
    writer.writerow = csv.DictWriter(file, fieldnames=["first_name","last_name","title","pronouns","dob","occupation"], extrasaction="ignore")
AttributeError: 'builtin_function_or_method' object has no attribute 'writerow

Here's the section of code i'm trying to get working:
if choice == "4":
    with open("mock_data.csv", newline='') as file:
        reader = csv.DictReader(file)
        client = list(reader)
    editClient = int(input("Please enter the index number of the client you wish to edit: "))
    print("Please enter the details for each of the following: ")
    for i in range(len(existing_clients[0])):
        newDetails = input("Enter new data for " + str(existing_clients[0][i]) + ": ")
        existing_clients[editClient][i] = newDetails
    changes = input("Are you sure you'd like to make these changes? Enter Yes or No")
    if changes == ("Yes"):
        # Newline fixed the spacing issue I was having
        with open("mock_data.csv",   "w+", newline="") as file:
            writer.writerow = csv.DictWriter(file, fieldnames=["first_name","last_name","title","pronouns","dob","occupation"], extrasaction="ignore")
            writer.writeheader()
            for line in client:
                writer.writerow(line)

And an example of my csv file:
first_name,last_name,title,pronouns,dob,occupation,account_balance,overdraft_limit
Garner,Coupman,Ms,Male,14/04/2022,General Manager,2200.76,2.28
Jens,Eldrid,Honorable,Male,13/11/2021,Research Associate,967.64,79.15
Enrichetta,Pinkerton,Honorable,Female,29/11/2021,Software Engineer I,1182.94,6.10
Merwyn,Abraham,Mrs,Male,23/05/2022,Associate Professor,1071.10,93.88

Cheers!
I've tried slicing but obviously that gets rid of the last two columns which i need for later in the program so if you can help me fix this or point me toward another method that would be great :)
cheers!


text:
Q: How to create a new struct and use its original value as a member of the new struct I am trying to create a new struct and use its original value as a member of the new struct. However, they both end up being the same reference (i.e. payload and payload.prev) and it causes infinite recursion in my code. I appreciate any help or hint.
package main

type Sieve struct {
    prime int
    prev  *Sieve
}

func Test(payload *Sieve, n int) {
    if payload.prime*(n/payload.prime) == n {

    } else if payload.prev == nil {
        println(n)
        // payload and payload.prev end up being the same reference
        // and it causes infinite loop
        *payload = Sieve{
            prime: n,
            prev:  payload,
        }
    } else {
        Test(payload.prev, n)
    }
}

func main() {
    var p = Sieve{
        prev:  nil,
        prime: 2,
    }

    println(2)

    for i := 2; i < 10; i++ {
        Test(&p, i)
    }
}

A: You want to update the "payload" pointer to point to the address of a new struct. Construct your new struct like this:
payload = &Sieve{
            prime: n,
            prev:  payload,
        }

A: With this code below, you are not creating a new instance of Sieve, you are setting the existing instance of Sieve to point to itself:
*payload = Sieve{
            prime: n,
            prev:  payload,
        }

If you want to push the payload one level down, you can do this:
p:=*payload
*payload = Sieve {
  prime: n,
  prev: &p}

This will first assign the contents of payload to p, and then will rewrite payload contents to point to p.
On the other hand, if you want to create a new payload pointing to the old one, use:
payload = Sieve {
   prime: n,
   prev: payload }

Then you have to return/use this new payload pointer.

A: Before overwriting the Sieve struct pointed by payload make a copy of it:
p := *payload

And now you can assign a new Sieve struct value, storing the address of the copy as its prev field:
*payload = Sieve{
    prime: n,
    prev:  &p,
}

With this change, your app runs and properly outputs the primes between 2 and 10 (try it on the Go Playground):
2
3
5
7


text:
Q: Add a tab between last number and first letter using sed I've read lots of very helpful posts about adding tabs between every number and letter, or adding/deleting tabs and spaces in other locations within a string, but I'm struggling to adapt those solutions to my current problem, so I figured it was worth adding to the stack! I have a bunch of genetic data that looks like this:
chr1    1324000 1325000tgagggtctgctg...
chr1    1318000 1319000gggactgcagctg...

etc.
Is there a way to add a tab between the last number and the first letter? The lengths of the sequences vary, so the tab isn't always going to be in the same position. Additionally, the first set of numbers don't always end in 0. However, the tab will always be immediately after the last number. I think it's going to be something like:
sed -e 's/\([[0-9]\+]\)/[\t/'

But of course this doesn't work. How can I tell sed to put a tab in this location?
Desired output:
chr1    1324000 1325000  tgagggtctgctg...
chr1    1318000 1319000  gggactgcagctg...

A: sed -E 's/([0-9])([acgtACGT])/\1\t\2/' file

works! Thank you Cyrus.

A: $ sed 's/[^0-9]*$/\t&/' file
chr1    1324000 1325000 tgagggtctgctg...
chr1    1318000 1319000 gggactgcagctg...


text:
Q: Cannot reverse a multidimensional array I have an array with this structure:
[
    {
        "id": "2644688"
    },
    {
        "id": "2644689"
    }
]

I'm trying to reverse it using array_reverse:
$reversed = array_reverse($result, true);
return $response->withJson($reversed);

but I get:
{
 "0": {
       "id": "2644688"
 },
 "1": {
       "id": "2644689"
 }
}

the order is the same, the function array_reverse just added the numerical indexes, I did something wrong?

A: You should not pass true in the second argument of array_reverse.
Try replacing your code to:
$reversed = array_reverse($result, false);

Or just:
$reversed = array_reverse($result);

The second argument is preserving original array keys. The problem with that is that JavaScript will change it's order according to the keys, so the output of the json will be:
{"1":{"id":"2644689"},"0":{"id":"2644688"}}

And JavaScript will change the order to 0,1.

A: According to array_reverse documentation. Second parameter, if set to TRUE numeric keys are preserved. Non-numeric keys are not affected by this setting and will always be preserved.
So try removing true as second parameter.
$reversed = array_reverse($result);
return $response->withJson($reversed);


text:
Q: XSLT 1.0 decimal number formatting for zero decimals and non zero decimals hi i have set of inputs as below
22.00
25.25
25.56
56.15
85

and the output to be
22
25.25
25.56
56.15
85

any ideas would be appreciated!

A: It is hard to deduce the rule from your examples. Applying the number() function to the input will produce the results you show - perhaps that is what you want.

Added:
If you want the input of 1.20 to be preserved as 1.20, then you can test for the value of input mod 1 to separate the two cases - see the demo at: https://xsltfiddle.liberty-development.net/ncnu9B7


text:
Q: Dungeon Defenders - Can't join friends' games (no attempt, nothing happens) I understand there's a bug where I can't join friends' ranked (Trendynet) games unless I am also logged into Trendynet.  This is not that.
After logging in, when I try to join a friend's game (shift+tab --> friends --> click the down arrow next to the friend's name --> Join Game), nothing happens.  It doesn't attempt to join the game, I don't get a "failed to join game" message - nothing.  However, they can all join my private game.
Does anyone know how to fix this problem?

A: Apparently, this happens when you (the player trying to join) have filters for custom games set.
To reset your filters:

*

*Log into TrendyNet

*Click "Custom Game"

*Click the "reset" button in the lower-right.

You should now be able to join friends' custom games.

Another solution that solved this intermittently for me (perhaps differing versions?) was to have all players (including the host) reverify their game-cache.
To reverify your game cache:

*

*Close out of Dungeon Defenders

*Right-click the game on Steam --> Properties --> Local Files --> Verify integrity of game cache.

Every time you do this after playing, you will get "Two files failed to validate.  They will be redownloaded," even if there's nothing wrong with your game.
However, this fixed the problem for us a few times, before we knew about the custom-games filter solution (and before I had any filters set...).

A: Do you have an update queued?  If so, quit the game and allow the update to download. That's what happened to me.


text:
Q: HIVEQL - how to write condition for JSON values I have the following data in one of the table I exported from dynamoDB:
...
SUID{
    "s": {\"profileElementType\":\"1\",\"version\":0,\"seq\":1,\"sUid\":\"15141\"}"
}
OPTED{
    "s": "{\"profileElementType\":\"2\",\"version\":0,\"seq\":4,\"value\":\"1\"}"
...

I created the hive table as follows:
CREATE EXTERNAL TABLE IF NOT EXISTS DATA_FULL (item map<string, string> )
STORED BY 'org.apache.hadoop.hive.dynamodb.DynamoDBStorageHandler'
TBLPROPERTIES ("dynamodb.table.name" = "ORIGINAL_DATA");

I wanted to understand how to write the WHERE clause in HiveQL to process such data.
I tried the following HiveQL:
SELECT * FROM DATA_FULL where item['SUID'] LIKE '%15141%';

No results.
SELECT item['SUID'],item['OPTED'] FROM DATA_FULL where
(item['OPTED'] LIKE '%\"value\":\"0\"%' or item['OPTED'] LIKE
'%\"value\":\"2\"%');

No Results (The HiveQL above tries to
 extract values from this table that has OPTED like "Value:0" or OPTED like "Value:2"

A: Changed the WHERE clause and added one more \ to the conditions.
 SELECT item['SUID'],item['OPTED'] FROM DATA_FULL where
 (item['OPTED'] LIKE '%\\"value\\":\\"0\\"%');


text:
Q: (System)Verilog bit cut out from arbitrary position I'd like to make an output bus 1 bit shorter than the input, by cutting a bit from arbitrary position, like this:
module jdoodle;
    integer i;
    reg [8:0] in;
    reg [7:0] out;
    reg [3:0] idx;

    always @*
    begin
        case(idx)
            0: out = in[8:1];
            1: out = {in[8:2], in[0]};
            2: out = {in[8:3], in[1:0]};
            3: out = {in[8:4], in[2:0]};
            4: out = {in[8:5], in[3:0]};
            5: out = {in[8:6], in[4:0]};
            6: out = {in[8:7], in[5:0]};
            7: out = {in[8], in[6:0]};
            default: out = in[7:0];
        endcase
    end

    initial begin
        in = 9'b010101010;
        for (i = 0; i < 9; i++)
        begin
            idx = i; #10;
            $display ("%x - %08b", idx, out);
        end
        $finish;
    end
endmodule

I found a way to write it in one line:
module jdoodle;
    integer i;
    reg [8:0] in;
    reg [3:0] idx;

    wire [7:0] out;
    assign out = ((in >> 1) & (16'h00ff << idx)) | (in & (16'hff00 >> (16-idx)));

    initial begin
        in = 9'b010101010;
        for (i = 0; i < 9; i++)
        begin
            idx = i; #10;
            $display ("%x - %08b", idx, out);
        end
        $finish;
    end
endmodule

But its less readable than the first, but the first is quite bad for larger buses. Is there a more elegant way to do it? Also is there standard library for verilog like std for c++, containing common modules like arbitrary rotate?
Thanks
Edit: here's the expected output:
0 - 01010101
1 - 01010100
2 - 01010110
3 - 01010010
4 - 01011010
5 - 01001010
6 - 01101010
7 - 00101010
8 - 10101010

A: You can use a loop to work on each bit:
module jdoodle #(parameter INW = 'd9)
 (
  input [INW-1:0] in,
  output[INW-2:0] out,
  input [$clog2(INW)-1:0] idx
 );
  always_comb begin
      for(int i = 0; i<INW; i++) begin
          if      (i < idx) out[i]   = in[i];
          else if (i > idx) out[i-1] = in[i];
          // do nothing if i == idx
      end
  end
endmodule


text:
Q: ¿Cómo crear un sistema de ecuaciones lineales de forma iterativa con python? estoy tratando de solucionar una ecuación diferencial ordinaria de segundo orden con valores en la frontera a través del método de diferencias finitas que sirve para discretizar la ecuación diferencial y poner la ecuación en términos de un sistema de ecuaciones lineales, sin embargo no sé como hacer que se me cree el sistema de ecuaciones de forma iterativa, agradecería si alguien puede ayudarme, dejo parte del código que he venido trabajando.
import numpy as np
from matplotlib import pyplot as plt
# se define un diccionario con la función externa y coeficientes de la ecuación diferencial; Los coeficientes A(x),B(X) Y C(X) además de la función externa f(x) tienen las claves 1,2,3 y 4 respectiviamente, hay que tener eso encuenta a la hora de quedar acceder a alguna de las funciones de coeficientes.
# dentro de la funciones lambda se puede modificar las funciones al gusto de quien edite el codigo
coefi={1:lambda x: np.sin(x),2:lambda x: np.cos(x),3:lambda x: x,4:lambda x:2*x}
cf=[(0,6),(5,10)] # se define una lista que contiene los valores en la frontera en forma de coordenada no mutable (x,y), el primer par de coordenadas (x,y) hace referencia al extremo izquierdo de la frontera y el segunda par de coordenadas hace referencia al extremo derecho de la frontera, si es necesario cambiarlos solametne modificar los valores numéricos dentro de los paréntesis
h=0.1 #tamaño de paso del proceso, modificar si se necesita
def FiniteDiferencies():
    n = int(cf[1][0] / h)
    xi = cf[0][0]
    #inicia la construcción de la matriz de coeficientes y el vector de terminos independientes
    mc=[]
    ti = []
    ti2 = []
    c1,c2,c3=0,0,0
    for e in range(n-2):
        xi=xi+h
        for ter in range(n-2):
            axi = (1 / h ** 2) * coefi[1](xi) - (1 / (2 * h)) * coefi[2](xi) #se calcula el coeficiente a
            bxi = (-2 / h ** 2) * coefi[1](xi) + coefi[3](xi) #se calcula el coeficiente b
            cxi = (1 / h ** 2) * coefi[1](xi) + (1 / (2 * h)) * coefi[2](xi) #Se calcula el coficiente c
            inxi = coefi[4](xi) #se calcula el termino indendiente
            if e==0: #verifica si está en la frontera izquierda
                f0x=cf[0][1]*-1*axi #si lo está entonces el valor de y0 paselo a la izquierda y sumelo al termino independiente
                inxi = inxi+f0x
            elif e==n-3: #verifica si está en la frontera derecha
                f0n=cf[1][1]*-1 #si lo están entonces el valor de yn paselo a la izquierda y sumelo al termino independiente
                inxi = coefi[4](xi)+f0n
            mc.append([axi,bxi, cxi,0]) #ingrese los coeficientes de la ecuación a la fila i
            ti2.append(inxi) #ingrese el valor del termino independiente al vector

A: He llegado a la solución, resulta que al hacer un análisis sobre las diferencias centradas me di cuenta que la conformación de la matriz de coeficientes del sistema de ecuaciones lineales es un sistema tridiagonal, en donde el coeficientes de las ecuaciones con diferencias centradas llenan las tres diagonales, a causa de ese análisis implementé un código que pudiera calcular y almacenar el valor de esas tres diagonales en listas diferentes, posteriormente a través de la librería de numpy se hizo uso del método diag para construir una matriz según la diagonal a la cual pertenece, posterior esa matriz la resuelvo con el método linalg.solve. Adjunto el código a continuación.
import numpy as np
from matplotlib import pyplot as plt
# Se define una lista llamada coefi en la cual cada elemento se le define una posición de la siguiente forma [0,1,2,3,...,n] y el elemento en la posición 0,1,2,3,n es un diccionario
# Nota: Un diccionario es una estructura de datos parecida a una lista con la diferencia en que los elementos no se acceden por una posición si no por una clave, es decir que un elemento está definida por una clave y el elemento
# para acceder a los elementos del diccionario se tiene que especificar la clave de la siguiente forma: diccionario[clave]
# si se quiere agregar un elemento al diccionario entonces se tiene que hacer de la siguiente forma: diccionario{elementos_anteriores,clave:dato_a_agregar}
# dentro de cada elemento de la lista coefi existe un diccionario con la función externa y los coeficientes de la ecuación diferencial; Los coeficientes A(x),B(X),C(X) Y la función externa f(x) tienen las claves 1,2,3 y 4 respectivamente, hay que tener eso encuenta a la hora de querer acceder a los coeficientes de la EDO elegida.
# Finalmente para acceder a los coeficientes de un edo en particular tenemos que hacerlo de la siguiente manera coefi[posición_de_mi_ecuacion_en_la_lista][clave_de_mi_coeficiente_dentro_del_diccionario](parámetro_a_evaluar_en_el_coeficiente_de_la_edo)
# dentro de la funciones lambda se puede modificar las funciones al gusto de quien edite el codigo
# Nota 2: Si se va a ingresar una nueva ecuación diferencial entonces debe de ingresarse un nuevo elemento a la lista coefi
# El elemento que se vaya a agregar debe de ser un diccionario que obligatoriamente debe contener 4 datos
# Esos cuatro datos corresponde a los coeficiente A(X),B(X),C(X) y la función externa f(x)
# Cada dato del diccionario debe de contener una clave de 1 a 4, en donde la clave 1 corresponde al coeficiente A(x), la 2 al coeficiente B(x)
# Así sucesivamente hasta llegar a la clave 4 que corresponde a la función externa f(x)
coefi=[{1:lambda x: 1,2:lambda x: 0,3:lambda x: -0.01,4:lambda x: -0.2},{1:lambda x: 7,2:lambda x: -2,3:lambda x: -1,4:lambda x:-x},{1:lambda x: x**2,2:lambda x: -x,3:lambda x: -1,4:lambda x:2*x}]
# cfr es una lista que contiene en cada posición un diccionario en donde hay dos elementos con una clave, el primer elemento siempre corresponderá a la frontera izquierda y el segundo elemento corresponderá a la frontera derecha
# Nota si se quiere ingresar unas nuevas condiciones de frontera para una ecuación diferencial en específico, se debe ingresar una nueva posición en la lista
# el dato de esa posición debe de tener la misma estructura que la de la primera posición de la lista
# recordar que en una lista los datos se separan por comas
cfr=[{1:(0,40),2:(10,200)},{1:(0,5),2:(20,8)},{1:(1.962,0),2:(9.265,0)}]
funcanali=[lambda x:73.4523*np.exp(0.1*x)-53.4523*np.exp(-0.1*x)+20,lambda x:(-1.783e-4)*np.exp(((1+2*np.sqrt(2))/7)*x)+7.0001783*np.exp(((1-2*np.sqrt(2))/7)*x)+x-2,lambda x:0.03862212*np.float_power(x,(1+np.sqrt(2)))+2.33412631*np.float_power(x,(1-np.sqrt(2)))-x]
# cantidad de puntos, modificar si se necesita
n=10
def Graphs(id,ls,h):
    x=np.arange(cfr[id][1][0],cfr[id][2][0]+h,h) # se llena un vector con todos los valores de x
    y=funcanali[id](x) # se calculan los valores de la función en los x calculados
    plt.plot(x,y,label="Solución analítica")
    plt.plot(x,ls,'r--',label="Solución numérica")
    plt.xlabel("x")
    plt.ylabel("y")
    plt.legend()
    plt.grid()
    plt.title("Solución numérica vs analítica")
    plt.show()
def finitediferencies(id):
    ai, di, bi, ci, yi = [], [], [], [], [] # se definen las listas que van a contener los coeficientes de las ecuaciones lineales
    xi = cfr[id][1][0] #se trae la coordenada x de la frontera izquierda
    h=(cfr[id][2][0]-cfr[id][1][0])/n # se calculan el número de puntos a econctrar la solución
    for i in range(0,n-1): # empieza el bucle iterador para la variable i
        xi=xi+h # se incrementa el valor de xi para evaluar en el punto xi
        for j in range(0,n-1): # empieza el bucle iterador para la variable j
            if i==j: # si en la diagonal principal
                c2 = (-2 / h ** 2) * coefi[id][1](xi) + coefi[id][3](xi) # entonces calcule el coeficiente 2
                di.append(c2) # y haga una lista con los elementos de la diganonal principal
            if i==j-1: # si se está en la diagonal que está por encima de la principal
                c3 = (1 / h ** 2) * coefi[id][1](xi) + (1 / (2 * h)) * coefi[id][2](xi) #calcula el coeficiente 3
                ci.append(c3) #y haga una lista de valores  de la diagonal que está por encima de la diagonal principal
            if i==j+1: #si se está en la diagonal que está por debajo de la principal
                c1 = (1 / h ** 2) * coefi[id][1](xi) - (1 / (2 * h)) * coefi[id][2](xi) #calcule el cofiente 1
                ai.append(c1) # y haga una lista de valores con los elementos de la diagonal que está por debajo de la diagonal pricipal
        ti=coefi[id][4](xi) #calculo de los bi
        if i==0: # se verifica si se está en la ecuación 1
            ti=ti-((1 / h ** 2) * coefi[id][1](xi) - (1 / (2 * h)) * coefi[id][2](xi))*cfr[id][1][1] #si está en la ecuación 1 entonces se despeja el termino para suma cn bi
        elif i==n-2: # se verifica si se está la última ecuación
            ti=ti-((1 / h ** 2) * coefi[id][1](xi) + (1 / (2 * h)) * coefi[id][2](xi))*cfr[id][2][1] # si están en la última ecuación despeja el termino para sumar con bi
        bi.append(ti) #Se ingresa bi a la lista
    matriz = np.diag(di) + np.diag(ci, 1) + np.diag(ai, -1) # se construye la matriz tridiagonal
    sol=np.linalg.solve(matriz,bi) # se soluciona la matriz tridiagonal
    print("Resultados con la aproximación centrada, para un error de h^2 y un tamaño de paso de h="+str(h))
    xi=cfr[id][1][0]
    print("x="+str(xi)+"  y="+str(cfr[id][2][1])) # se muestra el resultado inicial
    ynum=[cfr[id][1][1]]
    for r in sol: # se recorre el vector solución
        xi=xi+h # se calcula el x para el cual se obtiene una solución de y
        print("x="+str(xi)+"  y="+str(r))
        ynum.append(r) # se guardan los valores del vector solución en otra lista para poder gráficar
    print("x=" + str(cfr[id][2][0]) + "  y=" + str(cfr[id][2][1])) #se muestra el resultado final
    ynum.append(cfr[id][2][1])
    Graphs(id,ynum,h) # se llama a una función que grafica las dos soluciones, si no se tiene función analítica para la función escogida, comentar esta línea con #

try:
    print("Actualmente hay "+str(len(coefi))+" ecuaciones diferenciales ingresadas")
    print("Las funciones están en una lista que van desde las posición 0 hasta "+str(len(coefi)-1)+", el id será esa posición en la lista")
    id=int(input("Ingrese el id de la ecuación diferencial para la cual se solucionará sobre un intervalo"))
    finitediferencies(id)
except:
    print("""Ha ocurrido un error al ejecutar el código, revisa si la información que ingresaste es válida""")


text:
Q: Java 8 - Initilize a List in one line difference between Arrays.asList and Stream.of I want to create a list of city names. And I know two ways.
List<String> cities = Stream.of("Paris", "London", "New York", "Tokyo").collect(Collectors.toList());

List<String> cities = Arrays.asList("Paris", "London", "New York", "Tokyo");

What is difference between Stream.of(..).collect(..) and and Arrays.asList(..)?

A: *

*Stream.collect() will return a List<> with non-fixed size (with the current implementation of toList())
List<String> cities = Stream.of("Paris", "Tokyo").collect(Collectors.toList());
cities.add("foo"); // OK

In the case of create a basic List it's useless to use Stream, use them when you need to make operation before collecting data, like filter, map, ...

*Arrays.asList()will return List<> of fixed size : see Documentation
List<String> cities = Arrays.asList("Paris", "London", "New York", "Tokyo");
cities.add("bar"); // NOK : java.lang.UnsupportedOperationException

This can be used when you quickly need a List of elements, for iteration, or other simple thing but no more, then use a implementation of List of go back to point 1.

The construction .collect(Collectors.toCollection(ArrayList::new)); would guarantee the returned list to be mutable, as for toList there are no guarantees on the type, mutability, serializability, or thread-safety of the List returned


text:
Q: Conditional page layout with ASP.net MVC I would like to respond to a web request with a partial view if the request is an Ajax request. If its not an Ajax request I would like to wrap the partial in a layout and deliver a full page.
What's the best way to do this?
Cheers, Ian.

A: Something like this should work:
if(request.IsAjaxRequest()) {
    return PartialView();
} else {
    return View();
}

A: You can create two copies of the Controller method, one for HTTP GET and one for HTTP POST.  If all your AJAX uses POST, that'd handle it.
    [HttpGet]
    public ActionResult Index()
    {
        // Do something
        return View();
    }

    [HttpPost]
    public PartialViewResult Index()
    {
        // Do something
        return PartialView();
    }

Alternatively, in the MVC3 Futures Library, there's an [AjaxOnly] tag you can use to similar effect.


text:
Q: jquery-validation-unobtrusive: Display Different Error Messages in Summary and Label I want to show different Error messages for the same control in Error Summary and label after the checkbox.
If the checkbox is not ticked,
In Summary, I want to display "You must tick the Copyright Confirmation checkbox to continue."
In adjacent Checkbox label, I want to display "must check to continue"
js:
$.validator.addMethod("chkCopyright", function (value, element) {
        return $('#chkCopyright').is(':checked');
    }, "You must tick the Copyright Confirmation checkbox to continue.");

html code:
<label class="checkbox-inline">
     <input type="checkbox" name="chkCopyright" data-rule-chkCopyright="true" value="1" data-msg-chkCopyright="must check to continue"> I confirm that there are no copyright restrictions on this repro request. <span class="text-danger field-validation-valid" data-valmsg-for="chkCopyright" data-valmsg-replace="true"> </span>
</label>

But when the validation fails, the message in data-msg is overtaking and it's showing on the Error Summary.
How can I show different error messages in both places?

A:
How can I show different error messages in both places?

This plugin provides no procedure or method to have two completely different error messages both representing the same rule for the same field.  Period.

Possible workaround?...
You might be able to leverage the showErrors function to construct a custom list of messages up top, however, this may get very tedious and sticky.
You could use the errorMap and/or errorList objects to help construct a new list of errors for each field and rule.  And if you use this.defaultShowErrors() inside of this function, you will reactivate the default messages that normally appear next to every form input.  These defaults would use the messages as you've previously defined them within your rules.


text:
Q: QT error with copy file function I wrote a QT code to copy the whole content from sourcefile to destfile. With small-size files, it runs successfully, but with large-size files (for example, a video with 700MB of size), after process of copy, the destfile only had 2Kb of size.
This is the code of Copy routine, which does the copying process:
void Copy(QString destfile, QString sourcefile)
{
    qint64 bufSize = 100*1024*1024;//100 MB
    char *buf = new char [bufSize];
    //qint64 dataSize;
    QFile sfile(sourcefile), dfile(destfile);
    if (!sfile.open(QIODevice::ReadOnly) || !dfile.open(QIODevice::WriteOnly))
    {
        qDebug() << "Error";
        return;
    }
    while (!sfile.atEnd())
    {
        sfile.read(buf, bufSize);
        dfile.write(buf);
    }
    sfile.close();
    dfile.close();
    qDebug() << "OK";
}

A: dfile.write(buf); will write a null terminated string to your file, not the entire array. You want to do :
dfile.write(buf, bufSize);
                  ^^^^

Notes:

*

*You probably want to check the returned value of this call to test how many bytes were actually written. Same for sfile.read(buf, bufSize);, test how many bytes were read (it could be less than bufSize).

Something like :
while (!sfile.atEnd())
{
    qint64 bytesRead = sfile.read(buf, bufSize);
    if(dfile.write(buf, bytesRead) < 0)
    // error ...
}

*

*Also, buf could be allocated on the stack, no new is needed here.


text:
Q: How to send nested structures in MPI using MPI_Send I need to send  the plista array using MPI_SEND :
Traza* plista;

    struct Evento{
    char* evento;
    unsigned char cant;
    };

    struct Traza
    {
            char* nombre;
            Evento* eventos;
        unsigned int cantEventos;
            bool revisado;
            unsigned int idTraza;
    };

I read some articles in the witch the peoples use MPI_PACKED, but this is a complicated structure.

A: The data structure you want to send is complicated in the sense that it contains pointers to substructures.  Communicating the pointers obviously does not make sense, instead you have to recourse into the substructures in the style of a deep copy.  Additionally some of the substructures contain arrays of dynamic length, known only to the sender beforehand, so the receiver is unable to allocate the correct amount of memory.
You may be tempted to create your own composite MPI data types, and indeed it is possible to do so by making use of MPI_BOTTOM and encoding the absolute addresses of all of the sub-parts of the data structure.  You need to create this custom data type anew each time you want to do a communication, since you are likely to use different data and thus the absolute addresses change.  However, this only works on the sender side, since on the receiver you still do not know how much memory to allocate for each part of your data structure.
One way to solve this is to do many communications, sending the sizes first and then the data separately.  This however has the disadvantage of increasing the number of communications and can introduce unnecessary latencies.
Enter MPI_PACKED, which you already mentioned.  MPI_PACKED lets you pack the data you want to send one piece at a time into a buffer, and then sending the whole buffer in a single communication.  On the receiving side, it can be received in a single communication, and then unpacked piece by piece.
Below is a solution for your data structure that uses MPI_PACKED.
Note: I know pretty much nothing about latin languages, so I had to make guesses what some of your identifiers mean.  Namely I interpreted

*

*cant as an element count of some kind

*Evento::evento as an array of numbers that happen to fit into a char, with the length of the array in Evento::cant.

*Traza::nombre as an array of numbers and Traza::eventos as an array of events, with the length for both arrays given by Traza::cantEventos
It should be easy to correct these interpretations where they are incorrect (just obtain the sizes of the arrays from the correct source and pack them up separately the way I packed up the number of Traza in the message).
#include <iomanip>
#include <iostream>
#include <ostream>
#include <vector>

#include <mpi.h>

struct Evento {
  char* evento;
  unsigned char cant;
};

struct Traza
{
  char* nombre;
  Evento* eventos;
  unsigned int cantEventos;
  bool revisado;
  unsigned int idTraza;
};

void pack_plista(int incount, Traza* data, MPI_Comm comm,
                 std::vector<char> &buf)
{
  int pos = 0;
  buf.clear();
  int size;

  MPI_Pack_size(1, MPI_INT, comm, &size);
  buf.resize(pos+size);
  MPI_Pack(&incount, 1, MPI_INT, buf.data(), buf.size(), &pos, comm);

  for(int t = 0; t < incount; ++t)
  {
    MPI_Pack_size(2, MPI_UNSIGNED, comm, &size);
    buf.resize(pos+size);
    MPI_Pack(&data[t].cantEventos, 1, MPI_UNSIGNED,
             buf.data(), buf.size(), &pos, comm);
    MPI_Pack(&data[t].idTraza, 1, MPI_UNSIGNED,
             buf.data(), buf.size(), &pos, comm);

    MPI_Pack_size(1, MPI_UNSIGNED_CHAR, comm, &size);
    buf.resize(pos+size);
    { // MPI does not know about C++ bool
      unsigned char revisado = data[t].revisado;
      MPI_Pack(&revisado, 1, MPI_UNSIGNED_CHAR,
               buf.data(), buf.size(), &pos, comm);
    }

    // This interprets Traza::nombre as a character code, which is probably incorrect
    // However, that is unlikely to be a problem, unless you are in a
    // heterogeneous ASCII/EBCDIC environment
    MPI_Pack_size(data[t].cantEventos, MPI_CHAR, comm, &size);
    buf.resize(pos+size);
    MPI_Pack(data[t].nombre, data[t].cantEventos, MPI_CHAR,
             buf.data(), buf.size(), &pos, comm);

    for(unsigned int e = 0; e < data[t].cantEventos; ++e)
    {
      // send count (interpret as a number)
      MPI_Pack_size(1, MPI_UNSIGNED_CHAR, comm, &size);
      buf.resize(pos+size);
      MPI_Pack(&data[t].eventos[e].cant, 1, MPI_UNSIGNED_CHAR,
               buf.data(), buf.size(), &pos, comm);

      // send events (interpret as character codes)
      MPI_Pack_size(data[t].eventos[e].cant, MPI_CHAR, comm, &size);
      buf.resize(pos+size);
      MPI_Pack(data[t].eventos[e].evento, data[t].eventos[e].cant, MPI_CHAR,
               buf.data(), buf.size(), &pos, comm);
    }
  }
  buf.resize(pos);
}

void unpack_plista(int &outcount, Traza* &data, MPI_Comm comm,
                   // buf cannot be reference-to-const since MPI_Unpack takes
                   // pointer-to-nonconst
                   std::vector<char> &buf)
{
  int pos = 0;

  MPI_Unpack(buf.data(), buf.size(), &pos, &outcount, 1, MPI_INT, comm);

  data = new Traza[outcount];
  for(int t = 0; t < outcount; ++t)
  {
    MPI_Unpack(buf.data(), buf.size(), &pos,
               &data[t].cantEventos, 1, MPI_UNSIGNED, comm);
    MPI_Unpack(buf.data(), buf.size(), &pos,
               &data[t].idTraza, 1, MPI_UNSIGNED, comm);

    { // MPI does not know about C++ bool
      unsigned char revisado;
      MPI_Unpack(buf.data(), buf.size(), &pos,
                 &revisado, 1, MPI_UNSIGNED_CHAR, comm);
      data[t].revisado = revisado;
    }

    // This interprets Traza::nombre as a character code, which is probably incorrect
    // However, that is unlikely to be a problem, unless you are in a
    // heterogeneous ASCII/EBCDIC environment
    data[t].nombre = new char[data[t].cantEventos];
    MPI_Unpack(buf.data(), buf.size(), &pos,
               data[t].nombre, data[t].cantEventos, MPI_CHAR, comm);

    data[t].eventos = new Evento[data[t].cantEventos];
    for(unsigned int e = 0; e < data[t].cantEventos; ++e)
    {
      // receive count (interpret as a number)
      MPI_Unpack(buf.data(), buf.size(), &pos,
                 &data[t].eventos[e].cant, 1, MPI_UNSIGNED_CHAR, comm);

      // receive events (interpret as character codes)
      data[t].eventos[e].evento = new char[data[t].eventos[e].cant];
      MPI_Unpack(buf.data(), buf.size(), &pos,
                 data[t].eventos[e].evento, data[t].eventos[e].cant, MPI_CHAR,
                 comm);
    }
  }
}

void send_plista(int incount, Traza* data, int dest, int tag, MPI_Comm comm)
{
  std::vector<char> buf;
  pack_plista(incount, data, comm, buf);
  MPI_Send(buf.data(), buf.size(), MPI_PACKED, dest, tag, comm);
}

void recv_plista(int &outcount, Traza* &data,
                 int src, int tag, MPI_Comm comm)
{
  MPI_Status status;
  MPI_Probe(src, tag, comm, &status);
  int size;
  MPI_Get_count(&status, MPI_PACKED, &size);
  std::vector<char> buf(size);
  MPI_Recv(buf.data(), buf.size(), MPI_PACKED, src, tag, comm, &status);

  unpack_plista(outcount, data, comm, buf);
}

void make_test_data(int &count, Traza *&data) {
  count = 2;
  data = new Traza[2] {
    {
      new char[3] { char(0), char(1), char(3) },
      new Evento[3] {
        {
          new char[4] { 'a', 'b', 'c', 'd' },
          (unsigned char)4,
        },
        {
          new char[3] { 'e', 'f', 'g' },
          (unsigned char)3,
        },
        {
          new char[2] { 'h', 'i' },
          (unsigned char)2,
        },
      },
      3u,
      true,
      0u,
    },
    {
      new char[1] { char(4) },
      new Evento[1] {
        {
          new char[1] { 'j' },
          (unsigned char)1,
        },
      },
      1u,
      false,
      1u,
    },
  };
}

void print_data(std::ostream &out, int count, const Traza *data)
{
  for(int t = 0; t < count; ++t)
  {
    std::cout << "{\n"
              << "  nombre = { ";
    for(unsigned e = 0; e < data[t].cantEventos; ++e)
      std::cout << int(data[t].nombre[e]) << ", ";
    std::cout << "},\n"
              << "  eventos = {\n";
    for(unsigned e = 0; e < data[t].cantEventos; ++e)
    {
      std::cout << "    {\n"
                << "      evento = { ";
      for(int c = 0; c < data[t].eventos[e].cant; ++c)
        std::cout << "'" << data[t].eventos[e].evento[c] << "', ";
      std::cout << "},\n"
                << "      cant = " << int(data[t].eventos[e].cant) << ",\n"
                << "    },\n";
    }
    std::cout << "  },\n"
              << "  cantEventos = " << data[t].cantEventos << ",\n"
              << "  revisado = " << data[t].revisado << ",\n"
              << "  idTraza = " << data[t].idTraza << ",\n"
              << "}," << std::endl;
  }
}

int main(int argc, char **argv)
{
  int rank;
  Traza *plista = nullptr;
  int count = 0;

  MPI_Init(&argc, &argv);
  MPI_Comm_rank(MPI_COMM_WORLD, &rank);
  if(rank == 1) {
    make_test_data(count, plista);
    send_plista(count, plista, 0, 0, MPI_COMM_WORLD);
  }
  else if(rank == 0) {
    recv_plista(count, plista, 1, 0, MPI_COMM_WORLD);

    std::cout << std::boolalpha;
    print_data(std::cout, count, plista);
  }
  // don't bother freeing allocated memory, the process is ending anyway
  MPI_Finalize();
}

Sample run:
-*- mode: compilation; default-directory: "/tmp/" -*-
Compilation started at Wed Sep  9 20:04:24

set -ex; mpic++ -std=c++11 -Wall -Wno-literal-suffix -o check check.cc; mpirun -n 2 ./check
+ mpic++ -std=c++11 -Wall -Wno-literal-suffix -o check check.cc
+ mpirun -n 2 ./check
{
  nombre = { 0, 1, 3, },
  eventos = {
    {
      evento = { 'a', 'b', 'c', 'd', },
      cant = 4,
    },
    {
      evento = { 'e', 'f', 'g', },
      cant = 3,
    },
    {
      evento = { 'h', 'i', },
      cant = 2,
    },
  },
  cantEventos = 3,
  revisado = true,
  idTraza = 0,
},
{
  nombre = { 4, },
  eventos = {
    {
      evento = { 'j', },
      cant = 1,
    },
  },
  cantEventos = 1,
  revisado = false,
  idTraza = 1,
},

Compilation finished at Wed Sep  9 20:04:26


text:
Q: git stash seems not to work when new files have been added? I don't have the exact setup on me right now, but I remember adding a couple of new files to my tree and then wanting to stash them. Instead of stashing correctly, git stash returned an error:
error: Entry 'x' not uptodate. Cannot merge.

It seems weird, since the error message has to do with merging, but that's what I got back from git stash.
Does anyone know why and in what circumstances git stash returns an error such as this?
Edit:
In response to the nice people who have answered so far, I'd like to clarify something that I didn't mention originally. After rebuilding the situation in a new git repo, I can say for certain that I wasn't in the middle of a merge and my new files were being tracked. I used git add -N . to add the files without staging them, so that I could stash them properly. After trying to stash, I get this error message:
error: Entry 'x' not uptodate. Cannot merge.
Cannot save the current worktree state.

A: This is because the new files you have are not added to the index (they are new files) and are not being tracked and you are attempting to stash the changes. You can do this:
git add <file1> <file2> ...

and the git stash should work.
If it doesn't, you can force the index to refresh and try again:
git update-index --really-refresh

Followed by git stash.

A: I'll leave the original answer below, since it applies to most cases, but your question edit changes the answer.  Here's the correct one:  Don't use git add -N.
The way git add -N works is to make a special index entry, that Git is supposed to know what to do with.  For a long time, it was badly broken.  A number of corner cases have been fixed over the last five or so years, and it now works for a lot of cases—but it's still broken for git stash, even in Git 2.37:
$ git --version
git version 2.37.0.3.g30cc8d0f14
$ touch newfile && git add -N newfile && git stash
error: Entry 'newfile' not uptodate. Cannot merge.
Cannot save the current worktree state
$ git rm newfile
error: the following file has staged content different from both the
file and the HEAD:
    newfile
(use -f to force removal)
$ git rm -f newfile
rm 'newfile'

Note that git add newfile would have worked, but git add -N newfile doesn't.
(It's not clear to me how git stash should behave with a -N file in the first place, which is probably why nobody else has fixed it either.)

Original answer

error: Entry 'x' not uptodate. Cannot merge.

This error is ... not a good message, but it means you're in the middle of a conflicted merge.  Presumably you recently ran git merge or git rebase or some other command that started a merge.  This command, whatever it was, was unable to finish the merge.
Running git status now will tell you which files are unmerged.  You must finish merging them before you can move forward.  Alternatively, you can use git reset or another equivalent command to "move backwards" as it were, but you'll lose uncommitted work you have done since the failed merge failed.
If the command that was unable to finish was git merge, you can use git merge --abort, which is more or less equivalent to git reset --hard.  If the command that was unable to finish was git rebase, you can use git rebase --abort, which is more or less equivalent to git reset --hard ORIG_HEAD.  If the command that was unable to finish was git stash apply (perhaps invoked via git stash pop), there is no git stash command that will clean up, and you may be in fairly deep trouble here.  This is one of several reasons that I suggest Git users (regardless of how beginner or advanced they are) try to avoid using git stash: its corner cases can be really miserable.  (Once you're an advanced Git user, you'll know what to do for the most-miserable cases, but that won't make you any happier.  But you'll also know which ones can be the most awful, and know to avoid git stash for those.)
My main advice here is: do not try to use git stash.  Instead, use git status to figure out what operation has failed to complete and left you in this conflicted-merge state.  Finish that operation, by providing Git with the correct merge result, and use git merge --continue or git rebase --continue or git cherry-pick --continue or whatever is appropriate here based on the operation that's currently half-done.
Depending on how you like to resolve conflicted merges, use git checkout-index or git show to extract particular file copies from the index—Git's index is where the conflict really "lives"—or just edit the working tree file directly, or use git mergetool, or whatever you prefer.  Once you've come up with the correct result, put that in your working-tree file and use git add to tell Git that the file now contains the correct result.  Remember that Git itself has left you with a working tree file that probably does not have the correct result so do not just git add the existing working tree file without looking!
(The git mergetool command will optionally do the git add step for you, if the merge tool you select can tell Git whether you've told the merge tool that the file is now correct.)


text:
Q: Why am I getting an invalid prop type warning? I have the following component:
import React from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import { Box } from 'grid-styled';

const Pane = ({
  children,
  px,
  py,
}) => (
  <StyledBox
    px={px}
    py={py}
  >
    {children}
  </StyledBox>
);

Pane.propTypes = {
  children: PropTypes.node.isRequired,
  px: PropTypes.oneOfType([PropTypes.number, PropTypes.arrayOf(PropTypes.object)]),
  py: PropTypes.oneOfType([PropTypes.number, PropTypes.arrayOf(PropTypes.object)]),
  marginBottom: PropTypes.number,
  color: PropTypes.string,
};

Pane.defaultProps = {
  px: [null],
  py: [32, 40],
};

export default Pane;

My web-client's JS console is warning with the following:
preview.bundle.js:4294 Warning: Failed prop type: Invalid proppysupplied toPane.
    in Pane
Why?

A: py: [32, 40], is an array of numbers while you declare it should be PropTypes.arrayOf(PropTypes.object) - an array of objects. It's not the same.
py: PropTypes.oneOfType([PropTypes.number, PropTypes.arrayOf(PropTypes.number)]),

This means it will be a single number like 4 or an array of numbers like [32, 40].


text:
Q: How to run a virtual desktop and access it using Google Cloud Free Tier I need a virtual desktop to access chrome on the go via the Chrome Remote Desktop app on IOS.
The virtual desktop should be the usual GUI where I can open / install programs like a normal PC.
I know Windows is not free hence I am stuck with linux.
I created account and I know I need to create an instance.
What instance? How to get GUI? How to setup and access using Chrome Remote Desktop? Etc
Totally clueless.
What I Did:
1) I installed a Ubantu instance with a disk space of 30G.
2) I went into the shell and tried to run commands for installing a standard GUI.

sudo apt-get install ubuntu-desktop

3) Immediately received errors of missing dependencies.


text:
Q: DHCP Server Port-Based Address Allocation on Cisco switch 2960-x I am trying to configure DHCP Server on a Cisco 2960-x Switch to achieve port-based address allocation. I would like the ip address assigned to any device connected to that port to be the same every time.
I have used the following guide to achieve this:
http://www.cisco.com/c/en/us/td/docs/switches/lan/catalyst2960/software/release/12-2_55_se/configuration/guide/scg_2960/swdhcp82.html#wp1320905
The commands used are explained in detail here:
http://www.cisco.com/c/en/us/td/docs/ios-xml/ios/ipaddr/command/ipaddr-cr-book.pdf
I have also tried various iterations of the following command to find something that works:
address ip-address client-id string [ascii]
What I am not sure about is the string after Client ID. Does it have to match your interface name? If not how does the DHCP server know which interface to relate the assigned IP address.
Here's my running-config:
version 15.0
no service pad
service timestamps debug datetime msec
service timestamps log datetime msec
no service password-encryption
!
hostname otg
!
boot-start-marker
boot-end-marker
!
enable secret 5 $1$43Kk$SyzqQc5biarBjD2TD9Hw0/
enable password otgswitch
!
no aaa new-model
clock timezone UTC -5 0
clock summer-time UTC recurring
switch 1 provision ws-c2960x-24ts-l
no ip dhcp use vrf connected
ip dhcp use subscriber-id client-id
ip dhcp subscriber-id interface-name
!
ip dhcp pool mypool
network 192.168.200.0 255.255.255.0
reserved-only
address 192.168.200.20 client-id "GigabitEthernet1/0/2" ascii
address 192.168.200.25 client-id "GigaEth1/0/1" ascii
address 192.168.200.30 client-id "GE1/0/4" ascii
address 192.168.200.35 client-id 188b.4528.d482
address 192.168.200.45 client-id "188b.4528.d482" ascii
!
I then enables DHCP debug messages and here is what I receive:
Jan  4 02:55:49.112: DHCPD: Reload workspace interface Vlan1 tableid 0.
Jan  4 02:55:49.112: DHCPD: tableid for 192.168.200.245 on Vlan1 is 0
Jan  4 02:55:49.112: DHCPD: client's VPN is .
Jan  4 02:55:49.112: DHCPD: using subscriber-id as client-id
Jan  4 02:55:49.112: DHCPD: using received relay info.
Jan  4 02:55:49.112: DHCPD: DHCPDISCOVER received from client 0047.6931.2f30.2f on interface Vlan1.
Jan  4 02:55:49.112: DHCPD: using received relay info.
Please advise on what I might be doing wrong. Would appreciate your help.

A: I was facing problem due to loss of information in the dhcp binding table. In short the subscriber id automatically generated would not match my reservations. Here are some examples:
port#  interface  received SID(hex)      expected SID(hex)
2      Gi1/0/2    0047-6931-2f30-2f      0047-6931-2f30-2f32
13     Gi1/0/13   0047-6931-2f30-2f31    0047-6931-2f30-2f31-33
24     Gi1/0/24   0047-6931-2f30-2f32    0047-6931-2f30-2f32-34

I was hitting IOS bug present in some 15.0 releases. I updated my ios to 15.2 and problem solved!


text:
Q: Outlook body with clickable link? I have the excel file with some url rows.
I want to copy excel table to Outlook body with clickable links of URL column, but when using this code, the url is copies to email without clickable.
import win32com.client as win32
import pandas as pd
df = pd.read_excel('Article.xlsx', index_col=False)
body = df.to_html()
outlook = win32.gencache.EnsureDispatch('Outlook.Application')
mail = outlook.CreateItem(0)
mail.To = 'abc@example.com'
mail.Subject = "Test";
mail.HTMLBody = (body)
mail.Save()

https://drive.google.com/file/d/1Z7AJy8YyD0--w6gy5aX5RdiuLL-dlETG/view?usp=sharing
I put my excel file on gg drive as below link.
Could you help me with this case? Thanks a lot.


text:
Q: python: accessing class variable with or without reference code:
class Example:

    pos_list=[]
    last_cell=0

    def setText(self):
        last_cell = 10
        pos_list.append(int(10))              #Line 1
        print pos_list , last_cell            #Line 2

Error: global name 'pos_list' is not defined.
if i access pos_list in Line 1 and Line 2 as
   self.pos_List or Example.pos_list

then
      no error [ which is fine as i'm accessing it as a instance(self) or class(Example)    variable ]
but what about last_cell ?
i am  accessing it without either self or class reference. But in case of pos_list python interpreter was forcing me to use either those two references.
why am able to access last_cell without any reference ?

A: You aren't. You're just creating a local variable that happens to have the same name.
class Example:
    x = 1
    def f(self):
        x = 2
Example().f()
print(Example.x) #=> 1

A: Because you declare last_cell as a local variable. When doing pos_list.append() you are trying to call a method on something that is undefined, which generates an error.


text:
Q: Why is my docker.compose file not creating my database? I have a docker.compose file and when I start it I want it to create a database with some tables.
My docker compose:
services:
  mysql:
    image: mysql:latest
    container_name: mysqldb
    cap_add:
      - SYS_NICE # CAP_SYS_NICE
    # container_name: my_very_special_server
    ports:
      - 3307:3306
    environment:
      MYSQL_DATABASE: todo
      MYSQL_ROOT_PASSWORD: password!
      MYSQL_PASSWORD: password!
    volumes:
      - ./DbScripts/DumpTodoOnly.sql:/docker-entrypoint-initdb.d/DumpTodoOnly.sql
      - db_data:/var/lib/mysql
    restart: always
  phpmyadmin:
    image: phpmyadmin/phpmyadmin
    container_name: dev_pma
    links:
      - mysql
    environment:
      PMA_HOST: mysql
      PMA_PORT: 3307
      PMA_ARBITRARY: 1
    restart: always
    ports:
      - 8183:80
  server:
    container_name: server
    build:
      context: ./BE
      dockerfile: ./Dockerfile.prod
    depends_on:
      - mysql
    environment:
      MYSQL_HOST_IP: mysql
    ports:
      - 4000:4000
    links:
      - mysql
  client:
    container_name: FE
    build:
      context: ./FE
      dockerfile: ./Dockerfile.prod
    ports:
      - 3000:3000
    environment:
      - CHOKIDAR_USEPOLLING=true
    tty: true
volumes:
  db_data:

project structure:

the actual sql file:
-- MySQL dump 10.13  Distrib 8.0.18, for Win64 (x86_64)
-- Host: localhost    Database: todo

-- Server version   8.0.18
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT /;
/!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS /;
/!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION /;
/!50503 SET NAMES utf8 /;
/!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE /;
/!40103 SET TIME_ZONE='+00:00' /;
/!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 /;
/!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 /;
/!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' /;
/!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table todos
DROP TABLE IF EXISTS `todos`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `todos` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `todotext` varchar(200) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table users
DROP TABLE IF EXISTS `users`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `users` (
  `Id` varchar(36) NOT NULL,
  `Email` varchar(200) NOT NULL,
  `Password` binary(60) NOT NULL,
  `ChangedPassword` bit(1) NOT NULL,
  `FirstName` varchar(45) NOT NULL,
  `LastName` varchar(45) NOT NULL,
  `ImageId` varchar(36) DEFAULT NULL,
  `SeqRef` varchar(36) DEFAULT NULL,
  PRIMARY KEY (`Id`),
  UNIQUE KEY `Email_UNIQUE` (`Email`),
  UNIQUE KEY `Id_UNIQUE` (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci KEY_BLOCK_SIZE=2;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping routines for database 'todo'
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE /;
/!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS /;
/!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS /;
/!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT /;
/!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS /;
/!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION /;
/!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2022-03-16 20:20:30
When I run docker-compose up I see:

And in my php admin I dont see any users or todos table:

What have I missed?

A: Alright this is somewhat not great to find an answer when you post but for those with similar issue:
Apperently When you run the docker-compose up command the database configuration gets stored and survices a restart. To make this I had to:
docker-compose down -v

Answer found here
Note @Sebastiaan Renkens answer


text:
Q: Looking for the name of a C# syntax I've been away from C# for a while and now that I'm trying to read some code, I'm having a hard time find the meaning of it:
var server = new WebSocketServer("ws://localhost:8181");
server.Start(socket =>
{
    socket.OnOpen = () =>
    {
        Console.WriteLine("Open!");
        allSockets.Add(socket);
    };
    socket.OnClose = () =>
    {
        Console.WriteLine("Close!");
        allSockets.Remove(socket);
    };
    socket.OnMessage = message =>
    {
        Console.WriteLine(message);
        allSockets.ToList().ForEach(s => s.Send("Echo: " + message));
    };
});

What's the name for socket => { .. } syntax and where can I find some text on it? And in which version of C# is it introduced? Is the = () => { .. } the same?

A: It is a lambda expression, basically it is a shortcut for defining delegates, which are anonimous methods. It was introduced in C# 3 along with LINQ to make its use much simpler. Syntax is as follow:
parameters => body

Usually the compiler can infer in some way the type of the parameter, that's why you see only the names of the parameters.

A: in c# this syntax is called Lambda Expressions. They are available since C# 3.0
more about:
Microsoft's Programming Guide explaining lambda expression
C# Lambda expressions: Why should I use them?
and an example of programmersheaven.com


text:
Q: Refresh a GUI using AutoIt I am making AutoIt code and one of the items on the GUI needs to be updated every few seconds, and I can seem to get it to do it. To make it simple I have written some code that shows the problem:
$num = 0
GUICreate("Example")
$Pic1 = GUICtrlCreateLabel($num, 10, 10)
GUISetState()
While 1
   sleep(1000)
   $num = $num + "1"
WEnd

If the code was working then the number would change, but it does not. How do I  make it refresh?

A: The number is updating, but your data is not. Plus, you are mixing integers with strings.
Luckily AutoIt converts them automatically. But take care, because you will have problems in other programming languages.
Here you go:
Local $num = 0
Local $hGUI = GUICreate("Example")
Local $Pic1 = GUICtrlCreateLabel($num, 10, 10)
GUISetState()

Local $hTimer = TimerInit()
While 1
    ;sleep(1000)
    If TimerDiff($hTimer) > 1000 Then
        $num += 1
        GUICtrlSetData($Pic1, $num)
        $hTimer = TimerInit()
    EndIf

    If GUIGetMsg() = -3 Then ExitLoop
WEnd

P.S.: Avoid using sleep in these situations while they will pause your script.

A: This is easily done with AdLibRegister passing the function name and then 1000 milliseconds (1 second).
Local $num = 0
Local $hGUI = GUICreate("Example")
Local $Pic1 = GUICtrlCreateLabel($num, 10, 10)
Local $msg
GUISetState()

AdLibRegister("addOne", 1000)

While 1
    $msg = GUIGetMsg()
    Switch $msg
        Case $GUI_EVENT_CLOSE
            Exit
    EndSwitch
WEnd

Func addOne ()
    $num += 1
    GUICtrlSetData($Pic1, $num)
EndFunc

A: You need to set the new data in the GUI using GUICtrlSetData. Simply modify your loop like this:
While 1
   sleep(1000)
   $num += 1
   GUICtrlSetData($Pic1, $num)
WEnd

Note that I removed the double-quotes so that AutoIt handles the values as integers.


text:
Q: Simple android app (in flash) teleports between frames So I am trying to make a small android app. I have two frames, one with "start" and one with "rules" I only have code on the first one which is:
(The start button has an instance and symbol of start)
        /* Tap Event
Instructions:
1. Add your custom code on a new line after the line that says "// Start your custom code" below.
The code will execute when the symbol instance is tapped.
*/

Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT;

start.addEventListener(TouchEvent.TOUCH_TAP, fl_TapHandler_2);

function fl_TapHandler_2(event:TouchEvent):void
{
    // Start your custom code
    // This example code reduces the transparency of the object by half upon each tap event
    start.alpha *= 0.5;
    gotoAndStop(2);
    trace("going to 2")
    start.alpha *= 2;
    // End your custom code
}

When I run it, the emulator teleports between frames, like it usually does if there is a compiler error. However, when I look at the compiler errors, it does not say anything. Is there a problem already or is it happening because there is no code on the second frame?

A: [1] Add stop() in the first frame.
[2] Either remove
Instructions:
1. Add your custom code on a new line after the line that says "// Start your custom code" below.
The code will execute when the symbol instance is tapped.
*/

or change it to
/*Instructions:
1. Add your custom code on a new line after the line that says "// Start your custom code" below.
The code will execute when the symbol instance is tapped.
*/

[3] Make sure no errors are being outputted.


text:
Q: Autofac resolve all EventHandlers of abstract base class Hi Some how I cannot find the answer to this problem:
I Have event handler ala:
public class MyEvenHandler : EventHandler<MyEvent>

Where EventHandler is an abstract class
 public abstract class EventHandler<TEvent> : IEventHandler<TEvent>
    where TEvent : IDomainEvent

And
public interface IEventHandler<in TEvent> : IEventHandler where TEvent : IDomainEvent
{
    bool Handles(IDomainEvent @event);
    void Handle(TEvent @event);
    Task HandleAsync(TEvent @event);
}

I Register with autofac like this:
var builder = new ContainerBuilder();

builder.RegisterSource(new ContravariantRegistrationSource());

...
builder.RegisterAssemblyTypes(commandsAssemblies)
            .AsClosedTypesOf(typeof(EventHandler<>))
            .AsImplementedInterfaces()
            .InstancePerRequest();

Now I want to resolve all eventhandlers and register them with a messageDispatcher class
var handlers = e.Context.Resolve<IEnumerable<IEventHandler<IDomainEvent>>>().ToList();

var handlers2 = e.Context.Resolve<IEnumerable<IEventHandler<PolicyCreated>>>().ToList();

the handlers variable is empty...
handlers2 resolves correctly. But I would like to resolve all handlers genericly
the messageDispatcher (eventDispathcer) look like this:
public class EventDispatcher : IEventDispatcher
{
    private readonly IList<IEventHandler> _eventHandlers = new List<IEventHandler>();

    public virtual void RegisterEventHandler(IEventHandler eventHandler)
    {
        _eventHandlers.Add(eventHandler);
    }

    public virtual IMessageResults Publish<TEvent>(TEvent @event) where TEvent : IDomainEvent
    {
        var result = new MessageResults();
        var handlers = _eventHandlers;

        if (handlers == null)
        {
            Trace.WriteLine(String.Format("No event handlers for event {0} ", typeof(TEvent)));

            result.AddResult(new MessageResult(true));
            return result;
        }

        foreach (var eventHandler in handlers.Where(h => h.Handles(@event as IDomainEvent)))
        {
            eventHandler.Handle(@event);
        }
        return result;
    }

    public int EventHandlerCount
    {
        get
        {
            return _eventHandlers.Count();
        }
    }
}

To summarize goals:

*

*use assembly scanning

*resolve to IEnumerable of implementations of EventHandler

A: You want to cast MyEvenHandler to IEventHandler<IDomainEvent>
If we try the following code :
MyEventHandler handler = new MyEventHandler();
IEventHandler<IDomainEvent> e = (IEventHandler<IDomainEvent>)handler;

The CLR will throw an InvalidCastException because IEventHandler<TDomainEvent> is not covariant. If the CLR allow this kind of conversion, it would mean that the following code would compile :
MyEventHandler handler = new MyEventHandler();
IEventHandler<IDomainEvent> e = (IEventHandler<IDomainEvent>)handler;
e.Handle(new MyEvent2());

How the CLR should execute it ?  e expect a MyEvent and not a MyEvent2
If you want a list of all your eventHandlers you will have to introduce a base interface
public interface IEventHandler
{
    Boolean Handles(IDomainEvent @event);
}
public interface IEventHandler<TEvent> : IEventHandler
    where TEvent : IDomainEvent
{
    void Handle(TEvent @event);
    Task HandleAsync(TEvent @event);
}

And register eventHandlers as IEventHandler
ContainerBuilder builder = new ContainerBuilder();
builder.RegisterAssemblyTypes(typeof(Program).Assembly)
       .AsClosedTypesOf(typeof(IEventHandler<>))
       .As<IEventHandler>();

Using this registration, you will be able to resolve IEventHandler and IEventHandler<MyEvent>
var genericHandlers = container.Resolve<IEnumerable<IEventHandler>>();
var handlers = container.Resolve<IEnumerable<IEventHandler<MyEvent>>>();

By the way, instead of having a dependency on IEnumerable<IEventHandler>, messageDispatcher may have a dependency on ILifetimeScope and when it needs eventHandlers, it will be able to resolve them :
public class EventDispatcher
{
    private readonly ILifetimeScope _scope;

    public EventDispatcher(ILifetimeScope scope)
    {
        this._scope = scope;
    }

    public virtual IMessageResults Publish<TEvent>(TEvent @event) where TEvent : IDomainEvent
    {
        var result = new MessageResults();
        var handlers = this._scope.Resolve<IEnumerable<IEventHandler<TEvent>>>().ToList();

        if (!handlers.Any())
        {
            Trace.WriteLine(String.Format("No event handlers for event {0} ", typeof(TEvent)));

            result.AddResult(new MessageResult(true));
        }
        else
        {
            foreach (var eventHandler in handlers.Where(h => h.Handles(@event as IDomainEvent)))
            {
                eventHandler.Handle(@event);
            }
        }
        return result;
    }

    public int EventHandlerCount
    {
        get
        {
            // not tested
            var handlerCount = this._scope.ComponentRegistry
                                          .Registrations
                                          .Where(r => r.Services
                                                     .OfType<IServiceWithType>()
                                                     .Any(swt => swt.ServiceType.IsGenericType
                                                                 && swt.ServiceType.GetGenericTypeDefinition() == typeof(IEventHandler<>)))
                                          .Count();
            return handlerCount;
        }
    }
}

EDIT : This answer was before the edit with full interface declaration
If IEventHandler<TEvent> doesn't accept any TEvent in methods, you have to convert your IEventHandler<TEvent> to a covariant interface using the out modifier (see out (Generic Modifier) (C# Reference) for more information).
public interface IEventHandler<out TEvent>
    where TEvent : DomainEventBase
{ }

Using this, the CLR will be able to cast MyEventHandler to IEventHandler<DomainEventBase>.
Then, you have to tell Autofac that your types is IEventHandler<DomainEventBase> by registering them as IEventHandler<DomainEventBase>
builder.RegisterAssemblyTypes(typeof(Program).Assembly)
       .As<IEventHandler<DomainEventBase>>();

You can now get all your eventHandlers using
container.Resolve<IEnumerable<IEventHandler<DomainEventBase>>>()

By the way, the ContravariantRegistrationSource is not needed in your case.

A: 1、create an empty interface without generic
public interface IEventHandler{}

2、your IEventHandler should implement this interface
IEventHandler<TEvent>:IEventHandler

3、try resolve use this interface
e.Context.Resolve<IEnumerable<IEventHandler>>()

this way may not the best


text:
Q: Relationship between locks and atomic operations in thread programming Are all locks implemented using atomic operations? In some book, it says "one lock needs several atomic operations". I thought atomic operations and locks are different things. But it seems I was wrong. What's the relationship between locks and atomic operations?

A: Locks and atomics
Locks are a protection mechanism to perform complex, thread-unsafe operations on some data that is protected by the lock. Atomic operations are operations that can never be observed only part-way through, and are not interrupted if multiple threads are simultaneously accessing the same variables (note that in C++, variables on which atomic operations are performed are called atomic too). Locks are an abstract concept implemented using atomic operations.
How to use mutexes / locks
A mutex is the standard way to perform locking: A mutex always guards some variables that are associated with it. It is either locked or unlocked, and only one thread at a time can lock it. While the mutex is locked, the thread can perform thread-unsafe operations on its guarded variables, and it is guaranteed that no other thread can interfere or observe partial changes made by the thread that holds the lock. After the thread is done modifying the variables, it can unlock the mutex, so that other threads can now access the guarded variables (by locking the mutex themselves).
Note that whenever a thread wants to access any of the protected variables in any way, it needs to lock the associated mutex. Otherwise, it is no longer guaranteed that threads won't interfere with each other's work.
How are locks implemented?
As far as I know, locks/mutexes are always implemented using atomic operations. One such operation is the atomic exchange: It allows you to read a value from a variable, and write a new value to it, atomically, so no other thread can interfere in this process or observe it half-way done. A mutex would be implemented using an atomic bool (true = LOCKED, false = UNLOCKED), and locking it is performed by performing the following:
while(mutex.locked.exchange(LOCKED) == LOCKED);

This always sets the mutex to LOCKED, and reads the previous value, and if it was UNLOCKED, finishes. In this scenario, we are the only thread that set the mutex from UNLOCKED to LOCKED.
Unlocking is very simple: mutex.locked = UNLOCKED; This simply sets the mutex to UNLOCKED, and it can then be locked again by other threads.
Note
For simplicity, I did leave out memory ordering, an aspect of atomics which deals with the order in which changes made by one thread become visible to other threads (as with some memory orders, changes may be observed in a different order than in which they were made, and multiple threads may even see changes in inconsistent orders). Memory ordering is very complex to get into.
Conclusion
As a general rule of thumb, unless you really know what you're doing, you should always use mutexes and locks, and not atomics. Although mutexes are slower, they are complex enough to get into already, and are much easier to use correctly. They automatically deal with visibility of changes made, so your program becomes easier to understand and write.


text:
Q: How to use wildcards in Spring MVC servlet mapping URLs? I've got a controller set up in my web.xml:
<servlet>
    <servlet-name>controller</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>controller</servlet-name>
    <url-pattern>/console/index</url-pattern>
</servlet-mapping>

And a matching bean defined in controller-servlet.xml:
<bean name="/console/index" class="com.package.OverviewController"/>

Which works correctly - when I get "/appName/console/index" it behaves as I expect. But when I change web.xml to this:
<servlet>
    <servlet-name>controller</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>controller</servlet-name>
    <url-pattern>/console/*</url-pattern>
</servlet-mapping>

It no longer functions, giving me the following exception:
WARN (org.springframework.web.servlet.PageNotFound) - No mapping for [/appName/console/index] in DispatcherServlet with name 'controller'

So my question is how do I use wildcards in the servlet mappings, so that different URLs all go through the single DispatcherServlet but may go to one of several controller beans?
FYI: I'm stuck on Spring 2.0, as it's an established application used in government.

A: When you use wildcards in <url-pattern>, controller names by default correspond to wildcard part of the pattern.
So, you can either rename your controller to /index, or set the alwaysUseFullPath property of your HandlerMapping to true.


text:
Q: $group with $map not working properly in mongodb I am new to mongodb aggregation, i have a collection
{
"_id":60ab3312623b0108338a9601,
"items":[{"type":"Tshirt","price":300,"quantity":2}],
"orderId":"ORD189",
"from":"abc",
"to":"xyz",
"createdAt":2021-05-24T05:01:06.960Z,
"__v":0,
"tracking":null
}

I want to find the count of orders per day and totalPrice of items like
{_id: {date:24, month:05, year:2021}, count: 1, totalPrice: 600}

I used aggregations like below

db.getCollection("orders").aggregate(
    [
        {
            "$group" : {
                "_id" : {
                    "date" : {
                        "$dayOfMonth" : "$createdAt"
                    },
                    "month" : {
                        "$month" : "$createdAt"
                    },
                    "year" : {
                        "$year" : "$createdAt"
                    }
                },
                "count" : { $sum : 1},
                "totalPrice" : {
                    $sum: {
                        $map: {
                            "input" :"$items",
                            "as":"item",
                            "in":{
                                $multiply: ["$item.price", "$item.quantity"]
                            }
                        }
                    }
                }
            }
        }
    ]
);

It is giving me the following result
{
    "_id" : {
        "date" : NumberInt(24),
        "month" : NumberInt(5),
        "year" : NumberInt(2021)
    },
    "count" : 1.0,
    "totalPrice" : NumberInt(0)
}

If I use unwind am not able to get the proper count.

A: You just need to correct totalPrice calculation,

*

*$map to iterate loop of items and do multiplication of price and quantity, this will return array of total

*$sum to get total of above total

"totalPrice": {
  $sum: {
    $sum: {
      $map: {
        input: "$items",
        in: {
          $multiply: ["$$this.price", "$$this.quantity"]
        }
      }
    }
  }
}

Playground


text:
Q: How to export data and its relationships we do have a client server application with database. Now our customer wants to have the following feature:
He wants to enter a ProductNumber and wants to know what kind of entities we have stored in our database and what relationships they have. E.g. ProductNumber "1239293" has Customer "A" and "B" also there are some product attributes associated with.
So to say it is an export of our Database to a flat file.
My question now is: What would be a good output-format ?

*

*The data is hierarchical

*The output should be readable to the customer

The only solution I can think of is XML. Can you suggest others?


text:
Q: GWT Simple Drag and Drop for custom widgets Are there any GWT gurus out there who can guide me on how to start with Drag and Drop in GWT for custom widgets. I have a build a simple tree structure by putting custom widgets inside an HTMLPanel (table rows) and want to be able to drag and drop each widget above or below other widgets but don't know where to start I am using 1.6. I need someone to guide me or point me in the right direction. thanks

A: gwt-dnd providing easy to use drag-and-drop capabilities to Google Web Toolkit (GWT) projects.
I encourage you for using this library. You can see a complete demo with source code about gwt-dnd in this site .

A: You can also look at drag-and-drop plugin of gwtquery.
documentation : http://code.google.com/p/gwtquery-plugins/wiki/DragAndDropPluginForGWTDeveloppers


text:
Q: Git - Merge apenas de arquivos com conflito Boa tarde!
Existe alguma maneira de fazer o merge entre duas branchs somente nos arquivos com conflitos?
Estou em uma situação onde trabalhamos com Azure e ao fazer um Pull Request ela notifica que há conflitos em dois arquivos específicos. Eu normalmente atualizo as duas branchs localmente e faço o "checkout" dos arquivos listados com conflitos.
Mas gostaria de saber se há alguma maneira de fazer já o mexe com os arquivos conflitados localmente (sem precisar ficar descrevendo quais arquivos quero fazer merge)
Atenciosamente

A: Não sei se entendi bem a pergunta mas vamos la, no git quando você da o comando
git checkout sua_branch

git merge master

pra dar merge da sua_branch com a master no caso. Se der conflito vai aparecer a seguinte mensagem
Auto-merging arquivo.ext
CONFLICT (content): Merge conflict in arquivo.ext
Automatic merge failed; fix conflicts and then commit the result.

nesse caso você arruma os conflitos nos arquivos e da o seguinte comando
git add arquivo.ext
git commit -m "correção do conflito..."

deve aparecer a mensagem
Recorded resolution for 'arquivo.ext'.
[sua_branch 645c4e6] Merged master fixed conflict.

depois so seguir o fluxo


text:
Q: Testing request after request jmeter I have a quick question I have a simple web application composed of cars a user is able to select the car and then is displayed his choice. The application is a dynamic web application built in eclipse.
So I am testing my web application using jmeter.
Firstly the user searches for a car ..... this works in jmeter
The result page has a checkbox with select car, the user checks the box and the cars are selected... this does not work.
THe thing is after the user selects the cars his selection is shown the thing is how do I test generate proper Http request for this because the each of these request share data amongst each other and cannot be tested indvidaully. I am using a simple controller in jmetter and I have grouped these http requests
So it looks like this
Simple Controller
  Search Cars  (Get Method ) ... Works
  Search Results .. works
  Select Car (Get Method)... Does not wrok
  Selected Cars ... Does not work

I am new to jmeter

A: Kindly go though the below link, it will help you to record and replay the scenarios using Jmeter
http://jmeter.apache.org/usermanual/jmeter_proxy_step_by_step.pdf

*

*first you can record the scenario

*second apply correlation where ever required

*group the scenarios together using controllers (simple/transaction... etc.)

re-run the script
Hope this will help


text:
Q: What is the difference between `set -o` vs `bindkey`? From what I have seen, both set -o emacs and bindkey -e are used to modify the behavior of your terminal line editor to emulate emacs whereas set -o vi and bindkey -v are used to emulate vi keybindings. Since both set -o and bindkey seem to do the same thing, I was wondering what the differences between the two were and if there were any differences at all.
It seems like set -o works for most shells whereas bindkey is a zle specific command. Is this the only difference? Also, do they bind the same keys or are there some keys where set -o and bindkey bind to different operations?

A: bindkey -v/-e is the tcsh syntax (a bindkey builtin was added to tcsh in 5.19PL2 in 1990), while set -o vi/emacs is the ksh syntax (already there in ksh85, probably earlier as ksh had emacs/vi mode at least as far back as 1983).
In zsh, bindkey was added in 2.0 in 1991 which came with the first version of zle (1.0 the previous version used readline borrowed from bash).
zsh, since the first 1.0 version had setopt to set options (in addition to the options passed on the command line like in csh/Bourne), while (t)csh and bash used special variables instead. In 2.0, a -o option (both to the interpreter and to the set builtin) was added for compatibility with ksh (bash itself converted its special variables to options set with a new shopt builtin in 2.0 in 1996; that's a separate set of options from those set with set -o there; set -o support added circa 1990).
The vi and emacs "options" were not added to zsh until 2003 in version 4.1.1 though. The "option" paradigm is not very appropriate for that as when you set the emacs option, it disables the vi mode.
You'll notice that zsh -o emacs and zsh -o vi currently don't work properly in that zsh reports zsh: invalid module name `zsh/zle' on startup (a bug).
Most shells including zsh also select the default editing mode based on the value of the $EDITOR and $VISUAL environment variables to try and match the line editing mode to the user's editor preference.


text:
Q: Wordpress add_options_page I would like to create two plugins for my wordpress blog and I need different admin settings for both.I am trying to adding plugin administration; but which selecting both settings together when select single.What's wrong with me.Here I am attaching what I done
add_action('admin_menu', 'sb_load_featured_slider');

function sb_load_featured_slider() {
$mypage = add_options_page('SB_Featured Slider', 'SB_Featured Slider', 8,   array('sbslider','sbslider1','sbslider2'), 'sb_featured');
add_action( "admin_print_scripts-$mypage", 'sb_loadjs_admin_head' );
 }

and my second plugin says as follows
add_action('admin_menu', 'sb_load_intro');

  function sb_load_intro()
 {
$mypage = add_options_page('SB Introduction', 'SB Introduction', 9,  array('sbintro','sbjquery'), 'sb_intro');
add_action( "admin_print_scripts-$mypage", 'sb_introjs_admin_head' );
 }

A: well I see one similarity between the 2 functions. You use the $mypage variable in both functions and use that for the second add action. try to use different variable names and see if it fix your problem.
eg: $mypage1, $mypage2


text:
Q: Cannot find HapticAudioResourceID in scope I have a problem when adding audio to haptic feedback using core haptics in swifui. The system keeps showing the error "can't find audioID" in scope as audioID should be a registered audio resource ID parameter created by the function registerAudioresource of CHHapticEngine.
Here are the two functions that I have written:
//get engine ready
func prepareHaptics() {
  guard CHHapticEngine.capablitiesForHardware().supportHaptics else { return }
  do {
    engine = try CHHapticEngine()
    try engine?.start()
} catch {
    print("There was an error creating the engine: \(error.localizedDescription)")
}
}

//play haptic and audio pattern
func Haptictransient() {
  guard CHHapticEngine.capablitiesForHardware().supportHaptics else { return }
  guard let sound = Bundle.main.url(forResource: "tapsound", withExtension: "wav") else { return }

  do {
    let audioID = try engine?.registerAudioresource(sound)
} catch {
    print("Couldn't create the audio ID")
}
  var events = [CHHapticEvent]()
//The code below get me an error "cannot find 'audioID' in scope"
  let audio = CHHapticEvent(audioresourceID: audioID, parameters: [], relativeTime: 0)
  events.append(audio)
  let haptic = CHHapticEvent(evnetType: .hapticTransient, parameters: [], relativeTime: 0)
  events.append(haptic)

  do {
    let pattern = try CHHapticPattern(events: evnets, parameters: [])
    let player = try engine?.makePlayer(with: pattern)
    try player?.start(atTime: 0)
} catch { print("Failed to play pattern")}
}

I tried different ways but none have worked. Any idea or help will be much appreciated!
Edit 2
This is the full version of my codes. Although no error received, no feedback received.
import SwiftUI
import CoreHaptics

struct TapView: View {
  @State var engine: CHHapticEngine?

  var body: some View {
    Button(action: {
        prepareHaptics()
        hapticTransient()
    }) { Text("PRESS") }
  }

//get haptic engine ready
  func prepareHaptics() {
    guard CHHapticEngine.capabilitiesForHardware().supportsHaptics else { return }
    do {
      engine = try CHHapticEngine()
      try engine?.start()
    } catch {
      print("There was an error creating the engine: \(error.localizedDescription)")
    }
  }

//add haptic and audio feedback
  func hapticTransient() {
    guard CHHapticEngine.capabilitiesForHardware().supportsHaptics, let engine else { return }
    guard let sound = Bundle.main.url(forResource: "tapsound", withExtension: "wav") else {return}
    let audioID: CHHapticAudioREsourceID
    do { audioID = try engine.registerAudioResource(sound) }
    catch { print("Failed to create the audio") return }

    var events = [CHHapticEvent]()
    let audioEvent = CHHapticEvent(audioResourceID: audioID, parameters: [], relativeTime: 0)
    let hapticEvent = CHHapticEvent(eventType: .hapticTransient, parameters: [], relativeTime: 0)
    events.append(audioEvent)
    events.append(hapticEvent)

    do {
      let pattern = try CHHapticPattern(events: events, parameter: [])
      let player = try engine.makePlayer(with: pattern)
      try palyer.start(atTime: 0)
   } catch {
       print("Failed to play pattern \(error.localDescription)")
     }
  }
}

A: The problem is here:
do {
    let audioID = try engine.registerAudioResource(sound)
} catch {
    print("Couldn't create the audio ID")
}

audioID is out of scope when you try to use it later. You can fix it by moving the declaration of audioID before the do/catch:
var engine: CHHapticEngine?

//get engine ready
func prepareHaptics() {
    guard CHHapticEngine.capabilitiesForHardware().supportsHaptics else { return }
    do {
        engine = try CHHapticEngine()
        try engine?.start()
    } catch {
        print("There was an error creating the engine: \(error.localizedDescription)")
    }
}

//play haptic and audio pattern
func hapticTransient() {

    // Also check you have an engine before continuing
    guard CHHapticEngine.capabilitiesForHardware().supportsHaptics, let engine else { return }

    guard let sound = Bundle.main.url(forResource: "tapsound", withExtension: "wav") else { return }

    //Declare audioID here so it's in scope
    let audioID: CHHapticAudioResourceID
    do {
        audioID = try engine.registerAudioResource(sound)
    } catch {
        print("Couldn't create the audio ID")

        // return if it fails
        return
    }

    var events = [CHHapticEvent]()
    //The code below get me an error "cannot find 'audioID' in scope"
    let audio = CHHapticEvent(audioResourceID: audioID, parameters: [], relativeTime: 0)
    events.append(audio)
    let haptic = CHHapticEvent(eventType: .hapticTransient, parameters: [], relativeTime: 0)
    events.append(haptic)

    do {
        let pattern = try CHHapticPattern(events: events, parameters: [])
        let player = try engine.makePlayer(with: pattern)
        try player.start(atTime: 0)
    } catch { print("Failed to play pattern")}
}

Notice I've added a return if  registerAudioResource fails
I've also added let engine to your guard as it makes no sense if it's nil


text:
Q: Expo App with Google Login is not redirecting to app I having a problem with my Google Sign In, I'm Currently using EXPO app I wish at all cost not to eject / opt out of Expo, the problem is that when I click on the Button to log in with Google in my App it does take me to the login page for me inside the browser, but once I put my Google credentials, it just lands inside the Google.com page.
I checked a lot of posts but still I'm unable to get it to come back to the app.
My app Code to log in is:
//import de Google en Expo
import * as Google from 'expo-google-app-auth';
import * as AppAuth from 'expo-app-auth';

export const googleLogin = () => {
    console.log('***Entro en Google***');
    return async dispatch => {
        try {
            const result = await Google.logInAsync({
              androidClientId: '***my ID Censored***',
              scopes: ['profile', 'email'],
              behavior: 'web',
              redirectUrl: `${AppAuth.OAuthRedirect}:/oauthredirect`
            });
            console.log('***Hizo Consulta***');
            if (result.type === 'success') {
              console.log(result.accessToken);
            } else {
              return { cancelled: true };
            }
          } catch (e) {
            return { error: true };
          }
    }
};

I checked on many posts that the issue was the redirect URL and I tried setting 4 options:

*

*${AppAuth.OAuthRedirect}:/oauthredirect

*${AppAuth.OAuthRedirect}:/oauthredirect/google

*'host.exp.exponent:/oauth2redirect/google'

*'host.exp.exponent:/oauth2redirect/'

None of them worked, I did the last 2 of host.exp.exponent as that is the Bundle Identifier used by Expo on their documentation:
https://docs.expo.io/versions/latest/sdk/google/
Create an Android OAuth Client ID

*

*Select "Android Application" as the Application Type. Give it a name
if you want (maybe "Android Development").

*Run openssl rand -base64
32 | openssl sha1 -c in your terminal, it will output a string that
looks like A1:B2:C3 but longer. Copy the output to your clipboard.
Paste the output from the previous step into the
"Signing-certificate fingerprint" text field.

*Use host.exp.exponent as the "Package name".
4.Click "Create"

*You will now see a modal with the Client ID.

*The client ID is used in the androidClientId option for Google.loginAsync (see code example below).

I did just that, and now it always gets stuck in the google.com page, any Ideas or recommendations?
Kind Regards

A: What have you added to your bundle id (e.g "Apple bundle ID")?
Take into account that there is a difference between production and development.
In development, you should use the default expo apple bundle id so you will be allowed to use the google login (and you won't get redirect_fail).
The default apple bundle id for development using expo is: host.exp.exponent
In production, you should have your own bundle id.
Please write up a follow-up message if any extra help is needed.

A: 'expo-google-app-auth' is deprecated:
https://www.npmjs.com/package/expo-google-app-auth

Author message:

Please migrate to expo-auth-session

You need use expo-auth-session.
Example of code:
//imports

WebBrowser.maybeCompleteAuthSession();

//component name

const [requestGoogle, responseGoogle, promptAsyncGoogle] =
    Google.useAuthRequest({
      expoClientId: "clientId",
      androidClientId: "clientId,
      webClientId: "clientId",
      iosClientId: "clientId",
    });

  useEffect(() => {
    if (responseGoogle?.type === "success") {
      const token = responseGoogle.params.access_token;

      // some code to get google data by google token

    }
  }, [responseGoogle]);

// in your button add to onPress={promptAsyncGoogle}

P.S: it works with libs:
"expo": "~47.0.13"
"expo-auth-session": "~3.8.0",

A: In app.json,
package name as to be all in small letters like com.app.cloneapp


text:
Q: Find stationary distribution for infinite space Markov chain Let their be a Markov chain on state space $S = \{0,1,2,...\}$. Transition probabilities are given as:
$p_{0,1} = 1$, $p_{i,i+1} = p$, $p_{i+1, i} = q$
where $0<p,q<1$ and $p+q=1$. For $p<q$ , I need to find the stationary distribution (say $\pi$) of this Markov chain.
I got the balance equations: $$\pi_{0}  =q.\pi_{1}$$ $$\pi_{i} = p.\pi_{i-1}+ q.\pi_{i+1}$$
and normalization conditoin: $$\sum_{i=0}^{\infty}\pi_{i} = 1$$
Using these relations, how can I get the stationary distribution?

A: The condition you give is the correctly identified global balance equation for $\pi, \, P$, however it is much easier to find the closed form of the stationary distribution by proving that it satisfies the detailed balance condition
$$\pi(i) P(i,j) = \pi(j)P(j,i), \qquad \forall \, i,j\, \in S.$$
If we can find such a probability vector $\pi$ which satisfies this condition, then $\pi$ is known to be a stationary distribution for $P$.
In the context of your Markov chain, we know that $P(i,j) = 0$ if $j \neq i \pm 1$ and it suffices to find $\pi$ satisfying
$$ \pi(i)P(i,i+1) = \pi(i+1)P(i+1,i)$$
That is
$$\pi(i)p = \pi(i+1)(1-p).$$
If we write $\rho  = p/(1-p)$ then we have the recurrence relation
$$\pi(i+1) = \rho \pi(i) = \cdots = \rho^{i} \pi(1) = \frac1p \, \rho^{i+1} \pi(0),$$
where in the final equality we use that the detailed balance at $i = 0$ is given by $\pi(0) = (1-p) \pi(1)$.
Since the stationary distribution must sum to $1$ (it is a probability distribution) we have
$$1 = \sum_{i=0}^{\infty} \pi(i) = \frac{\pi(0)}p  \sum_{i=0}^\infty \rho^i$$
You can now use the geometric series identity to identify when this is well defined, and to find the exact formula for the stationary distribution.
Note: In the above I worked with the method of assuming detailed balance to be true, and then showing that this was in fact the case (for certain $p$, which you will need to check). An alternate approach would have been to first demonstrate that the process is reversible by proving Kolmogorov's Criterion (which shows reversibility, which is equivalent to detailed balance), and then deriving the detailed balance relationship after.

A: Just write those equations between only two nodes, like you have for $0$.
$$1 \cdot \pi_0 = q \cdot \pi_1$$
$$p \cdot \pi_1 = q \cdot \pi_2$$
$$ \ldots $$
$$\pi_{k+1} = \frac{p}{q} \cdot \pi_k = \left(\frac{p}{q}\right)^{k}\cdot \pi_1$$
Then you have $$1 = \sum\limits_{k=0}^{\infty}\pi_k = q \cdot \pi_1 + \pi_1 + \left(\frac{p}{q}\right)^{1}\cdot \pi_1 + \left(\frac{p}{q}\right)^{2}\cdot \pi_1 + \ldots$$
$$1 = \pi_1 \cdot \left( q + 1 + \left(\frac{p}{q}\right)^{1} + \left(\frac{p}{q}\right)^{2} + \ldots\right)$$
$$\pi_1 = \frac{1}{\frac{1}{1 - p/q} + q}$$
you need to be careful, so $p < q$, otherwise no stationary distribution exists.


text:
Q: Am I writing this code wrong? This looks wrong to me, am i right? This is the code that I am using:
_editButton = [[UIBarButtonItem alloc] initWithTitle:@"Back"
                                               style:UIBarButtonItemStylePlain
                                              target:self
                                              action:@selector(editButtonPressed:)];

// If we have no threads we don't have the edit button
self.navigationItem.leftBarButtonItem = _editButton ; nil;

Mainly I am concerned with self.navigationItem.leftBarButtonItem = _editButton ; nil; the _editButton ; nil; looks wrong to me.
Should the code look like this? self.navigationItem.leftBarButtonItem = _editButton;

A: It's not wrong per se, but it is unnecessary.  The ; after _editButton ends the statement making nil; a statement of its own, and as you might imagine that does nothing whatsoever.  The two are functionally identical, so you may as well take out the extra code.

A: I've never used this particular type before, but your main indicator is prooobably if it works as intended (+ if it shows up on a debugger as correct, but that's a given).


text:
Q: SQL Prepared statement reuse in plan cache I'm working on minimising our plan cache usage, and I've read a lot around Adhoc queries and how we can parameterize and reuse rather than having many single use plans.
I'm not seeing as much information out there about the prepared plan reuse.  We have around 100gb of RAM dedicated to our production box, and 90% of our plan cache is divided into ~10% Single Use Adhoc, ~35% Plan stubs Adhoc and 36% Single Use Prepared.
So, I am basically trying to understand what prepared really means.
I believe the plans exist only for the duration of the connection, but I can see that many of the plans are duplicates similar to this:
(@bitValid BIT OUTPUT)IF(SELECT COUNT(pkItemID) FROM vwValidateDetail WITH (NOLOCK) WHERE fkInvoiceID = 43630155) > 0 BEGIN SET @bitValid = 1 END

Similarly, there are UPDATE statements where there are many plans for the same type - where one part is parameterized and the rest of the query isn't.
(@ElementValue nvarchar(4000))UPDATE ImportInterfaceSub Set [sub1] = @ElementValue WHERE [ID] = 18926954

Even if these queries are short lived, is there a better way I can parameterize the queries to re-use for memory?
The sql in question lives in a stored procedure which looks parameterized already IE:
UPDATE ImportInterfaceSub Set [sub1] = NULL WHERE [ID] = @id

Is this just a factor of how the engine operates, or is there a gain to be re-writing prepared queries as well as the single-use adhoc queries?