text:
Q: Popover for button created via code for long press I know how to create popovers if my button added to story board, but how can I create popover if my button created via code.
UIButtonS *button = [UIButtonS buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self action:@selector(siteButtonPressed:)forControlEvents:UIControlEventTouchUpInside];
[button setTitle:string1 forState:UIControlStateNormal];
button.frame = CGRectMake(XLocatioan, YLocation, 90, 30);

UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]
                                                   initWithTarget:self
                                                   action:@selector(handleLongPress:)];
longPress.minimumPressDuration = 1.0;
[button addGestureRecognizer:longPress];
[self.view addSubview:button];

-  (void)handleLongPress:(UILongPressGestureRecognizer*)sender {
    if (sender.state == UIGestureRecognizerStateEnded) {
    }
    else if (sender.state == UIGestureRecognizerStateBegan){
      //create popover for button
    }
}

A: You are already doing it right, but you are overthinking. There is no need to check the state of the gesture recognizer. If the target function has been triggered, it means that the user has done a long press. Also, note that not all of the values of the property state may be supported. As the documentation says: Some of these states are not applicable to discrete gestures.
So your code should look like this (unless you want to implement dragging or something similar):
UIButtonS *button = [UIButtonS buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self action:@selector(siteButtonPressed:)forControlEvents:UIControlEventTouchUpInside];
[button setTitle:string1 forState:UIControlStateNormal];
button.frame = CGRectMake(XLocatioan, YLocation, 90, 30);

UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]
                                                   initWithTarget:self
                                                   action:@selector(handleLongPress:)];
longPress.minimumPressDuration = 1.0;
[button addGestureRecognizer:longPress];
[self.view addSubview:button];

-  (void)handleLongPress:(UILongPressGestureRecognizer*)sender {
    //create popover for button
}

If your target is iOS 6+ you should use a UIPopoverController to create the popover, otherwise use UIAlertView.


text:
Q: How can I store SQL Server query value to variable? I want to sum all values of a column (ttl), and store result in a variable (sum), I tried some code snippets, but I didn't get any success.
SqlCommand cmd1 = new SqlCommand("Select sum(ttl) from feereceipt where std_id = '"+ textBox1.Text +"'",con);

SqlDataReader dr = cmd1.ExecuteReader();

while (dr.Read())
{
     sum = Convert.ToInt32(dr[0]);
     MessageBox.Show(sum.ToString());
     con.Close();
}

A: In your code, you should close the connection after the loop, closing the connection inside the loop will cause an error:
while (dr.Read())
{
    sum = Convert.ToInt32(dr[0]);
    MessageBox.Show(sum.ToString());
}
con.Close();

*

*Sum should return a single value, so you can simply get the value like this:
int sum = Convert.ToInt32(cmd1.ExecuteScalar());

*Adding a variable directly to query makes it vulnerable for injections. Use parameters instead:
SqlCommand cmd1 = new SqlCommand("Select sum(ttl) from feereceipt where std_id = @id",con);
cmd1.Parameters.Add("@id", SqlDbType.VarChar).Value = textBox1.Text;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Problema con objetos en hilos de java Estoy practicando los hilos y después de llevar un rato con ello no consigo llegar al punto donde en el método run() dentro de la clase Requerimiento_1.java reconozca los objetos de tipo ArrayList(), ¿debería crear los objetos dentro del método run()? aprecio cualquier sugerencia os pego por orden de aparición la clase main  Main_Actividad01.java y su clase correspondiente Requerimiento_1.java lo que pide la actividad es sacar la lista de los números primos y los no primos usando una hilo para cada una.
import java.util.ArrayList;
import java.util.Scanner;

public class Main_Actividad01 {

    public static void main(String[] args) {

    ArrayList<Integer> lista_primos = new ArrayList<Integer>();
    Requerimiento_1 lista_primos1 =  new Requerimiento_1(lista_primos);
    Thread t1 = new Thread(lista_primos1);
    t1.setName(" Hilo 1 ");

    ArrayList<Integer> lista_Noprimos = new ArrayList<Integer>();
    Requerimiento_1 lista_Noprimos1 = new Requerimiento_1(lista_Noprimos);
    Thread t2 = new Thread(lista_Noprimos1);
    t2.setName(" Hilo 2 ");
    try {
        Thread.sleep(500);
    }catch (InterruptedException e) {
        e.printStackTrace();
    }

    t1.start();
    t2.start();

    System.out.println("Esta es la lista de primos "+lista_primos + " esta en la lista de los No primos"+ lista_Noprimos);
    }
}

public class Requerimiento_1 implements Runnable{
private ArrayList lista;
Scanner sc = new Scanner(System.in);
public Requerimiento_1() {
    super();
}
public Requerimiento_1(ArrayList<Integer> lista) {
    super();
    this.lista = lista;
}
public ArrayList<Integer> getLista() {
    return lista;
}
public void setLista(ArrayList<Integer> lista) {
    this.lista = lista;
}
public void add(ArrayList<Integer> req) {
    this.lista =  req;
}
public synchronized ArrayList<Integer> esprimo(ArrayList<Integer> lista_Noprimos, ArrayList<Integer> lista_primos) {
    int num;
    for (int i=0; i<4; i++) {
        System.out.println("Dame un numero: ");
        num = sc.nextInt();
        // Si es divisible por cualquiera de estos números, no
        // es primo
        if (num == 0 || num == 1 || num == 4)
            lista_Noprimos.add(num);
        System.out.println();
    for (int x = 2; x < num / 2; x++) {
            // Si es divisible por cualquiera de estos números, no
            // es primo
            if (num % x == 0)
                lista_Noprimos.add(num);
            //sino, es primo
            else {
                lista_primos.add(num);
            }

          }
    }

    return lista;
}
@Override
public void run() {
    System.out.println("Arrancando hilo: "+ Thread.currentThread().getName());

        try {
            Thread.sleep(300);

        }catch (InterruptedException e) {
        e.printStackTrace();
        }
    sc.close();
    System.out.println("El hilo ha terminado");
        }
}

Lo que no termino de tener claro es como arrancar el método run() utilizando los objetos creados en el método main

A: Lo primero que tienes que entender es que todo lo que esté en hilos se puede ejecutar en cualquier momento, y el hecho de ponerle synchronized equivale a crear un cuello de botella que no es realmente lo que quieres en este caso para los cálculos pero sí para la lectura de datos.
Primero abstraemos la funcionalidad de pedir números y regresar una lista, perderemos un poco de desempeño la verdad, pero ganaremos que tu código sea más reutilizable y más fácil de mantener.
package es.stackoverflow.com.questions488069;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class LeerNumeros {

    public List<Integer> lee(Scanner sc) {
        int num;
        List<Integer> lista = new ArrayList<>(4);
        for (int i = 0; i < 4; i++) {
            System.out.println("Dame un numero: " + i + ":");
            num = sc.nextInt();
            lista.add(num);
            System.out.println();
        }
        return lista;
    }

}

Ahora los hilos los usaremos para procesar en paralelo los primos y los no primos por lo que renombraremos tu clase como ExtractorDePrimos:
package es.stackoverflow.com.questions488069;

import java.util.ArrayList;
import java.util.List;

public class ExtractorDePrimos implements Runnable {

    final List<Integer> lista;

    public ExtractorDePrimos(List<Integer> lista) {
        this.lista = lista;
    }

    public void esprimo() {

        ArrayList<Integer> lista_Noprimos = new ArrayList<>(4);
        ArrayList<Integer> lista_primos = new ArrayList<>(4);

        for (int i = 0; i < lista.size(); i++) {
            int num = lista.get(i);

            for (int x = 2; x < num / 2; x++) {
                // Si es divisible por cualquiera de estos números, no
                // es primo
                if (num % x == 0) {
                    lista_Noprimos.add(num);
                    break;
                } //sino, es primo
                else {
                    lista_primos.add(num);
                    break;
                }

            }

        }

        System.out.println("Esta es la lista de primos " + lista_primos + " esta en la lista de los No primos" + lista_Noprimos + " del hilo " + Thread.currentThread().getName());
    }

    @Override
    public void run() {
        System.out.println("Arrancando hilo: " + Thread.currentThread().getName());
        esprimo();

        System.out.println("El hilo ha terminado");
    }
}

Como verás reuso muchas de tus ideas como que:

*

*cada hilo puede crearse con la lista de números con los que va a trabajar

*cada hilo dice su nombre cuando inicia a correr

Finalmente la clase principal para llamar a todo queda como
package es.stackoverflow.com.questions488069;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main_Actividad01 {

    public static void main(String[] args) {

        List<Integer> lista_primos = new ArrayList<Integer>();
        List<Integer> lista_Noprimos = new ArrayList<Integer>();
        Scanner sc = new Scanner(System.in);

        ExtractorDePrimos lista_primos1 = new ExtractorDePrimos(new LeerNumeros().lee(sc));
        Thread t1 = new Thread(lista_primos1, " Hilo 1 ");
        ExtractorDePrimos lista_Noprimos1 = new ExtractorDePrimos(new LeerNumeros().lee(sc));
        sc.close();
        Thread t2 = new Thread(lista_Noprimos1, " Hilo 2 ");
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        t1.start();
        t2.start();

    }
}

Es importante que sepas que los hilos no neesariamente terminan en el óden en que los creaste, (y de hecho por eso imprimo su nombre junto con los resultados)  por lo que podrías obtener una salida como la siguiente.
Dame un numero: 0:
13

Dame un numero: 1:
53

Dame un numero: 2:
42

Dame un numero: 3:
31

Dame un numero: 0:
33

Dame un numero: 1:
57

Dame un numero: 2:
75

Dame un numero: 3:
23

Arrancando hilo:  Hilo 1
Arrancando hilo:  Hilo 2
Esta es la lista de primos [33, 57, 75, 23] esta en la lista de los No primos[] del hilo Hilo 2
El hilo ha terminado
Esta es la lista de primos [13, 53, 31] esta en la lista de los No primos[42] del hilo Hilo 1
El hilo ha terminado

En esta corrida si te fijas los cálculos se han hecho de manera independiente, y el hilo 2 acabó antes que el uno.
Si bien tu ejemplo funciona, el código es muy educativo y parece escrito en tiempos de tus abuelitos, desde el ya obsoleto java 8 se agregaron nuevos APIs que nos permiten hacer ese código menos en el paradigma orientado a objetos y un poco más en el paradigma funcional.
como el orden realmente no te importa, se puede hacer el cálculo de esprimo tamién de manera paralela con el uso del Stream API de la siguente manera:
lista.stream().parallel().forEach(num->{
        for (int x = 2; x < num / 2; x++) {
            // Si es divisible por cualquiera de estos números, no
            // es primo
            if (num % x == 0) {
                lista_Noprimos.add(num);
                break;
            } //sino, es primo
            else {
                lista_primos.add(num);
                break;
            }

        }
    });

nota que .parallel() solito se encarga de crear tantos Threads como sea posible según las limitaciones de tu sistema para el código que le pases.
la llamada a forEach() es equivalente a un for mejorado, que internamente usa un iterador en vez de índices para recorrer la lista, y el parámetro que recibe es ni más ni menos que una función lambda, que como podrás intuir nos permite reducir mucho el código que se habría hecho en una clase interna anónima.
El código ya se ve mejorcito, pero sigue con muchos pasos para ser educativo, y estamos reservando en memoria un arreglo con el tamaño de 4 enteros por cada lista. Lo podemos modificar para usar colectores y que solito de manera paralela clasifique los números
public void esprimo() {

    Map<Boolean, List<Integer>> primosyNoPrimos = lista.stream().parallel().collect(Collectors.partitioningBy(num -> {
        for (int x = 2; x < num / 2; x++) {
            // Si es divisible por cualquiera de estos números, no
            // es primo
            return num % x != 0; //sino, es primo

        }
        System.err.println("El número no es positivo, no se trata de un primo a menos que se trate de Optimus Prime xD");
        return false;
    }));

    System.out.println("Esta es la lista de primos " + primosyNoPrimos.get(true) + " esta en la lista de los No primos " + primosyNoPrimos.get(false) + " del hilo " + Thread.currentThread().getName());
}

Ahora suponiendo que sea un fanático del paradigma funcional podrías reducir tu método a:
public void esprimo() {

    Map<Boolean, List<Integer>> primosyNoPrimos = lista
            .stream()
            .parallel()
            .collect(
                    Collectors.partitioningBy(num -> IntStream.range(2, num / 2)
                    .mapToObj(x -> num % x != 0)
                    .findFirst()
                    .orElse(false))
            );

    System.out.println("Esta es la lista de primos " + primosyNoPrimos.get(true) + " esta en la lista de los No primos " + primosyNoPrimos.get(false) + " del hilo " + Thread.currentThread().getName());
}

Que aunque está acomodado muy bonito tiene solamente dos líneas.
Para entenderlo solo toca observar que IntStream es un Stream pero optimizado para datos de tipos int, y que el método range trata de generar números en una secuencia del valor inicial al valor final, después simplemente nos da si para el índice dado el número en cuestion es primo o no, y al encadenar el método findFirst, el A´PIinternamente optimiza las llamadas para que no tengamos que generar todo el rango que especificamos inicialmente para el IntStream, sino solamente hasta que se cumpla la condición.
Lo último a destacar es que find first nos regresa una semi-mónada llamada Optional, que aunque si no la sabes usar puedes generar NPE (no, no se lee nepe, así se le conoce coloquialmente al NullPointerException), también cuando se usa de forma inteligente como acá nos da valores para los casos no contemplados, es decir, para los casos en que no se haya marcado como primo por el cálculo se encarga de marcarlo como no primo, y con eso te ahorras lidiar con los tipos de números no tan comunes como los imaginarios, los negativos, y demás condiciones raras que te pudieran sacar del espacio Z+ (léase este enunciado final de manera rimbombante).
Hace tiempo también me cree algún artículo sobre como generar series a partir de algún subconjunto como en este caso lo es el de los primos, y que puedes hallar en mi sitio con explicación de algunas cosas más acerca del uso de lambdas para hacer generadores.


text:
Q: CXF selective service exposure Can CXF services be exposed selectively to different consumers/clients?
for eg., if I have methods A, B, C, D in my WSDL, can i make only A, C available for one consumer and all the four methods for a different consumer?

A: Web service is just a URL and calling a WS method is a matter of sending properly formatted request wrapped in an envelope. From that description you can probably guess that you cannot hide or block some methods from certain clients. Your clients are free to send any request they want. The fact that the method does not exist in WSDL (if you manage to send different WSDL to different client) doesn't mean that method will disappear from service.
It's up to you to discover which client tries to connect and either allow or deny access to certain methods. Allow or deny are keywords here. You must implement some notion of authorization and authentication on top of your services and block some clients if they don't have permissions to certain methods.


text:
Q: Constantly freezes the Spring Tool Suite (STS) I recently started using the Spring Tool Suite (STS) for development under Spring Boot.
After not continuing the work after starting STS hangs tightly.
Used OS Linux Mint.
Tell me how to diagnose the problem of suspense?

A: If STS hangs, I would strongly recommend to:

*

*capture a thread dump while STS hangs (using jps and jstack)

*file an issue at https://github.com/spring-projects/spring-ide/issues and attach the full thread dump

*continue to capture thread dumps and attach them to the issue, sometimes slightly different thread dumps reveal interesting details

The thread dump usually reveals whether there is a thread deadlock under the hood, a network issue, or some other very long running process doing some work.

A: Faced similar issue in windows. Encountered when extracted by jar -xvf spring-tool-***.jar.
It has been resolved the way by which the jar is extracted by executing it rather extract directly.
java -jar spring-tool-***.jar


text:
Q: Handling slide movements cocos2d My game in cocos2d is handling touches from the user in a way that just get touches, but not slide/drag movements. How can I hlandle slide/drag movements in cocos2d/objective-c?
E.g. if the user slides the finger in any point of the screen above the sprite _player, I want to move the sprite _player up.
This is my function that is handling touches now:
-(void) touchBegan:(UITouch *)touch withEvent:(UIEvent *)event {

    CGPoint touchLocation = [touch locationInNode:self];

    positionY1 = self.contentSize.height*.2;
    positionY2 = self.contentSize.height*.40;
    positionY3 =  self.contentSize.height*.60;

    float distY1Y2 = (positionY1 + positionY2)/2;
    float distY2Y3 = (positionY2 + positionY3)/2;
    float playerMove;

    if (touchLocation.y  <= distY1Y2) {

        if(_player.position.y <= distY1Y2) {
            playerMove = positionY1;
        } else if(_player.position.y > distY1Y2 && _player.position.y < distY2Y3) {
            playerMove = positionY1;
        } else if (_player.position.y >= distY2Y3) {
            playerMove = positionY2;
        }

    } else  if (touchLocation.y  > distY1Y2 && touchLocation.y < distY2Y3) {

        if(_player.position.y <= distY1Y2) {
            playerMove = positionY2;
        } else if(_player.position.y > distY1Y2 && _player.position.y < distY2Y3) {
            playerMove = positionY2;
        } else if (_player.position.y >= distY2Y3) {
            playerMove = positionY2;
        }

    } else if (touchLocation.y  >= distY2Y3) {
        if(_player.position.y <= distY1Y2) {
            playerMove = positionY2;
        } else if(_player.position.y > distY1Y2 && _player.position.y < distY2Y3) {
            playerMove = positionY3;
        } else if (_player.position.y >= distY2Y3) {
            playerMove = positionY3;
        }
    }

    //play audio
    [[OALSimpleAudio sharedInstance] playEffect:@"pew-pew-lei.caf"];

    //Disable another touch movement
    //[[UIApplication sharedApplication] beginIgnoringInteractionEvents];

    // Move our sprite to touch location
    CCActionMoveTo *actionMove = [CCActionMoveTo actionWithDuration:.2f position:CGPointMake(_player.position.x, playerMove)];
    [_player runAction:actionMove];

    //Enable another touch movement

    //[[UIApplication sharedApplication] endIgnoringInteractionEvents];

    /*
    NSMethodSignature *sgn = [self methodSignatureForSelector:@selector(enableTouch:)];
    NSInvocation *inv = [NSInvocation invocationWithMethodSignature: sgn];
    [inv setTarget: self];
    [inv setSelector:@selector(enableTouch:)];
    [NSTimer scheduledTimerWithTimeInterval:.7f
                                 invocation:inv
                                    repeats:NO];

     */

}

A: I will share some code. Please go through this code.
Your Ques :  if the user slides the finger in any point of the screen above the sprite _player, I want to move the sprite _player up.
Ans :
This is for, if you touch the particular sprite and move that sprite......
-(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *myTouch=[touches anyObject];
    CGPoint point=[myTouch locationInView:[myTouch view]];
    point=[[CCDirector sharedDirector] convertToGL:point];
    NSLog(@"point is %@",NSStringFromCGPoint(point));
}
-(void) ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *myTouch=[touches anyObject];
    CGPoint point=[myTouch locationInView:[myTouch view]];
    point=[[CCDirector sharedDirector] convertToGL:point];
    CCNode *Sprite=[self getChildByTag:spriteTag]; // This is your sprite, which one you want to move.
    [Sprite setPosition:point];

   // This is the boundary for sprite, for what sprite is nor cross the screen.
    if(Sprite.position.y>245)
        [Sprite setPosition:ccp(Sprite.position.x,245)];
    if(Sprite.position.y<25)
        [Sprite setPosition:ccp(Sprite.position.x,25)];
    if(Sprite.position.x<15)
        [Sprite setPosition:ccp(15,Sprite.position.y)];
    if(Sprite.position.x>465)
        [Sprite setPosition:ccp(465,Sprite.position.y)];
}

This is for, if you touch anywhere on screen and move that sprite ......
// CGPoint initialPos; // in .h file

-(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint touchPt = [touch locationInView:touch.view];
    initialPos = [[CCDirector sharedDirector] convertToGL:touchPt];
}
-(void) ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *myTouch=[touches anyObject];
    CGPoint currentPos=[myTouch locationInView:[myTouch view]];
    currentPos=[[CCDirector sharedDirector] convertToGL:currentPos];

    float diffX = currentPos.x - initialPos.x;
    float diffY = currentPos.y - initialPos.y;

    CGPoint velocity = ccp(diffX, diffY);
    initialPos = currentPos;
    [Sprite setPosition:ccpAdd([SmileBall position], velocity)];
}

- (void) ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *myTouch=[touches anyObject];
    CGPoint currentPos=[myTouch locationInView:[myTouch view]];
    currentPos=[[CCDirector sharedDirector] convertToGL:currentPos];
    float diffX = currentPos.x - initialPos.x;
    float diffY = currentPos.y - initialPos.y;
    CGPoint velocity = ccp(diffX, diffY);
    initialPos = currentPos;
    [Sprite setPosition:ccpAdd([SmileBall position], velocity)];
}

I think this will help you :)


text:
Q: paint g method print out only last char from array Hi i have following problem my applet should print characters to applet along to vertical line, but it prints only last character from a string. i try to move repaint() method in different places outside inside the loop but it still print out only last character in string. When i use //System.out.print(letters[i]); or //System.out.println(text); to check what is the content of string or charArray it prints right output but my paint g method prints only the last char form array
Any suggestions??
public class ExtensionExercise extends Applet implements ActionListener {
    String text;
    String output;
    Label label;
    TextField input;
    int xCoordinates = 30, yCoordinates = 50;
    char letters [];
    public void init(){
        label = new Label("Enter word");
        add(label);
        input = new TextField(10);
        add(input);
        input.addActionListener(this);
    }
    public void start(){
        text = "";
    }
    @Override
    public void actionPerformed(ActionEvent event) {
        text = event.getActionCommand();
        letters = text.toCharArray();

        for(int i = 0; i<letters.length; i++){
            text = String.valueOf(letters[i]);
            xCoordinates +=10;
            yCoordinates +=10;
        }
        repaint();
    }
    @Override
    public void paint(Graphics g){
        g.drawString(text, xCoordinates, yCoordinates);
    }
}

A: You're only calling repaint once after the for loop so obviously only the last letter will appear. All the letter selection logic needs to appear in the paint method itself
@Override
public void paint(Graphics g) {
    super.paint(g);

    for (int i = 0; letters != null && i < letters.length; i++) {
        text = String.valueOf(letters[i]);
        g.drawString(text, xCoordinates, yCoordinates);
        // xCoordinates += 10; remove this
        yCoordinates += 10;
    }
}

Note you don't want to increment the xCoordinates offset to achieve vertical output


text:
Q: Copy data on parent and child table
I have two database tables. What I need to do is to copy specific data from one storage to another, but also keep the mapping to the photos. First part I can do easily writing
INSERT INTO item (storage_id, price, quantity, description, document_id)
SELECT 10, price, quantity, description, document_id
FROM item
WHERE quantity >= 10 AND price <= 100

but after that newly inserted items does not have photos. Note, that document_id field is unique for not copied items.

A: Assuming id columns are auto-generated surrogate primary keys, like a serial or IDENTITY column.
Use a data-modifying CTE with RETURNING to make do with a single scan on each source table:
WITH sel AS (
   SELECT id, price, quantity, description, document_id
   FROM   item
   WHERE  quantity >= 10
   AND    price <= 100
   )
, ins_item AS (
   INSERT INTO item
         (storage_id, price, quantity, description, document_id)
   SELECT 10        , price, quantity, description, document_id
   FROM   sel
   RETURNING id, document_id  -- document_id is UNIQUE in this set!
   )
INSERT INTO item_photo
      (item_id,    date,    size)
SELECT ii.id  , ip.date, ip.size
FROM  ins_item   ii
JOIN  sel        s  USING (document_id)   -- link back to org item.id
JOIN  item_photo ip ON ip.item_id = s.id; -- join to org item.id

CTE sel reads all we need from table items.
CTE ins_item inserts into table item. The RETURNING clause returns  newly generated id values, together with the (unique!) document_id, so we can link back.
Finally, the outer INSERT inserts into item_photo. We can select matching rows after linking back to the original item.id.
Related:

*

*Insert New Foreign Key Row for new Strings
But:

document_id field is unique for not copied items.

Does that guarantee we are dealing with unique document_id values?

A: Given that document_id is the same in the two sets, we can used that to ensure that after the first copy, that all duplicate entries that have photos are copied across.

Note: This is still a dirty hack, but it will work. Ideally with data synchronizations we make sure that there is a reference or common key in all the target tables. You could also use output parameters to capture the new id values or use a cursor or other looping constructs to process the records 1 by 1 and copy the photos at the same time instead of trying to update the photos after the initial copy stage.

This query will insert photos for items that do NOT have photos but another item with the same document_id does have photos.
INSERT INTO item_photo (item_id, "date", size)
SELECT "source_photo".item_id, "source_photo"."date", "source_photo". Size
FROM item "target_item"
INNER JOIN item "source_item" on "target_item".document_id = "source_item".document_id
INNER JOIN item_photo "source_photo" ON "source_item".id = "source_photo".item_id
WHERE "target_item".id <> "source_item".id
  AND NOT EXISTS ( SELECT id FROM item_photo WHERE item_id = "target_item".id)
  AND source_item.id IN (
                         SELECT MIN(p.item_id) as "item_id"
                         FROM item_photo p
                         INNER JOIN item i ON p.item_id = i.id
                         GROUP BY document_id
                        )


text:
Q: How to map a flat model to a Class that has a string property and IEnumerable using automapper I am new to automapper and am wondering how I could map a flat model into a Dto with 1 string property and IEnumerable
I have these classes
And I want to map this Model
public class DirectionModel
{
    public string DirectionId { get; set; }
    public decimal Longitude { get; set; }
    public decimal Latitude { get; set; }
}

To this DTO classes
public class DirectionDto
{
    public string DirectionId { get; set; }
    public IEnumerable<CoordinateDto> Coordinates { get; set; }
}

public class CoordinateDto
{
    public decimal Longitude { get; set; }
    public decimal Latitude { get; set; }
}

Sample Input:
IEnum<DirectionModel>()
{
    new DirectionModel() {DirectionId="id1", Longitude=1, Latitude=2},
    new DirectionModel() {DirectionId="id1", Longitude=3, Latitude=4},
    new DirectionModel() {DirectionId="id2", Longitude=5, Latitude=6}
}

This is the expecteed output:
IEnum<DirectionDto>()
{
    new DirectionDto() {DirectionId="id1", IEnum<CoordinateDto>(){new CoordinateDto(){Longitude=1, Latitude=2}, new CoordinateDto(){Longitude=3, Latitude=4}}},
    new DirectionDto() {DirectionId="id2", IEnum<CoordinateDto>(){new CoordinateDto(){Longitude=5, Latitude=6}}},
}

(edit: Corrected the sample input which may have caused confusion)

A: You can use AfterMap in AutoMapper, I prefer to use List instead of IEnumerable like this:
autoMapperConfig.CreateMap<List<DirectionModel>, List<DirectionDto>>()
                            .AfterMap((model, dto) =>
                            {
                                if (dto == null)
                                    dto = new List<DirectionDto>();

                                if (model.Any())
                                {
                                    dto.AddRange(model.GroupBy(x => x.DirectionId)
                                        .Select(x => new DirectionDto()
                                        {
                                            DirectionId = x.Key,
                                            Coordinates = x.ToList()
                                                .Select(c => new CoordinateDto()
                                                {
                                                    Latitude = c.Latitude,
                                                    Longitude = c.Longitude
                                                }).ToList()
                                        }).ToList());
                                }
                            });

And use it:
   var lists = new List<DirectionModel>()
            {
                new DirectionModel() {DirectionId = "id1", Longitude = 1, Latitude = 2},
                new DirectionModel() {DirectionId = "id1", Longitude = 3, Latitude = 4},
                new DirectionModel() {DirectionId = "id2", Longitude = 5, Latitude = 6}
            };

    var dtos = _mapper.Map<List<DirectionModel>, List<DirectionDto>>(lists);


text:
Q: Python - loop through files in different folders I want to extract data from multiple files nested within subfolders.
e.g. folder structure
A/B/C/D.dat
A/B/E/F.dat
A/B/G/H.dat

The code I came up with is:
import os
values = 2
doc = []
rootdir = 'C:/A/B'

for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        if file.endswith('.dat'):
            with open (file, 'rt') as myfile:
                    current_line = 0
                    for mylines in myfile:
                            if current_line == values:
                                doc.append()
                                break
                            current_line += 1
            continue

print(doc)

Error I struggle to solve:
...with open (file, 'rt') as myfile:
IOError: [Errno 2] No such file or directory: 'D.dat'

A: Though your solution is not the cleanest. The bug you are getting comes from
            with open (file, 'rt') as myfile:

which should be replaced with
            with open (subdir + "/" + file, 'rt') as myfile:

A: Error is due to missing of complete file path. So you need make sure that "A/B/C/D.dat" should be there in file which you are trying to open as myfile.
you can add the below snippet to your logic to achieve it.
for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        filepath=subdir+'/'+file

A: I had a similar problem. My file structure is something like this:
project
|__dir1
|  |__file_to_read.txt
|
|__dir2
   |__file_reader.py

In order to actually find the other file, I have to go out one directory, to the parent dir of my .py file. I used this code originally:
import os

current_path = os.path.dirname(__file__)

file_to_read = os.path.relpath('project/dir1/file_to_read', current_path)

This worked for me, but I later changed over to a different version. The reason is not for any reason you'll have to worry about, other than evidently this next module is better for path crawling than os.
from pathlib import Path

parent = Path.cwd().parent
file_to_read = Path(f'{parent}/project/dir1/file_to_read.txt').resolve()

Maybe this would be more preferable, as it's more highly recommended to me. I hope this helps your problem.

A: The issue here is that you are trying to call filename.dat. Instead you should access A/B/C/filename.dat .
Join the pathname + filename for this:
import os
values = 2
doc = []
rootdir = 'A/B/C/'

for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        if file.endswith('.txt'):
            print(file)
            file = os.path.join(rootdir,subdir,file)
            with open (file, 'rt') as myfile:
                    current_line = 0
                    for mylines in myfile:
                            if current_line == values:
                                doc.append(mylines)
                                break
                            current_line += 1
            continue

print(doc)

A: sounds like you are looking for the third line of all the .dat files in the subdirectories.  There are using pathlib.Path you can do quite a lot of this in a few simple steps.
from pathlib import Path
doc = []
line_number_of_each_file = values = 2

for file in Path('C:/A/B').rglob('*.dat'):
    doc.append(file.readtext().splitlines()[line_number_of_each_file])

print(doc)


text:
Q: How do I prove that group determined by generators and relations is trivial? I have a group $\langle a,b\mid a^4=b^2=1, ab^2=b^3a, ba^3=a^2b\rangle $ how do I show that it's trivial?

A: $a=ab^2=b^3a \implies b^3=1$. Then $b^2=1$ and $b^3=1$ imply that $b=1$. Then $ba^3=a^2b \implies a^3=a^2 \implies a=1$.

A: Since $b^2=1$,$$ab^2=b^3a\implies a=ba\implies b=1$$Then using this, $$ba^3=a^2b\implies a^3=a^2\implies a=1$$


text:
Q: Create function dynamically in a database HI i need to create a function dynamically in a database..My procedure accepts Database name  as a parameter, then i need to create this function dynamically in that DATABASE.
But i am unable to execute this..please help me.Regards in advance
Create procedure [dbo].[Sp_Insertfun]
(
@OrgName nvarchar(100)
)
AS BEGIN
Declare @orgdataInsertString nvarchar(max);

set @orgdataInsertString='Use '+@OrgName+'' ;

set @orgdataInsertString=@orgdataInsertString+char(13)+char(10)+'GO'+'
Create function dbo.[fn_GroupDisplay](@GroupID int)

RETURNS @Group TABLE
(

GrpPath nvarchar(max)

)
as
begin
declare @ParentId1 int
declare @ParentId2 varchar(50)
declare @ParentId3 varchar(50)
declare @parentId4 varchar(50)
declare @Text nvarchar(max)

set @ParentId3=''''
begin
set @ParentId1=(select ParentID from GroupDetails where GroupID=@GroupID)
set @ParentId4=(select GroupName from GroupDetails where GroupID=@GroupID)

while(@ParentId1>0)
begin
set @parentId2=(select GroupName from GroupDetails where GroupID=@ParentId1 )
set @ParentId3 =  @ParentId2+ ''\'' + coalesce(@ParentId3,''')
set @ParentId1=(select  ParentID from GroupDetails where GroupID=@ParentId1 )
end
set @Text=@ParentId3+@ParentId4
INSERT INTO @Group VALUES (@Text)
end
RETURN
end'

execute sp_executesql @query=@orgdataInsertString
print @orgdataInsertString
end


text:
Q: How i can replace None value in list with int? enter code hereSo, Basically I have a list with int values, and I want to see which values are missing in List. To do that I am comparing Value with a range from 1 to 9 (range(1,9)).
matrix = [None, 8, 3, 9, 2, 1, 6, 5, None]

when i run this code:
for row in matrix:
       if range(1,9) not in row :
                print(row)
        else:
            print('wrong logic')

I am getting this error
TypeError: 'NoneType' object cannot be interpreted as an integer

A: We can see this as a difference of two sets, one with all numbers of interest and one with the numbers in your list. All you need to do is to subtract the set with all numbers by the set with the values in your list.
list = [None, 8, 3, 9, 2, 1, 6, 5, None]
missing_numbers = set(range(1,9)) - set(list)
print(missing_numbers)

This will print {4, 7}.

A: Remove the Nones from the list before evaluating whether the range is in the list.
start_list = [None, 8, 3, 9, 2, 1, 6, 5, None]
new_list = [item for item in start_list if item is not None]

And then check for numbers 1-9 in the new list.
Another way to do this without even removing the Nones is to just loop through the numbers 1-9 and check if they are in the list.
start_list = [None, 8, 3, 9, 2, 1, 6, 5, None]
missing = []
for num in range(1,10):
    if num not in start_list:
        missing.append(num)
print(missing)

A: the range function takes integers as its arguments. you cannot pass it a None value. You can convert your None values to zero's first.
my_list = [None, 8, 3, 9, 2, 1, 6, 5, None]
my_list = [item if item else 0 for item in my_list]
print(my_list)

OUTPUT
[0, 8, 3, 9, 2, 1, 6, 5, 0]

A: Requirement is not very clear but I suppose you want to compare values to list and finally print the missing numbers.
A possible approach to obtain the missing values in list_to_check is to compare if its entries are present in good_values and, if so, remove them from good_values.
What will be left is just the missing entries in list_to_check.
list_to_check = [None, 8, 3, 9, 2, 1, 6, 5, None]
good_values = list(range(1, len(list_to_check) + 1))

for number in list_to_check:
    if number in good_values:
        good_values.remove(number)
print(good_values)

Output
[4, 7]

Edit

Now I read from comments that you would also like to add the missing numbers in place of the None items.
Here's a more verbose and easy to understand solution:
list_to_check = [None, 8, 3, 9, 2, 1, 6, 5, None]
good_values = list(range(1, len(list_to_check) + 1))

for number in list_to_check:
    if number in good_values:
        good_values.remove(number)

result = []

for value in list_to_check:
    if value is None:
        result.append(good_values.pop())
    else:
        result.append(value)

print(result)

Output:
[7, 8, 3, 9, 2, 1, 6, 5, 4]

For reasons that I do not fully understand if you are not using list comprehensions in your Python code you are simply not cool.
Let's also be cool, then!
Here's a shorter solution for the same problem:
list_to_check = [None, 8, 3, 9, 2, 1, 6, 5, None]
good_values = list(range(1, len(list_to_check) + 1))

for number in list_to_check:
    if number in good_values:
        good_values.remove(number)

print([good_values.pop() if value is None else value for value in list_to_check])

Output
[7, 8, 3, 9, 2, 1, 6, 5, 4]


text:
Q: How to fake submit with a button outside the form I want to have a top menu with New, Save, Cancel buttons and below, 3 different entry forms, similar to a "desktop application". When form1 is filled up, Save button would submit the form. Also, if form2 or form3 are filled up, the same Save button can submit the form, taking into account that is in a different form.
Is it possible to do this, a submit button outside form tags ?
If not, any suggestion how to fake submit?
Thanks for your help

A: You just have to trigger the submit event with .submit in jQuery by example.
Here is the doc : http://api.jquery.com/submit/

A: Instead of an <input type="submit"> button or jQuery call you could use the new HTML5 <button> element and its form attribute to specify which form(s) the button belongs to. Then just set its formaction attribute to the required destination. Documentation
Example:
<form id="form1">
    ...
</form>
<form id="form2">
    ...
</form>
<form id="form3">
    ...
</form>
<button form="form1 form2 form3" formaction="processForm.php" formmethod="POST">
    Submit
</button>

A: You can use
 $("#formId").submit(function() { /*your stuff*/ });


text:
Q: Equal split of vector using two label vectors I have a matrix consisting of three numerical vectors data=[kids,mothers,fathers] in which each vector contains the IDs of kids and their mothers and fathers. The IDs of kids are unique, but the IDs of fathers and mothers are non-unique (siblings and half-siblings exist). I wish to split the kids vector into two vectors of equal size with no family relationships across these vectors. I want these vectors to be as large as possible, but it may occur that some kids need be discarded to ensure equally sized vectors.
My current approach is to count the size of each 'family group' (=kids related through either parent) and then build equally sized groups using the size of each family.So far I've managed to count the number of kids that each mother or father has with:
mothersKids = arrayfun(@(x)nnz(mothers==x), mothers);
mothersKids = unique([mothers,mothersKids],'rows');
fathersKids = arrayfun(@(x)nnz(fathers==x), fathers);
fathersKids = unique([fathers,fathersKids],'rows');

This tells me how many kids are related to a single parent. Using the parent's ID I can figure out which kids are related and build groups based on that. However, I can't figure out how to combine the information of both parents to create the 'family groups'.
As a side-note: if a case occurs where kid A is related to kid B through one parent and kid B is related to kid C through one parent, but no relationship exists between kid A and kid C then for simplicity I will accept it if kid A and kid C are placed in the same family group.
EDIT::
Minimal example:
Input:
data = [1,2,3,4,5,6; 11,11,12,12,13,14; 21, 22, 23, 23, 24, 25]; % = [kids,mothers,fathers]

Output:
kidsInSameFamily = {[1,2],[3,4],[5],[6]};
groupOne = [1,2,5];
groupTwo = [3,4,6];

A: Resolved this by building an adjacency matrix and using that to find subgraphs. Building groups of equal size seems to be a variation on the partition problem (Partition Problems Brute Force Algorithm), for which a MATLAB script that I may need to modify for my needs exists at https://people.sc.fsu.edu/~jburkardt/m_src/partition_problem/partition_problem.html
% Get kids associated through their mother.
storepairs =[];
for mom = unique(mothers)'
    idx = find(mothers==mom);
    if numel(idx) > 1
        pairs = nchoosek(idx,2);
        storepairs = [storepairs; pairs];
    end
end
% Get kids associated through their father.
for dad = unique(fathers)'
    idx = find(fathers==dad);
    if numel(idx) > 1
        pairs = nchoosek(idx,2);
        storepairs = [storepairs; pairs];
    end
end

% Make pairs symmetric
storepairs = [storepairs; fliplr(storepairs)];
% Add diagonal
storepairs = [storepairs; [1:size(data,1); 1:size(data,1)]'];
% Remove non-unique pairs
storepairs = unique(storepairs,'rows');
% Build adjacency matrix
A = sparse(storepairs(:,1),storepairs(:,2),1);
% Create a graph object
G = graph(A);
% Get sub-graphs within graph
SG = conncomp(G);

% Kids in same family
kidsInSameFamily={};
for ii = 1:max(SG)
    kidsInSameFamily{ii} = kids(SG==ii);
end


text:
Q: How to disable code inspections for piece of code? In PhpStorm I can use tags
@codeCoverageIgnoreStart
@codeCoverageIgnoreStop

to disable coverage checking for piece of code.
Is there something similar for disabling code inspections for piece of code?


text:
Q: In Excel VBA 2010: How to destroy excel vba.application object I have an Excel.Application object which seems to live on as a Windows Process AFTER my VBA code has executed and Excel 2010 is completely closed out.
i.e. Windows Task Manager shows the Process as "EXCEL.EXE *32", even after I've closed Excel.
Here's some code below :
Public Sub Test
   Dim xls As Object
Set xls = CreateObject("Excel.Application")
Set wb = xls.Workbooks.Add

fullFilePath = importFolderPath & "\" & "A1"
wb.SaveAs fullFilePath, AccessMode:=xlExclusive    ' SAVE WORKBOOK AND CLOSE !
wb.Close (True)

' question: How can I destroy the xls object ????

end sub
Basically I can't figure out how to destroy the "xls" I've created in my code. And as I've stated above, it causes EXCEL.EXE *32 to live on as a windows process.
thanks in advance....
Bob

A: Use xls.Quit after you close the workbook


text:
Q: Oyster Prey Probability In an oyster experiment, an oyster predator is placed in the center of a tray with two oysters and two of other prey nearby.  The experimenter notes the order of the preying on the oysters - for example, if the predator preys upon the two oysters first, the order would be $1, 2$; if on the oysters last, it would be $3, 4$.
I wrote out the sample space for the question which gave me,
$$\{(1,2),(1,3),(1,4),(2,3),(2,4),(3,4)\}$$
Let $X$ denote the sum of the orders of preying on the two oysters.  Find the probability distribution of $X$ under the assumption that the predator chooses randomly among its available prey at each state.(Note that after preying upon an animal, that animal is killed, so it is not involved at the next choice stage.)
what can I do for this?

A: Guide:
You have listed out all the possibilities. Each of the possibilities happen with probability $\frac16$.
For each of the possibility, compute their sum, for example the sum for $(1,2)$ would be $3$. Do it for all  the $6$ possibilities.


text:
Q: java command works but javac command doesn't? I have downloaded the jdk 1.8.0_131
when I open the command prompt and write the following command - java -version it gives me the output
java version "1.8.0_131"
Java(TM) SE Runtime Environment (build 1.8.0_131-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.131-b11, mixed mode)

but when I write the following command: javac -version it gives me the output
'javac' is not recognized as an internal or external command,
operable program or batch file.

I have edit the system variables path to - C:\Progra~1\Java\jdk1.8.0_131\bin;
and when I do the following command : "C:\Program Files\Java\jdk1.8.0_131\bin\javac" -version
it gives me the output:
javac 1.8.0_131

So i know I have installed the correct java version
I also checked the above folder and did find a javac.exe there. Please help.
Edit:
I finally solved the problem. What I was doing is editing the "Path" variable when what I had to do was make a new variable called "PATH" and the the following details :
Variable name  : PATH
Variable value : c:\Program Files\Java\jdk1.8.0_xx\bin;[Existing Entries...

A: Have you tried restarting "cmd.exe" since adding the bin directory to your PATH?
If you confirm that your PATH includes the java bin directory and you can see the "javac.exe" binary in that location, then all should be set up correctly.

A: In Windows you need to add path to the jdk_your_version/bin to the PATH variable. Add this line to the PATH:
C:\Progra~1\Java\jdk1.8.0_131\bin;

Save it. Then restart CMD since it does not update the path automatically for the open cmd. Then you should be able to see that javac is working:
javac -version


text:
Q: Как сделать конфигурации debug и release одинаковыми? У меня есть проект A, написанный под .net FrameWork 4.0. В нём используется метод Load из одной библиотеки. Эта библиотека собрана из другого проекта B, написанного под Silverlight 5. И во время отладки, при вызове этого метода Load, у меня возникает ошибка:
Unexpected error: Не удалось загрузить файл или сборку "System.Xml, Version=5.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e" либо одну из их зависимостей. Не удается найти указанный файл.,    в )
При этом всём, в релизной сборке проекта A такой ошибки не возникает и всё работает корректно.
Можете объяснить из-за чего это происходит и как мне сделать конфигурации debug и release одинаковыми, чтобы и при отладке ошибки не было?


text:
Q: Tailwind-CSS config-file not "loading" I wanted to change the min-width of the screensize "md" in the config file but it's not loading it. The file is in the right place, written as in the docs and I even tried loading it manually, by writing it's directory in the tailwindcss watch-command

My config-file:

/** @type {import('tailwindcss').Config} */
module.export = {
  content: ["./src/**/*.{html,js}"],
  theme: {
    extend: {
      'sm': '640px',
      // => @media (min-width: 640px) { ... }

      'md': '924px',
      // => @media (min-width: 768px) { ... }

      'lg': '1024px',
      // => @media (min-width: 1024px) { ... }

      'xl': '1280px',
      // => @media (min-width: 1280px) { ... }

      '2xl': '1536px',
      // => @media (min-width: 1536px) { ... }
    },
  },
  plugins: [],
}

A: You define your project's breakpoints in the theme.screens section or theme.extend.screens of your tailwind.config.js file. Your screen configuration should be wrapped inside screens object
/** @type {import('tailwindcss').Config} */
module.export = {
  content: ["./src/**/*.{html,js}"],
  theme: {
    extend: {
      screens: {
        'sm': '640px',
        // => @media (min-width: 640px) { ... }

        'md': '924px',
        // => @media (min-width: 768px) { ... }

        'lg': '1024px',
        // => @media (min-width: 1024px) { ... }

        'xl': '1280px',
        // => @media (min-width: 1280px) { ... }

        '2xl': '1536px',
        // => @media (min-width: 1536px) { ... }
      }
    },

  },
  plugins: [],
}


text:
Q: Why is ViewPager2 delaying to load pages? I decided to give a try on the new and now available stable release of ViewPager2.
My ViewPager2 have a lot of pages, and  I am using TabLayout to give each page (fragment) scrollable tab titles, but I am facing a delay when loading the ViewPager2 for the first time in my view.
Is this the normal behavior?

A: I figured it out what was causing the ViewPager2 initial delay to load the pages.
It happens I was using TabLayout from com.google.android.material.tabs.TabLayout along with the ViewPager2 to give scrollable tab titles to each page. But if you have a lot of pages which is my case, the UI takes time to setup each tab and place in the UI.
The solution is to remove the TabLayout from ViewPager2, and if you need to display a title, use the ToolBar as title page indicator for each page by changing and setting ToolBar text according to your needs.
Looking the bright side you end up with more clean UI, by having more space in screen for your  ViewPager2 to display its content to the user.
Another thing I noticed is if you want to take full advantage of ViewPager2 performance benefits, then use the default viewpager's offscreenPageLimit, as stated bellow:

public void setOffscreenPageLimit (int limit)
Set the number of pages that should be retained to either side of the currently visible page(s). Pages beyond this limit will be recreated from the adapter when needed. Set this to OFFSCREEN_PAGE_LIMIT_DEFAULT to use RecyclerView's caching strategy. The given value must either be larger than 0, or #OFFSCREEN_PAGE_LIMIT_DEFAULT.
Pages within limit pages away from the current page are created and added to the view hierarchy, even though they are not visible on the screen. Pages outside this limit will be removed from the view hierarchy, but the ViewHolders will be recycled as usual by RecyclerView.
This is offered as an optimization. If you know in advance the number of pages you will need to support or have lazy-loading mechanisms in place on your pages, tweaking this setting can have benefits in perceived smoothness of paging animations and interaction. If you have a small number of pages (3-4) that you can keep active all at once, less time will be spent in layout for newly created view subtrees as the user pages back and forth.
You should keep this limit low, especially if your pages have complex layouts. By default it is set to OFFSCREEN_PAGE_LIMIT_DEFAULT.

https://developer.android.com/reference/androidx/viewpager2/widget/ViewPager2.html#setOffscreenPageLimit(int)
That being said I strongly recommend the replacement of your ViewPager to ViewPager2 for all cases, because  ViewPager is no longer receiving Google support, and ViewPager2 has a lot to offer other than what I spoke here:

RTL (right-to-left) layout support
Vertical orientation support
Reliable Fragment support (including handling changes to the underlying Fragment collection)
Dataset change animations (including DiffUtil support)

https://developer.android.com/jetpack/androidx/releases/viewpager2

A: There's a whole set of improvements over ViewPager:

*

*RTL (right-to-left) layout support

*Vertical orientation support

*Reliable Fragment support (including handling changes to the underlying Fragment collection)

*Dataset change animations (including DiffUtil support)

These features will never be fixed in ViewPager, so migrating to ViewPager2 would be the only way to get these features.


text:
Q: Sending JSON data from raspberry pi to Bluemix MQTT broker I have been looking all around on how to send data as JSON objects over to the  IBM Bluemix broker using paho python from raspberry pi ....can anyone pls help

A: Assuming you are trying to use the IOT service then I suggest you look at this:
https://developer.ibm.com/iot/recipes/raspberry-pi/


text:
Q: Compactness of Pseudo-differential Operators on $H^s(\mathbb R^n)$? The Sobolev space of order $s\in\mathbb R$ in $\mathbb R^n$, denoted by $H^s(\mathbb R^n)$, is defined as follows:
$$H^{s}(\mathbb R^n):=\{u\in\mathscr{S}^{'}(\mathbb R^n): \exists f\in L^1_{\textrm{loc}}(\mathbb R^n); (1+|\cdot|^2)f\in L^2(\mathbb R^n)\ \textrm{and}\ \hat{u}=T_f\}.$$
Above $T_f$ is the tempered distribution given by $$\langle T_f, \varphi\rangle:=\int_{\mathbb R^n} f(x)\varphi(x)\ dx,\ \forall \varphi\in C^\infty_0(\mathbb R^n).$$
I'm studying this space in the context of pseudo-differential operators with symbols in the class $S^m_{1, 0}$.
Can anyone recommend me a book or a paper which deals with the compactness of those operators when acting on $H^{s}(\mathbb R^n)$?
Obs: $\mathscr{S}^{'}(\mathbb R^n)$ is the space of continuous linear functionals on the Schwartz Space $\mathscr{S}(\mathbb R^n)$.


text:
Q: WPF IValueConverter.ConvertBack not called I have some code below which is a simplified example of what I'm trying to do.  I'm using a converter to try to fill a DataGrid with data from a model that I have.  The DataGrid is being populated correctly, but any changes in the grid are not being persisted back to the objects.  I have specified the mode as TwoWay.  When I put a breakpoint on the converters ConvertBack method, it is never being called.
I am fairly new to WPF and MVVM, so I don't see what I'm doing wrong.  There is not much I can do to change the model, so I'd like to see if this can work unless there is a clearly superior method.
XAML:
<Window x:Class="SampleBindingProblem.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:SampleBindingProblem"
        Title="MainWindow" Height="400" Width="500">
    <Window.Resources>
        <ResourceDictionary>
            <local:ScenarioDataTableConverter x:Key="ScenarioDataTableConverter" />
        </ResourceDictionary>
    </Window.Resources>
    <Grid>
        <ListBox ItemsSource="{Binding Scenarios}">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <DataGrid Margin="5" ItemsSource="{Binding Path=Options, Mode=TwoWay, Converter={StaticResource ScenarioDataTableConverter}}" />
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ListBox>
    </Grid>
</Window>

App.xaml.cs:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.Globalization;
using System.Windows;
using System.Windows.Data;

namespace SampleBindingProblem
{
    public class ColumnInfo
    {
        public static readonly String[] ColumnLabels = new String[] { "Variable1", "Variable2", "Variable3", "Variable4", "Variable5" };
    }

    public class ScenarioOption
    {
        public String Label { get; set; }
        public String[] Variables { get; set; }
    }

    public class Scenario
    {
        public ScenarioOption[] Options { get; set; }
    }

    internal class ScenarioDataTableConverter : IValueConverter
    {
        public Object Convert (Object value, Type targetType, Object parameter, CultureInfo culture)
        {
            if (value == null)
                return (null);

            ScenarioOption[] options = (ScenarioOption[]) value;

            DataTable table = new DataTable();

            table.Columns.Add("Label", typeof(String));
            for (Int32 c = 0; c < ColumnInfo.ColumnLabels.Length; ++c)
                table.Columns.Add(ColumnInfo.ColumnLabels[c], typeof(String));
            foreach (ScenarioOption option in options)
            {
                DataRow row = table.NewRow();
                List<String> lst = new List<String>();
                lst.Add(option.Label);
                lst.AddRange(option.Variables);
                row.ItemArray = lst.ToArray();
                table.Rows.Add(row);
            }

            return (table.DefaultView);
        }

        public Object ConvertBack (Object value, Type targetType, Object parameter, CultureInfo culture)
        {
            return (null);
        }
    }

    internal class ViewModel : INotifyPropertyChanged
    {
        public void RaisePropertyChanged (String property)
        {
            if (this.PropertyChanged != null)
                this.PropertyChanged(this, new PropertyChangedEventArgs(property));
        }

        public event PropertyChangedEventHandler PropertyChanged = null;

        public ObservableCollection<Scenario> Scenarios { get; set; }

        public ViewModel ()
        {
            Scenario s1 = new Scenario();
            s1.Options = new ScenarioOption[] {
                new ScenarioOption() { Label = "Opt1", Variables=new String[] { "1", "2", "3", "4", "5" } },
                new ScenarioOption() { Label = "Opt2", Variables=new String[] { "2", "3", "4", "5", "6" } },
                new ScenarioOption() { Label = "Opt3", Variables=new String[] { "3", "4", "5", "6", "7" } },
            };
            Scenario s2 = new Scenario();
            s2.Options = new ScenarioOption[] {
                new ScenarioOption() { Label = "Opt1", Variables=new String[] { "1", "2", "3", "4", "5" } },
                new ScenarioOption() { Label = "Opt2", Variables=new String[] { "2", "3", "4", "5", "6" } },
                new ScenarioOption() { Label = "Opt3", Variables=new String[] { "3", "4", "5", "6", "7" } },
            };

            this.Scenarios = new ObservableCollection<Scenario>();
            this.Scenarios.Add(s1);
            this.Scenarios.Add(s2);
        }
    }

    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        private void Application_Startup (Object sender, StartupEventArgs e)
        {
            MainWindow window = new MainWindow();
            window.DataContext = new ViewModel();
            window.ShowDialog();
        }
    }
}

A: Converters don't work that way when it comes to collections. ConvertBack will only be called when the entire collection is replaced. It won't be called when an item in the collection is modified. In your case the collection (the DataView) isn't being replaced with a new DataView instance, but rather modified, and that's why ConvertBack isn't being called.
If you ask me, I don't see why you need to use the converter anyway. Either bind directly to the Scenarios property and work on this collection that is exposed by the view model, or alternatively call the conversion code in your viewmodel and expose the resulting DataView in a different property. Then you'll just need to bind to that property without specifying a converter.

A: This sounds like the classic beginner's mistake... I think that you need to implement the INotifyPropertyChanged Interface in your model classes. The idea is that you inform the INotifyPropertyChanged interface when any property value changes. From the linked page on MSDN:
public string CustomerName
{
    get
    {
        return this.customerNameValue;
    }
    set
    {
        if (value != this.customerNameValue)
        {
            this.customerNameValue = value;
            NotifyPropertyChanged();
        }
    }
}

The UI can then be updated from the model class and the model class will be able to be updated from changes in the UI. See the linked page on MSDN for the full example.

Also, you don't need to declare a ResourceDictionary in the Window.Resources section... it is a ResourceDictionary:
<Window.Resources>
    <local:ScenarioDataTableConverter x:Key="ScenarioDataTableConverter" />
</Window.Resources>


text:
Q: Why does a large border-radius value cause chrome to hide the image? I have a 128px image with a border-radius to make it appear rounded (I'm actually using the .is-rounded class from Bulma to do this). This is the resulting CSS on the image:
.image img.is-rounded {
    border-radius: 9999px;
}

This works in Firefox but in Chrome, the image is hidden.
If I change it to the following, it works:
.image img.is-rounded {
    border-radius: 63px;
}

But anything beyond 63px, the image is hidden again:
.image img.is-rounded {
    border-radius: 64px;
}

You can see this on my personal website here: https://dominick.cc/
Chrome 110.0:

Firefox:

A: I updated Chrome to 110.0.5481.100 and it seemed to resolve it. Weird!


text:
Q: Problem with a $_POST in a while (POST sent by a JS pop up) I have a problem, I want to create a popup for my forum which says "Are you sure you want to delete on category?" and if click on yes, delete the category. But I have a problem, my sql request deletes all categories and not only one. Can you help me?
The code (Commented for you):
    while ($c = mysqli_fetch_assoc($result)) { // The wile
        if (isset($_SESSION['steamid'])) { // Check if user connected
            include('../script/steamlogin/userInfo.php');
            if (IsAdmin($steamprofile['steamid'])) { // Check if user is an admin
        ?>

<?=$c['name']?> Remove

Are you sure you want to delete this category?

                <button class="button_popup close_button">No</button>
                <button class="button_popup close_button" onclick='document.getElementById("remove").submit()'>Yes</button>

            <form id="remove" method="post"><input type="hidden" name="remove" /></form>

        <?php

            if (isset($_POST['remove'])) { // The remove script
                if (isset($_SESSION['steamid'])) {
                    include('../script/steamlogin/userInfo.php');
                    if (IsAdmin($steamprofile['steamid'])) {
                        mysqli_query($base, 'DELETE FROM `forum_categories` WHERE `id`="'.$c['id'].'"');
                        header('Location: index.php');
                    }
                }
            }

JS:
var modal = document.getElementById("popup");
var btns = Array.prototype.slice.call(document.querySelectorAll(".remove_openpopup"));
var span = document.querySelectorAll(".close_button")[0];

btns.forEach(function(btn) {
  btn.onclick = function() {
    modal.style.display = "block";
  }
});
span.onclick = function() {
  modal.style.display = "none";
}

window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}

I think its cause of the unique name remove, I think fix this with a array variable but how can I make and unlimited array value?
My idea:
$name = array('1' => 'remove1', '2' => 'remove2', '3' => 'remove3');

And after:
$c[$name][$VARIABLE WHICH COUNT THE WHILE]

Do you see what I mean? Have you got an idea? (For make the array unlimited)

A: you must create a saparate file to delete the categorie and proper validation with session
then you need to call this file from jquery in ajax call.
Example for ajax call is given below
To make ajax request using jQuery you can do this by following code
HTML:
<form id="foo">
    A bar
    <input id="bar" name="id" type="hidden" value="" />
    <input type="submit" value="Send" />
</form>

JavaScript:

/* Get from elements values */
var values = $(this).serialize();
$.ajax({
  url: "delete.php",
  type: "post",
  data: values,
  success: function(response) {
      // you will get resp`enter code here`onse from your php page (what you echo or print)
   },
 error: function(jqXHR, textStatus, errorThrown) {
       console.log(textStatus, errorThrown);
  }   });

In delete.php write your delete logic.

 <?php

    if (isset($_POST['remove'])) { // The remove script
        if (isset($_SESSION['steamid'])) {
            include('../script/steamlogin/userInfo.php');
            if (IsAdmin($steamprofile['steamid'])) {
                mysqli_query($base, 'DELETE FROM `forum_categories` WHERE `id`="' . $_POST['id'] . '"');
                echo "delete";
            } else {
                echo "something went wrong";
            }
        }
    }
    ?>

Hope this will help you


text:
Q: Running out of memory and process killed during Cholesky decomposition with Dask I'm trying to compute the cholesky decomposition of a matrix with 49152x49152 elements (around 19 Gb) in a laptop with only 16 Gb of RAM. I've seen that using dask it's possible to work with matrices that does not fit in memory, but running my code it always run out of memory (it does not matter if I change the number of chunks).
Here is where my code breaks:
M3 is a (49152, 49152) matrix, definite positive and non-singular.
M3 = da.rechunk(M3, chunks = (Chunks, Chunks))
chol_x2 = da.linalg.cholesky(M3, lower=True)
da.to_npy_stack("./Prueba_Nside_64", chol_x2)
old_name = "./Prueba_Nside_64/0.npy"
new_name = "./Prueba_Nside_64/Cholesky_Decomposition_Nside_64.npy"
os.rename(old_name, new_name)

I've tried different Chunks, always checking that each chunksize is less than 1Gb. I'm not sure if the problem is the cholesky decomposition or the .to_npy_stack function. Which function should I use to save the cholesky decomposition?
I've just realized the code breaks if I try to compute a single element from cholesky. How could I compute the cholesky in my own laptop? Or maybe it's not even possible?

A: I did a few tests with my laptop also with 16GiB.
I reproduced out of memory error on workers with just this code:
import dask
import dask.array as da

x = da.random.random((49152,49152))
x3 = da.tril(x, k = -1)
da.to_npy_stack("./Prueba_Nside_64", x3)

At first I thought this came from the tril function, but it is actually the to_npy_stack call that is causing issues.
Indeed, storing as Numpy stack requires chunking in only one axis, so it triggers some rechunking that fills Worker memory.
Just using another format (that can directly write the dask array chunks) did the trick for me:
x3.to_zarr("./Prueba_zarr")


text:
Q: Выпадающее меню при наведении на вышестоящее меню Есть код

                    <button data-toggle="dropdown" data-target="#menu" class="hamburger animated fadeInLeft noclose is-open" type="button">

                    </button>

КАТАЛОГ ТОВАРОВ

Главная

Новости

Прайс

Услуги

Услуга 1

Услуга 2

Услуга 3

Услуга 1

Услуга 2

Услуга 3

Услуга 4

Услуга 5

Услуга 4

Услуга 5

Контакты

В результате подменю

отображается сразу при загрузке, а не при наведении на вышестоящий пункт меню - Услуги. Как добиться отображение подменю при наведении на вышестоящий пункт меню?

A: В первом приближении так, но у вас, судя по классам, все это дело должен делать скрипт из коробки! Бутстрап (CSS+JS) подключен? И кнопка-бутерброд обычно ВНЕ списка, вомзожно у вас ошибка в верстке.

.left-menu ul ul {display:none}
.left-menu ul li:hover > ul{display:block}

                    <button data-toggle="dropdown" data-target="#menu" class="hamburger animated fadeInLeft noclose is-open" type="button">

                    </button>

КАТАЛОГ ТОВАРОВ

Главная

Новости

Прайс

Услуги

Услуга 1

Услуга 2

Услуга 3

Услуга 1

Услуга 2

Услуга 3

Услуга 4

Услуга 5

Услуга 4

Услуга 5

Контакты


text:
Q: Delphi - Text is printed out on black background I print out text on the printer canvas using Printer.Canvas.TextOut().
I have several printer jobs defined - some for graphics and some for plain text. This has worked fine until now. Now I have a problem that plain text prints out on a black background.
This happens only if I do a graphical print before a text print (it doesn't matter whether the same printer is used or not).
I have no idea what is causing this problem. I don't set a black background anywhere. So I hope that you can help.
The problem appears with PCL & Postscript.
In the print preview of my PCL-printer, everything looks fine. However, the final print on paper is black on black again.
Could there be a transparency flag causing this problem?

Edit: It seems the transparency was causing the problem. If I use:
SetBkMode( Printer.Canvas.Handle, TRANSPARENT );

before printing the plain text, everything works fine now.  It seems I messed up something somewhere.

A: Setting the BkMode to transparent solved the problem - but it was only a workaround.
The reason for the problem was that in the graphic print, Printer.Canvas.Brush.Color was being set to clBlack when drawing solid circles. And this value was not being reset correctly.


text:
Q: Counting the number of ways three dice can sum to $n$ I want to count in how many ways three dice can sum to a given number without brute forcing it. In fact, I would like to do it using generating functions and without having to expand out the product.

To do this, I have thought of making a differential equation out of $y=(x+x^2+x^3+x^4+x^5+x^6)^3$ and then solving the equation through the use of power series, or getting the $n$th taylor coefficient from the equation.

What I attempted was:
$$y=(x+x^2+x^3+x^4+x^5+x^6)^3$$
$$y'=3y^{2/3}(1+2x+3x^2+4x^3+5x^4+6x^5)$$
Then, by setting $x=0$ we see $y(0)=0$ and $y'(0)=0$, which is what I want, however, when trying to obtain $y''(0)$ by differentiating both sides, I get division by $0$ on the RHS.

Am I making a mistake in the set up or is calculating the expression through the use of a differenrial equation impossible?

A: Here is an alternate approach. We could at first  transform  $y(x)$ so that an expansion after that becomes less cumbersome. Maybe this variant is also useful for your needs.
It is convenient to use the coefficient of operator $[x^n]$ to denote the coefficient of $x^n$ of a series. We also use Iverson brackets
\begin{align*}
[[P(x)]]=\begin{cases}
1&\qquad P(x) \ \text{  true}\\
0&\qquad P(x) \ \text{ false}
\end{cases}
\end{align*}
This way we can treat multiple cases in one expression.

We obtain
  \begin{align*}
[x^n]y(x)&=[x^n](x+x^2+x^3+x^4+x^5+x^6)^3\\
&=[x^n]x^3(1+x+x^2+x^3+x^4+x^5)^3\\
&=[x^{n-3}][[n\geq 3]]\left(\frac{1-x^6}{1-x}\right)^3\tag{1}\\
&=[x^{n-3}][[n\geq 3]](1-3x^6+3x^{12}-x^{18})\sum_{j=0}^\infty\binom{-3}{j}(-x)^j\tag{2}\\
&=\left([x^{n-3}][[n\geq 3]]-3[x^{n-9}][[n\geq 9]]\right.\\
&\qquad\quad\left.+3[x^{n-15}][[n\geq 15]-[x^{n-21}][[n\geq 21]\right)
\sum_{j=0}^\infty\binom{j+2}{2}x^j\tag{3}\\
&=\binom{n-1}{2}[[n\geq 3]]-3\binom{n-7}{2}[[n\geq 9]]\\
&\qquad\quad+3\binom{n-13}{2}[[n\geq 15]]-\binom{n-19}{2}[[n\geq 21]]\tag{4}
\end{align*}

Comment:

*

*In (1) we apply the coefficient of rule
\begin{align*}
[x^p]x^qA(x)=[x^{p-q}]A(x)
\end{align*}
and we use the formula for the finite geometric series. Since there is no contribution to the coefficient of $x^n$ if $n<3$ we respect this by using $[[n\geq 3]]$.

*In (2) we expand the binomial and we also expand $\frac{1}{(1-x)^3}$ using the binomial series expansion.

*In (3) we use the linearity of the coefficient of operator and we use the binomial identity
\begin{align*}
\binom{-p}{q}=\binom{p+q-1}{q}(-1)^q=\binom{p+q-1}{p-1}(-1)^q
\end{align*}

*In (4) we select the coefficient of $x^{n-k}, k\in\{3,9,15,21\}$.
Note: The usage of the Iverson brackets covers the general case. If we need to calculate a specific case only, the calculation becomes even more straight forward.

Example: $[x^{10}]y(x)$
We obtain
  \begin{align*}
[x^{10}]y(x)&=[x^{10}](x+x^2+x^3+x^4+x^5+x^6)^3\\
&=[x^7]\left(\frac{1-x^6}{1-x}\right)^3\\\
&=[x^7](1-3x^6)\sum_{j=0}^\infty\binom{-3}{j}(-x)^j\\
&=\left([x^7]-3[x]\right)\sum_{j=0}^\infty\binom{j+2}{2}x^j\\
&=\binom{9}{2}-3\binom{3}{2}\\
&=27
\end{align*}


text:
Q: Android Saving a file to internal memory works while to Sd card fails I have an Android app where I need to save a file.
I create the file like this:
FileOutputStream fOut = openFileOutput(fileName,
                    MODE_WORLD_READABLE);
            osw = new OutputStreamWriter(fOut);

I open it like this:
FileInputStream srcFileStream = openFileInput(fileName);

This works fine with internal memory files.
I've added a prefrences to my app, where the user can select to save the file to the sd card instead.
I try this command:
if (Prefs.getCard(this))
        fileName="/sdcard/"+fileName;

Meaning that if the Prefrences is yes, I add "/sdcard/" infront of the file name.
The rest of the code remains the same,
This does not seem to work, as I get an Exception:
File /sd/file1 contains a path seperator

How can I use the same code for both saving to SD card and to internal memory, with just a small modification as i tried above?

A: You certainly didn't forget to add the right permission in the manifest...
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

You can also try to access the external path using:
Environment.getExternalStorageDirectory();

I've already seen different external path name, depending on the device...

A: This should work..
String baseDir = "";
String fileName = "myFile.txt";
FileOutputStream fOut = null;
if (Prefs.getCard(this)) {
    baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
    File file = new File(baseDir + fileName);
    fOut = new FileOutputStream(file)
}  else {
    fOut = openFileOutput(fileName, MODE_WORLD_READABLE);
}
if (fOut != null) {
    osw = new OutputStreamWriter(fOut);
    ...
}

A: Edit was beaten to it by Sevens:
You could try something like this:
File f = Environment.getExternalStorageDirectory();
String fullfilename = f.getAbsoluteFile() + "/Android/data/NameOfApp/fileshere/" ;

File folderToWrite = new File(fullfilename);
folderToWrite.mkdirs();

File fileToWrite = new File(fullfilename,"filename.txt");


text:
Q: Break numpy arrays into subarrays according to their signs Suppose I have a numpy array
a = numpy.array( [-1, -2, 3, 3, -4, -4, 9, 9, 10, -1, -3] ).

I would like to break the array into subarrays according to the rule: the first subarray starts with a[0] and ends before it changes sign. We continue  the process at where the last operation ends.
For example, the array in the example would be broken into subarrays:
a1 = numpy.array( [-1, -2] )
a2 = numpy.array( [3, 3] )
a3 = numpy.array( [-4, -4] )
a4 = numpy.array( [9, 9, 10] )
a5 = numpy.array( [-1, -3] )

I thought about using masks with did not work out a good implementation.

A: Here's one compact way to produce list of those subarrays as output -
In [170]: a
Out[170]: array([-1, -2,  3,  3, -4, -4,  9,  9, 10, -1, -3])

In [171]: np.split(a,np.flatnonzero(np.diff(a>0))+1)
Out[171]:
[array([-1, -2]),
 array([3, 3]),
 array([-4, -4]),
 array([ 9,  9, 10]),
 array([-1, -3])]

Alternatively, a bit more efficiency could be introduced with masking -
In [172]: mask = a>0

In [173]: np.split(a,np.flatnonzero(mask[:-1] != mask[1:])+1)
Out[173]:
[array([-1, -2]),
 array([3, 3]),
 array([-4, -4]),
 array([ 9,  9, 10]),
 array([-1, -3])]

If by different signs, you meant to group 0s separately, use np.sign into the mix -
In [272]: a
Out[272]: array([ 4,  0, -4,  3, -4, -4,  9,  9, 10, -1, -3])

In [273]: np.split(a,np.flatnonzero(np.diff(np.sign(a))!=0)+1)
Out[273]:
[array([4]),
 array([0]),
 array([-4]),
 array([3]),
 array([-4, -4]),
 array([ 9,  9, 10]),
 array([-1, -3])]

Create labelled islands
Create labelled islands based on the groupings -
mask = a>0
label = (np.ediff1d(mask.astype(int),to_begin=mask[0])!=0).cumsum()-mask[0]

Sample run -
# input array starting with negative number
In [243]: a
Out[243]: array([-1, -2,  3,  3, -4, -4,  9,  9, 10, -1, -3])

In [244]: mask = a>0

In [246]: (np.ediff1d(mask.astype(int),to_begin=mask[0])!=0).cumsum()-mask[0]
Out[246]: array([0, 0, 1, 1, 2, 2, 3, 3, 3, 4, 4])

# input array starting with positive number
In [248]: a
Out[248]: array([ 1, -2,  3,  3, -4, -4,  9,  9, 10, -1, -3])

In [249]: mask = a>0

In [251]: (np.ediff1d(mask.astype(int),to_begin=mask[0])!=0).cumsum()-mask[0]
Out[251]: array([0, 1, 2, 2, 3, 3, 4, 4, 4, 5, 5])

A: The following function splits a, returning a list of required sub-numpy.arrays
import numpy as np

def splitBySign(arr):
    arrSign = np.sign(arr)                              # array([-1, -1,  1,  1, -1, -1,  1,  1,  1, -1, -1])
    arrSignChange = arrSign[:-1] - arrSign[1:]          # array([ 0, -2,  0,  2,  0, -2,  0,  0,  2,  0])
    splitIndices = np.nonzero(arrSignChange)[0] + 1     # array([2, 4, 6, 9])
    startIndices = np.insert(splitIndices, 0, 0)        # array([0, 2, 4, 6, 9])
    endIndices = np.append(splitIndices, len(arr))      # array([ 2,  4,  6,  9, 11])
    subArrList = []
    for start, end in zip(startIndices, endIndices):
        subArr = arr[start:end]
        subArrList.append(subArr)

    return subArrList                                   # [array([-1, -2]), array([3, 3]), array([-4, -4]), array([ 9,  9, 10]), array([-1, -3])]

For better understanding, values of its local variables are provided as comments, for argument arr invoked with given a as follows
arr = np.array([-1, -2, 3, 3, -4, -4, 9, 9, 10, -1, -3])
subArrList = splitBySign(a)


text:
Q: Button Overlay on ListView Hides on MouseMove In the details view of ListView control, I need additional functionality of editing the entry pointed to by the cursor so I simply added a button overlay onto the ListView control.
The following code was intended to show the button on the rightmost part of each cell of the details view of  ListView control when the cursor is on the ListView control.
To determine which cell was hovered, HitTest method was used.
The problem is, the button show correctly only when the cursor is on the rectangle area the button is supposed to show up. In other words, when the cursor is on non-rightmost area of any field, redraw occurs in ListView control and erases the button (and the content of the cell). Also, BringToFront method doesn't work.
How to correct this behavior?
class DocumentView {
    Button btn = new Button();
    ListView lv; // designer-generated

    public DocumentView(Document doc)
    {
        btn.AutoSize = true;
        btn.AutoSizeMode = AutoSizeMode.GrowAndShrink;
        btn.AutoEllipsis = false;
        btn.Hide();
        this.Controls.Add(btn);
        InitializeComponent();
    }

    ListViewItem mouseMoveHitTestItem = null;
    ListViewItem.ListViewSubItem mouseMoveHitTestSubItem = null;
    int iCol_MouseMove = -1;
    int iRow_MouseMove = -1;
    private void lv_MouseMove(object sender, MouseEventArgs e)
    {
        var mousePos = lv.PointToClient(Control.MousePosition);
        var hitTest = lv.HitTest(mousePos);
        mouseMoveHitTestItem = hitTest.Item;
        mouseMoveHitTestSubItem = hitTest.SubItem;
        if (mouseMoveHitTestItem != null)
        {
            var iCol = hitTest.Item.SubItems.IndexOf(hitTest.SubItem);
            var iRow = hitTest.Item.Index;
            if (iCol != iCol_MouseMove || iRow != iRow_MouseMove)
            { //Reposition button if the cursor moved to a different cell
                var bounds = hitTest.SubItem.Bounds;
                btn.SetBounds(
                    bounds.Right - btn.Width + lv.Left,
                    bounds.Top + lv.Top,
                    bounds.Width, bounds.Height);

                if (!btn.Visible)
                {
                    btn.Show();
                    btn.BringToFront();
                }
                btn.Text = "" + iRow + ", " + iCol; //test hittest row, col calc.
            }
        }
        btn.BringToFront(); //takes no effect
    }
}

A: Missed status update so invalidatation occurred on every MouseMove:
                btnAddName.SetBounds(
                    bounds.Right - btnAddName.Width + lvVertices.Left,
                    bounds.Top + lvVertices.Top,
                    bounds.Width, bounds.Height);

                //-->
                iColBtnAdd = iCol;
                iRowBtnAdd = iRow;
                //<--

                if (!btnAddName.Visible)
                {

Warnings help. (CS0169)


text:
Q: Request buildings around and area osm android I would like to perform a request to OSM Overpass Turbo API or Overpass API from and Android Application so i can get the buildings around and area using JSON.
Something similar to
http://overpass-turbo.eu/ with the query presented below:
[out:json][timeout:25];
// gather results
(
  // query part for: "building"
  way["building"](37.98350674557998,23.72600823640823,37.98552989685638,23.728837966918945);
  relation["building"](37.98350674557998,23.72600823640823,37.98552989685638,23.728837966918945);
);
// print results
out body;
>;
out skel qt;

The thing is that i need the results in geojson like the result below but i cannot find any query that gives me the below result.
{
  "type": "FeatureCollection",
  "generator": "overpass-turbo",
  "copyright": "The data included in this document is from www.openstreetmap.org. The data is made available under ODbL.",
  "timestamp": "2015-03-23T20:41:02Z",
  "features": [
    {
      "type": "Feature",
      "id": "relation/2604192",
      "properties": {
        "@id": "relation/2604192",
        "building": "yes",
        "type": "multipolygon"
      },
      "geometry": {
        "type": "Polygon",
        "coordinates": [
          [
            [
              23.7319885,
              37.9752441
            ],
            [
              23.7319787,
              37.9751612
            ],
            [
              23.7319494,
              37.9751641
            ],
            [
              23.7319372,
              37.9748376
            ],
            [
              23.7319702,
              37.9748318
            ],
          ]
        ]
      }
    },

I get only results with nodes but not with geometry.
{
  "type": "way",
  "id": 25107859,
  "nodes": [
    2373953582,
    2373953586,
    2373953592,
    2373953599,
    2373953597,
    2373953636,
    2373953633,
    2373953626,
    273319309,
    2373953582
  ],
  "tags": {
    "building": "yes"
  }
},

After some useful comments (thanks scai) i found out that overpass turbo is not queried automatically. Therefore i searched for overpass api and i found out this site with a query for buildings to overpass api exporting to GeoJSON but i does not work (though the xml query in the site works but i need json). Anyone has a query that works so i can follow it?
http://inasafe.org/en/developer-docs/osm_building_downloads.html

http://overpass-api.de/api/interpreter?data=[out:json];(node[%23building%22=%22yes%22](-6.185440796831979,106.82374835014343,-6.178966266481431,106.83127999305725);way[%22building%22=%22yes%22](-6.185440796831979,106.82374835014343,-6.178966266481431,106.83127999305725);relation[%22building%22=%22yes%22](-6.185440796831979,106.82374835014343,-6.178966266481431,106.83127999305725););(._;%3E;);out%20body;


text:
Q: Why are distant lights more flickery in peripheral vision? I have just realized that if you arrange your angle to a flickering distant light source and make it fall into your far-peripheral vision (+70 degree to the side of your FOV), you perceive it to be flickering a lot faster.
Details
When I look at distant flickering street lights, I must pay special attention to tell that they are flickering. But when I change my angle and observe those with side of my field of vision, flicker rate is close to a TV screen with white noise, or a bubbles in heavily boiling water.
What is the reason of my peripheral vision capturing flickering of light better?


text:
Q: Rudder only trajectory Assuming a vehicle with negligible body in fluid (plane, boat, hovercraft) and a deflected single aft control surface (rudder, not affected by propulsion) causing lift and drag in the fluid, what is the vehicle's motion?
Does it turn or drift?
I am trying to validate a simulation (expected turn, but it drifts) but can't think of an easy kitchen table type experiment.
The closest real situation might be an unpowered airplane using rudder for a drift forward slip landing. Flight sim or paper plane?


text:
Q: use boost::is_upper properly How can I know whether a string contains a upper case or not?
for a string token,
for (std::string::iterator tokenIter = token.begin(); tokenIter != token.end(); tokenIter++) {
    return boost::all(*tokenIter, boost::is_upper(locale))

}

but it seems weird. Is there any elegent way to do this?

A: Under C++11
#include <iostream>
#include <algorithm>

#include <boost/algorithm/string/classification.hpp>

using namespace std;

int main()
{
    string str1 = "hello";
    cout << std::boolalpha << std::any_of(str1.begin(), str1.end(), boost::is_upper()) << endl; //false

    string str2 = "Hello";
    cout << std::boolalpha << std::any_of(str2.begin(), str2.end(), boost::is_upper()) << endl; //true

    return 0;
}


text:
Q: Some questions about representations of $SO(6)$ I would like to know the proof/explanation for the following three properties of the representation of $SO(6)$,

*

*What is the importance of symmetric traceless tensors of arbitrary rank w.r.t $SO(6)$ representations?

*Why can the $6$ dimensional vector representation of $SO(6)$ be thought of as the rank-$2$ anti-symmetric representation of $SU(4)$?

*Why can the tensor product two of $6$ dimensional vector representations of $SO(6)$ be thought of as a sum of a symmetric traceless, anti-symmetric and a one-dimensional representation?
I would also like to know if there are some general properties of $SO(n)$ representations from which the above follow.  Then may be someone can may be kindly also write down the explanation for $SO(n)$ in general!

A: I'm not sure how to answer question 1-- it is a little vague.  The second question is unique to $SO(6)$ and is answered by understanding how $SU(4)$ is the double cover of $SO(6)$.  This double cover is constructed as follows:  first notice that $\Lambda^2 \mathbb C^4$ is six dimensional and has a Hermitian inner product induced by the one on $\mathbb C^4$.  This can be defined by saying if $\{e_1,\ldots,e_4\}$ is an orthonormal basis for $\mathbb C^4$ then $\{e_i \wedge e_j\}$ is an orthonormal basis for $\Lambda^2 \mathbb C^4$ or, more invariantly,
$$
\langle v_1 \wedge v_2, w_1 \wedge w_2 \rangle = \det\langle v_i, w_j\rangle
$$
where $\langle v, w\rangle$ is the Hermitian inner product on $\mathbb C^4$.  Then it is easy to see that the action of $SU(4)$ on $\Lambda^2 \mathbb C^4$ preserves this inner product, giving a homomorphism $SU(4) \to U(\Lambda^2 \mathbb C^4) = U(6)$.  But there is also a symmetric inner product on $\Lambda^2 \mathbb C^4$
$$
\Lambda^2 \mathbb C^4 \otimes \Lambda^2 \mathbb C^4 \to \Lambda^4 \mathbb C^4 \simeq \mathbb C
$$
which is also preserved by the action of $SU(4)$ since elements in $SU(4)$ have determinant 1.  Thus the image of the above homomorphism lies in $U(6) \cap SO(6, \mathbb C) = SO(6)$.  One checks that the kernel of this map is $\{\pm 1\}$ and therefore, by dimensionality reasons, must be a surjection.  Thus this is the double cover $SU(4) \to SO(6)$ but now it is transparent that the $\Lambda^2 \mathbb C^4$ rep of $SU(4)$ corresponds to the vector representation of $SO(6)$.
Your third question holds for all of $SO(n)$ (indeed for any self-dual representation).  Since there is an invariant symmetric inner product on $V = \mathbb C^n$ preserved by $SO(n)$, it follows that the fundamental representation is self-dual.  Thus $V\otimes V \simeq V^* \otimes V \simeq End(V)$.  Now for any rep $V$ of any group, $V \otimes V$ always reduces into a direct sum of symmetric plus antisymmetric (this is immediate from the definition of the tensor product representation).  Similarly, for any rep $V$ of any group, $End(V)$ has a one-dimensional subrepresentation spanned by the identity transformation.  Now under the correspondence of $End(V) \simeq V\otimes V$, the symmetric tensors will contain the identity endomorphism but a complementary subspace is given by traceless endomorphisms.


text:
Q: $r$-representation of Operator I am watching this video
https://www.youtube.com/watch?v=sYgX5pdncG8
at 14:30, it has
$\langle r|H|r'\rangle = H(r) \delta(r-r') $
Can you help me to understand why it is so? I thought it should be $H(r,r')$. I believe I am missing some fundamental knowledge in quantum mechanics.

A: In general you are correct, the notation
$$H(r, r') = \langle r | \hat H |r' \rangle$$ is good. This indicates it is the matrix element of the Hamiltonian in the position representation and as such depends on both coordinates.
In the case in question (and many physical cases) the Hamiltonian is diagonal in position space (potentials are local) and this is indicated by the delta function: $H(r, r') = H(r) \delta(r - r') = H(r') \delta(r - r') $. The first factor contains all the "interesting" physics about the form of the Hamiltonian and the delta function tells us that only the diagonal elements are non zero.


text:
Q: SceneKit Project User Interaction I have been working on a game in SceneKit which involves a plane that the user can control using the arrow keys. The plane can fly, but the arrow keys have no effect on the plane. When I run a test to see if the arrow key function is working I can see that the arrow keys are effectively changing the speed of the plane, but the plane does not increase or decrease speed. Here is the code:
import SceneKit
import QuartzCore
class GameViewController: NSViewController {
var height = 0
var speed = 0 //I should be able to change this value by pressing the up arrow key during the simulation
override func keyDown(with theEvent: NSEvent) {
    if(theEvent.keyCode == 123){//left
    }
    if(theEvent.keyCode == 124){//right
    }
    if(theEvent.keyCode == 125){//down
    }
    if(theEvent.keyCode == 126){//up
        speed+=1
        print(speed)
    }
}
override func viewDidLoad(){
    super.viewDidLoad()
    let scene = SCNScene(named: "art.scnassets/Plane.scn")!
    let cameraNode = scene.rootNode.childNode(withName: "camera", recursively: true)!
    let plane = scene.rootNode.childNode(withName: "plane", recursively: true)!
    plane.runAction(SCNAction.repeatForever(SCNAction.moveBy(x: 0, y: CGFloat(height), z: CGFloat(speed), duration: 1)))
    cameraNode.runAction(SCNAction.repeatForever(SCNAction.moveBy(x:0, y:CGFloat(height), z: CGFloat(speed), duration:1)))

    let scnView = self.view as! SCNView
    }

}

A: Once you have a created a SCNAction object with parameters that depend on the speed variable, any change to speed won't update the action.
This is because speed is a value type (Int) and there's no connection between the SCNAction instance and your view controller's speed instance variable. This is not an issue specific to SceneKit, any API that takes an Int as a parameter would behave the same way.


text:
Q: RAILS Auto refresh partial I have a controller events with action show :
  def show
    @event = Event.get(params[:id])

    if !connected? || !@event
      return redirect_to request.referrer || root_path
    end

    @requests = @event.get_requests
  end

In view show.html.erb i have

...

    <%= render partial: 'requests' %>

...

The javascript function call controller method events/reload_requests :
def reload_requests
  @requests = @event.get_requests
  render partial: 'events/requests'
end

And content of partial _requests.html.erb :
<%= Time.now %>

<%= t '.requests' %>

<% @requests.each do |r| %>

 ...
<% end %>

Problem : The javascript function load all the content of my show.html.erb page in div #requests, but in the copy of show.html.erb in the div, it refresh div #request correctly :
enter image description here
You can see, in show#requests i have the content of show.
Than you

A: After re-reading your question, I think I understood your problem.
When you call the #load method, the HTML returned is actually your whole show.html.erb template.. which gets inserted into your $('#requests') element. Is that correct?
In the jQuery docs, you can find the following at: http://api.jquery.com/load/

Loading Page Fragments
The .load() method, unlike $.get(), allows us to specify a portion of
  the remote document to be inserted. (...)
$( "#result" ).load( "ajax/test.html #fragment" );

Maybe if you modify your script tag as follow:

you can insert only the fragment of the HTML you are interested in.
Please let me know if that was not your question.
Also, if your request to 'event/reload_requests' is returning your show.html.erb template, you may be mistakenly routing the event/reload_requests endpoint to your #show action.
Edit#1
The cleanest way to fix the nested div problem seems to be to add a container div and load from there:
$('#requestsContainer').load('/events/reload_requests #requests');

html:

      <%= render partial: 'requests' %>


text:
Q: jQuery sum table toFixed not working properly I have dynamic table with data that can be formatted differently. For example: 500  500,57 1500,00 1.500,00.
Currently I'm doing str_replace to remove first dot on thousandth and then replace comma with dot.
echo str_replace(array(".", ",",), array("", "."), $row['rad_iznos']);

That works fine and I get only thousandth with dot separator on decimal numbers. However when I use
toFixed(2) option on sum the value of decimal is left behind and it should work according to this: https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_tofixed .
As you can see only decimals after 2 digits are rounded up.
var totals=[0,0,0];
        $(document).ready(function(){

            var $dataRows=$("#sum_table tr:not('.totalColumn, .titlerow')");

            $dataRows.each(function() {
                $(this).find('.rowDataSd').each(function(i){
                    totals[i]+=parseInt( $(this).html());
                });
            });
            $("#sum_table td.totalCol").each(function(i){
                $(this).html(''+totals[i].toFixed(2)+' kn');
            });

        });

You can see example here:
.57 is missing and I just don't understand logic behind it. Please advise. thousandths value is correct.

A: The issue is not with .toFixed() but with:
totals[i] += parseInt($(this).html());

which will add each row's value as an integer - thus losing the decimal places as it goes, so when it gets to .toFixed() it's already lost the decimal places.
The solution is to use parseFloat() instead, to keep the decimal places:
totals[i] += parseFloat($(this).html());