text:
Q: NullPointerException when moving ImageView in Javafx, scenebuilder I'm aware that similar questions have been asked on Stackoverflow before, but none of the answers I've found seem to fix my problem. Also I'd like to add that I'm entirely new to javafx and started coding java literally a week ago altogether, so I apologize for any silly errors in my code!
When trying to move an ImageView in my javafx, moving a player and crates around in the game "sokoban", I get a nullpointerexception stating that my ImageView, marked with an fx:id in scene builder and then called on in my controller class, is a null object. Here's my code:
Application:
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class App extends Application{

    @Override
    public void start(final Stage primaryStage) throws Exception {
        primaryStage.setTitle("Sokoban");
        primaryStage.setScene(new Scene(FXMLLoader.load(App.class.getResource("StartScreen.fxml"))));
        primaryStage.show();

    }

    public static void main(final String[] args) {
        App.launch(args);
    }
}

Controller:
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.transform.Translate;
import javafx.stage.Stage;

public class SokobanController {

    GameState currentGame;

    int stepSize;

    @FXML Button Easy;
    @FXML Button Medium;
    @FXML Button Hard;
    @FXML AnchorPane easyGameScene;
    @FXML AnchorPane mediumGameScene;
    @FXML AnchorPane hardGameScene;
    @FXML ImageView playerEasy;
    @FXML ImageView crateEasy0;
    @FXML ImageView crateEasy1;
    @FXML ImageView crateEasy2;
    @FXML ImageView crateEasy3;

    List<ImageView> crateImagesEasy =

Arrays.asList(crateEasy0,crateEasy1,crateEasy2,crateEasy3);

    @FXML void handleDifficultySelection(ActionEvent event) throws IOException {
        String difficulty = ((Button) event.getSource()).getId();
        System.out.println(difficulty);
        if (difficulty.equals("Easy")) {
            stepSize = 75;
        }
        else if (difficulty.equals("Medium")) {

        }
        else if (difficulty.equals("Hard")) {

        }
        currentGame = new GameState(difficulty);

//      playerEasy = new ImageView(new Image("@player.png"));

        Scene gameScene = new Scene(FXMLLoader.load(getClass().getResource("GameScreen.fxml")));
        gameScene.setOnKeyPressed(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent event) {
                handleOnKeyPressed(event);
            }
        });
        Stage window = (Stage)((Node)event.getSource()).getScene().getWindow();

        window.setScene(gameScene);
        window.show();
        }

    @FXML void handleOnkey(ActionEvent event) {
        System.out.println("hallo");
    }

    void handleOnKeyPressed(KeyEvent event) {
        System.out.println("hallo");
        if (event.getCode().equals(KeyCode.LEFT)) {
//          Translate translate = new Translate();
//          translate.setX(-stepSize);
            if (!currentGame.checkCollideWall(-1, 0)) {
                int i = 0;
                for (Crate crate : currentGame.crates) {
                    if (currentGame.checkCollideCrate(crate, -1, 0)
                            && !currentGame.checkCollideWall(-2, 0)) {
//                      crateImagesEasy.get(currentGame.crates.indexOf(crate))
//                          .getTransforms().addAll(translate);

crateImagesEasy.get(currentGame.crates.indexOf(crate)).relocate(-stepSize,0);
//                      playerEasy.getTransforms().addAll(translate);
                        i = 1;
                        playerEasy.relocate(-stepSize, 0);
                    }
                }
                if (i == 0) {
//                  playerEasy.getTransforms().addAll(translate);
                    playerEasy.relocate(-stepSize, 0);
                }
            }
        }
        else if (event.getCode().equals(KeyCode.RIGHT)) {
            Translate translate = new Translate();
            translate.setX(stepSize);
            if (!currentGame.checkCollideWall(1, 0)) {
                int i = 0;
                for (Crate crate : currentGame.crates) {
                    if (currentGame.checkCollideCrate(crate, 1, 0)
                            && !currentGame.checkCollideWall(2, 0)) {
                        crateImagesEasy.get(currentGame.crates.indexOf(crate))
                            .getTransforms().addAll(translate);
                        playerEasy.getTransforms().addAll(translate);
                        i = 1;
                    }
                }
                if (i == 0) {
                    playerEasy.getTransforms().addAll(translate);
                }
            }
        }
        else if (event.getCode().equals(KeyCode.UP)) {
            Translate translate = new Translate();
            translate.setY(-stepSize);
            if (!currentGame.checkCollideWall(0, -1)) {
                int i = 0;
                for (Crate crate : currentGame.crates) {
                    if (currentGame.checkCollideCrate(crate, 0, -1)
                            && !currentGame.checkCollideWall(0, -2)) {
                        crateImagesEasy.get(currentGame.crates.indexOf(crate))
                            .getTransforms().addAll(translate);
                        playerEasy.getTransforms().addAll(translate);
                        i = 1;
                    }
                }
                if (i == 0) {
                    playerEasy.getTransforms().addAll(translate);
                }
            }
        }
        else if (event.getCode().equals(KeyCode.DOWN)) {
            Translate translate = new Translate();
            translate.setY(stepSize);
            if (!currentGame.checkCollideWall(0, 1)) {
                int i = 0;
                for (Crate crate : currentGame.crates) {
                    if (currentGame.checkCollideCrate(crate, 0, 1)
                            && !currentGame.checkCollideWall(0, 2)) {
                        crateImagesEasy.get(currentGame.crates.indexOf(crate))
                            .getTransforms().addAll(translate);
                        playerEasy.getTransforms().addAll(translate);
                        i = 1;
                    }
                }
                if (i == 0) {
                    playerEasy.getTransforms().addAll(translate);
                }
            }
        }

    }
}

FXML-file:
<?import javafx.scene.image.Image?>
<?import javafx.scene.image.ImageView?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.StackPane?>
<?import javafx.scene.layout.VBox?>
<?import javafx.scene.shape.Circle?>
<?import javafx.scene.shape.Rectangle?>
<?import javafx.scene.text.Font?>
<?import javafx.scene.text.Text?>

<AnchorPane prefHeight="630.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="app.SokobanController">
   <children>
      <VBox prefHeight="630.0" prefWidth="600.0">
         <children>
            <StackPane prefHeight="600.0" prefWidth="600.0">
               <children>
                  <AnchorPane fx:id="easyGameScene" prefHeight="600.0" prefWidth="600.0" style="-fx-background-color: f3e1bb;">
                     <children>
                        <ImageView fitHeight="75.0" fitWidth="75.0" pickOnBounds="true" translateX="150.0">
                           <image>
                              <Image url="@wall.PNG" />
                           </image>
                        </ImageView>
                        <ImageView fitHeight="75.0" fitWidth="75.0" layoutX="150.0" layoutY="150.0" pickOnBounds="true">
                           <image>
                              <Image url="@wall.PNG" />
                           </image>
                        </ImageView>
                        <ImageView fitHeight="75.0" fitWidth="75.0" layoutX="150.0" layoutY="225.0" pickOnBounds="true">
                           <image>
                              <Image url="@wall.PNG" />
                           </image>
                        </ImageView>
                        <ImageView fitHeight="75.0" fitWidth="75.0" layoutY="225.0" pickOnBounds="true">
                           <image>
                              <Image url="@wall.PNG" />
                           </image>
                        </ImageView>
                        <ImageView fitHeight="75.0" fitWidth="75.0" layoutY="300.0" pickOnBounds="true">
                           <image>
                              <Image url="@wall.PNG" />
                           </image>
                        </ImageView>
                        <ImageView fitHeight="75.0" fitWidth="75.0" layoutY="375.0" pickOnBounds="true">
                           <image>
                              <Image url="@wall.PNG" />
                           </image>
                        </ImageView>
                        <ImageView fitHeight="75.0" fitWidth="75.0" layoutX="75.0" layoutY="225.0" pickOnBounds="true">
                           <image>
                              <Image url="@wall.PNG" />
                           </image>
                        </ImageView>
                        <ImageView fitHeight="75.0" fitWidth="75.0" layoutX="150.0" layoutY="75.0" pickOnBounds="true">
                           <image>
                              <Image url="@wall.PNG" />
                           </image>
                        </ImageView>
                        <ImageView fitHeight="75.0" fitWidth="75.0" layoutX="225.0" pickOnBounds="true">
                           <image>
                              <Image url="@wall.PNG" />
                           </image>
                        </ImageView>
                        <ImageView fitHeight="75.0" fitWidth="75.0" layoutX="300.0" pickOnBounds="true">
                           <image>
                              <Image url="@wall.PNG" />
                           </image>
                        </ImageView>
                        <ImageView fitHeight="75.0" fitWidth="75.0" layoutX="300.0" layoutY="75.0" pickOnBounds="true">
                           <image>
                              <Image url="@wall.PNG" />
                           </image>
                        </ImageView>
                        <ImageView fitHeight="75.0" fitWidth="75.0" layoutX="300.0" layoutY="150.0" pickOnBounds="true">
                           <image>
                              <Image url="@wall.PNG" />
                           </image>
                        </ImageView>
                        <ImageView fitHeight="75.0" fitWidth="75.0" layoutX="375.0" layoutY="150.0" pickOnBounds="true">
                           <image>
                              <Image url="@wall.PNG" />
                           </image>
                        </ImageView>
                        <ImageView fitHeight="75.0" fitWidth="75.0" layoutX="450.0" layoutY="150.0" pickOnBounds="true">
                           <image>
                              <Image url="@wall.PNG" />
                           </image>
                        </ImageView>
                        <ImageView fitHeight="75.0" fitWidth="75.0" layoutX="525.0" layoutY="150.0" pickOnBounds="true">
                           <image>
                              <Image url="@wall.PNG" />
                           </image>
                        </ImageView>
                        <ImageView fitHeight="75.0" fitWidth="75.0" layoutX="525.0" layoutY="225.0" pickOnBounds="true">
                           <image>
                              <Image url="@wall.PNG" />
                           </image>
                        </ImageView>
                        <ImageView fitHeight="75.0" fitWidth="75.0" layoutX="525.0" layoutY="300.0" pickOnBounds="true">
                           <image>
                              <Image url="@wall.PNG" />
                           </image>
                        </ImageView>
                        <ImageView fitHeight="75.0" fitWidth="75.0" layoutX="450.0" layoutY="300.0" pickOnBounds="true">
                           <image>
                              <Image url="@wall.PNG" />
                           </image>
                        </ImageView>
                        <ImageView fitHeight="75.0" fitWidth="75.0" layoutX="375.0" layoutY="300.0" pickOnBounds="true">
                           <image>
                              <Image url="@wall.PNG" />
                           </image>
                        </ImageView>
                        <ImageView fitHeight="75.0" fitWidth="75.0" layoutX="375.0" layoutY="375.0" pickOnBounds="true">
                           <image>
                              <Image url="@wall.PNG" />
                           </image>
                        </ImageView>
                        <ImageView fitHeight="75.0" fitWidth="75.0" layoutX="375.0" layoutY="450.0" pickOnBounds="true">
                           <image>
                              <Image url="@wall.PNG" />
                           </image>
                        </ImageView>
                        <ImageView fitHeight="75.0" fitWidth="75.0" layoutX="375.0" layoutY="525.0" pickOnBounds="true">
                           <image>
                              <Image url="@wall.PNG" />
                           </image>
                        </ImageView>
                        <ImageView fitHeight="75.0" fitWidth="75.0" layoutX="300.0" layoutY="525.0" pickOnBounds="true">
                           <image>
                              <Image url="@wall.PNG" />
                           </image>
                        </ImageView>
                        <ImageView fitHeight="75.0" fitWidth="75.0" layoutX="225.0" layoutY="525.0" pickOnBounds="true">
                           <image>
                              <Image url="@wall.PNG" />
                           </image>
                        </ImageView>
                        <ImageView fitHeight="75.0" fitWidth="75.0" layoutX="225.0" layoutY="450.0" pickOnBounds="true">
                           <image>
                              <Image url="@wall.PNG" />
                           </image>
                        </ImageView>
                        <ImageView fitHeight="75.0" fitWidth="75.0" layoutX="225.0" layoutY="375.0" pickOnBounds="true">
                           <image>
                              <Image url="@wall.PNG" />
                           </image>
                        </ImageView>
                        <ImageView fitHeight="75.0" fitWidth="75.0" layoutX="150.0" layoutY="375.0" pickOnBounds="true">
                           <image>
                              <Image url="@wall.PNG" />
                           </image>
                        </ImageView>
                        <ImageView fitHeight="75.0" fitWidth="75.0" layoutX="75.0" layoutY="375.0" pickOnBounds="true">
                           <image>
                              <Image url="@wall.PNG" />
                           </image>
                        </ImageView>
                        <ImageView fx:id="crateEasy0" fitHeight="75.0" fitWidth="75.0" layoutX="225.0" layoutY="225.0" pickOnBounds="true">
                           <image>
                              <Image url="@crate.png" />
                           </image>
                        </ImageView>
                        <ImageView fx:id="crateEasy2" fitHeight="75.0" fitWidth="75.0" layoutX="225.0" layoutY="300.0" pickOnBounds="true">
                           <image>
                              <Image url="@crate.png" />
                           </image>
                        </ImageView>
                        <ImageView fx:id="crateEasy3" fitHeight="75.0" fitWidth="75.0" layoutX="300.0" layoutY="375.0" pickOnBounds="true">
                           <image>
                              <Image url="@crate.png" />
                           </image>
                        </ImageView>
                        <ImageView fx:id="crateEasy1" fitHeight="75.0" fitWidth="75.0" layoutX="375.0" layoutY="225.0" pickOnBounds="true">
                           <image>
                              <Image url="@crate.png" />
                           </image>
                        </ImageView>
                        <ImageView fx:id="playerEasy" fitHeight="75.0" fitWidth="75.0" layoutX="300.0" layoutY="300.0" pickOnBounds="true">
                           <image>
                              <Image url="@player.png" />
                           </image>
                        </ImageView>
                        <Circle fill="#eb6020" layoutX="113.0" layoutY="338.0" radius="15.0" stroke="BLACK" strokeType="INSIDE" />
                        <Circle fill="#eb6020" layoutX="263.0" layoutY="113.0" radius="15.0" stroke="BLACK" strokeType="INSIDE" />
                        <Rectangle arcHeight="5.0" arcWidth="5.0" fill="#f5f5f500" height="75.0" layoutX="75.0" layoutY="300.0" stroke="#eb6020" strokeType="INSIDE" strokeWidth="5.0" width="75.0" />
                        <Circle fill="#eb6020" layoutX="488.0" layoutY="263.0" radius="15.0" stroke="BLACK" strokeType="INSIDE" />
                        <Circle fill="#eb6020" layoutX="338.0" layoutY="488.0" radius="15.0" stroke="BLACK" strokeType="INSIDE" />
                        <Rectangle arcHeight="5.0" arcWidth="5.0" fill="#f5f5f500" height="75.0" layoutX="225.0" layoutY="75.0" stroke="#eb6020" strokeType="INSIDE" strokeWidth="5.0" width="75.0" />
                        <Rectangle arcHeight="5.0" arcWidth="5.0" fill="#f5f5f500" height="75.0" layoutX="450.0" layoutY="225.0" stroke="#eb6020" strokeType="INSIDE" strokeWidth="5.0" width="75.0" />
                        <Rectangle arcHeight="5.0" arcWidth="5.0" fill="#f5f5f500" height="75.0" layoutX="300.0" layoutY="451.0" stroke="#eb6020" strokeType="INSIDE" strokeWidth="5.0" width="75.0" />
                     </children>
                  </AnchorPane>
               </children>
            </StackPane>
            <HBox alignment="CENTER" prefHeight="30.0" prefWidth="600.0" style="-fx-background-color: #000000;">
               <children>
                  <Text fill="#d79420" strokeType="OUTSIDE" strokeWidth="0.0" text="Controls: move with arrow-keys and press "R" to restart the game">

                  </Text>
               </children>
            </HBox>
         </children>
      </VBox>
   </children>
</AnchorPane>

My application starts with an initial difficulty selection scene and then switches over to the actual game scene, where I've encountered the problem.
This is the error I get:
Exception in thread "JavaFX Application Thread" java.lang.NullPointerException
    at ovinger/app.SokobanController.handleOnKeyPressed(SokobanController.java:97)
    at ovinger/app.SokobanController$1.handle(SokobanController.java:64)
    at ovinger/app.SokobanController$1.handle(SokobanController.java:1)
    at javafx.base/com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
    at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at javafx.base/com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at javafx.base/com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at javafx.base/com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
    at javafx.base/javafx.event.Event.fireEvent(Event.java:198)
    at javafx.graphics/javafx.scene.Scene$KeyHandler.process(Scene.java:4058)
    at javafx.graphics/javafx.scene.Scene$KeyHandler.access$1500(Scene.java:4004)
    at javafx.graphics/javafx.scene.Scene.processKeyEvent(Scene.java:2121)
    at javafx.graphics/javafx.scene.Scene$ScenePeerListener.keyEvent(Scene.java:2595)
    at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler$KeyEventNotification.run(GlassViewEventHandler.java:217)
    at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler$KeyEventNotification.run(GlassViewEventHandler.java:149)
    at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
    at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleKeyEvent$1(GlassViewEventHandler.java:248)
    at javafx.graphics/com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:390)
    at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler.handleKeyEvent(GlassViewEventHandler.java:247)
    at javafx.graphics/com.sun.glass.ui.View.handleKeyEvent(View.java:547)
    at javafx.graphics/com.sun.glass.ui.View.notifyKey(View.java:971)
    at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:174)
    at java.base/java.lang.Thread.run(Thread.java:830)

(Line 97 is the first point in which I try to call a method on the ImageView object playerEasy)


text:
Q: Sum of a combination i cant find an expression for:
$\sum_{k=0}^{\lfloor
\frac{p}{2}\rfloor}$ ${p}\choose{k}$
The hint given by the exercise is to do it by seperating the cases where p is odd and even.
What I did so far:
When $p$ is even, $\lfloor p/2 \rfloor = p/2$, so all we need is find an expression
$\sum_{k=0}^{ \frac{p}{2}}$ ${p}\choose{k}$, which I was not able to do.
When $p$ is odd, there is $q$ so that $p=2q+1$ and $p/2= q +1/2$ which means $\lfloor p/2 \rfloor = q$, and I really dont know what to do with this.
The previous question was to show that functions that are of the form $ax+b$ are both convex and concave.
I thought that I should try to put some values in to look for a pattern and here is what I have :
for $p$ even :
$p=2, \sum_{k=0}^{1}$ ${2}\choose{k}$$=1+2=3$
$p=4, \sum_{k=0}^{2}$ ${4}\choose{k}$$=1+6+4=11$
$p=6, \sum_{k=0}^{3}$ ${6}\choose{k}$$=1+6+15+20=42$
no apparent pattern.
when p is odd,
$p=1, \sum_{k=0}^{0}$ ${1}\choose{k}$$=1$
$p=3, \sum_{k=0}^{1}$ ${3}\choose{k}$$=1+3=4$
$p=5, \sum_{k=0}^{2}$ ${5}\choose{k}$$=1+5+10=16$
$p=7, \sum_{k=0}^{4}$ ${7}\choose{k}$$=1+7+21+35+35=99$
No apparent pattern here
Thank you for your help

A: We have ${p \choose k} = {p \choose p-k}$, so
$$ \sum_{k=0}^{\lfloor p/2 \rfloor} {p \choose k} = \sum_{k = p - \lfloor p/2 \rfloor}^p {p \choose k}$$
Thus if $p$ is odd, $\{0, \ldots, \lfloor p/2 \rfloor \}$ and $\{p - \lfloor p/2 \rfloor, \ldots, p\}$ are disjoint and their union is $\{0, \ldots, p\}$, so using the binomial theorem your sum is $2^{p-1}$.
If $p$ is even, $p/2$ is in both sets, so your sum is $2^{p-1} + {p \choose p/2}/2$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: While-loop Python Fibonacci I am new to python and I have really poor expiriences with other codes.
For the most of you a stupid question but somewhere I should start.
 def fib(n):
 a, b = 0, 1
 while a < n:
     print(a, end=' ')
     a, b = b, a+b
 print()

I don't understand why one should enter a, b = b, a+b
I see and understand the result and I can conclude the basic algorithm but I don't get the real understanding of what is happening with this line and why we need it.
Many thanks

A: This line is executed in the following order:

*

*New tuple is created with first element equal to b and second to a + b

*The tuple is unpacked and first element is stored in a and the second one in b
The tricky part is that the right part is executed first and you do not need to use temporary variables.

A: The reason you need it is because, if you update a with a new value, you won't be able to calculate the new value of b. You could always use temporary variables to keep the old value while you calculate the new values, but this is a very neat way of avoiding that.
It's called sequence unpacking.
In your statement:
a, b = b, a + b

the right side b, a + b creates a tuple:
>>> 8, 5 + 8
(8, 13)

You then assign this to the left side, which is also a tuple a, b.
>>> a, b = 8, 13
>>> a
8
>>> b
13

See the last paragraph the documentation on Tuples and Sequences:

The statement t = 12345, 54321, 'hello!' is an example of tuple packing: the values 12345, 54321 and 'hello!' are packed together in a tuple. The reverse operation is also possible:
>>> x, y, z = t
This is called, appropriately enough, sequence unpacking and works for any sequence on the right-hand side. Sequence unpacking requires the list of variables on the left to have the same number of elements as the length of the sequence. Note that multiple assignment is really just a combination of tuple packing and sequence unpacking.


text:
Q: (Recursive) SQL query instead of loops I'm looking for a query to get the following output:
Id Number
-- ------
 1 241100
 2 241110
 2 241111
 2 241112
 2 241113
 2 241114
 2 241115

Table strucutre:
Id Number From To
-- ------ ---- ----
 1 241100 NULL NULL
 2 241110  111  115

Rows without a from/to range has to return the number. The other ones have to return the number followed by SUBSTRING(Number, 1, 3) + <from/to range>
One possible solution would be using while-loops. But thats not the way I'd prefer. And it's quite slow. And there's no way to change the data structure. We query data from a third party supplier.

On application site I've a (very small) list of numbers such as '241113', '241000', ... and need to know to which id this number is assigned to.
The query I will use to get a result is:
SELECT Id, Number FROM MyView WHERE Number IN ('241113', '241000')

A: You can create an auxiliary numbers table
CREATE TABLE Numbers
(
N int primary key
)

  WITH E00(N) AS (SELECT 1 UNION ALL SELECT 1),
        E02(N) AS (SELECT 1 FROM E00 a, E00 b),
        E04(N) AS (SELECT 1 FROM E02 a, E02 b),
        E08(N) AS (SELECT 1 FROM E04 a, E04 b),
        E16(N) AS (SELECT 1 FROM E08 a, E08 b),
        E32(N) AS (SELECT 1 FROM E16 a, E16 b),
   cteTally(N) AS (SELECT ROW_NUMBER() OVER (ORDER BY N) FROM E32)

   INSERT INTO Numbers
   SELECT N FROM cteTally
  WHERE N <= 1000000;

then to generate your desired results
;WITH T (Id, Number, [From], [To]) AS
(
 SELECT 1, 241100, NULL, NULL UNION ALL
 SELECT 2, 241110,  111,  115
)

SELECT Id, Number + N-1  AS Number
FROM T
JOIN Numbers ON N <= 1 + ISNULL(1 + [To] - [From],0)

A:
The query I will use to get a result is:
SELECT Id, Number FROM MyView WHERE Number IN ('241113', '241000')

This is how you can write that query instead. There is no need to generate the numbers.
declare @T table
(
  Id int,
  Number int,
  [From] int,
  [To] int
)

insert into @T values
(1, 241100, NULL, NULL),
(2, 241110,  111,  115)

select T.Id, V.Number
from @T as T
  inner join (values (241113),
                     (241100)) as V(Number)
    on V.Number between T.Number and T.Number + isnull(T.[To], 0)

A version where you put the numbers you look for in a table variable instead.
declare @V table(Number int)
insert into @V values(241100)
insert into @V values(241113)

select T.Id, V.Number
from @T as T
  inner join @V as V
    on V.Number between T.Number and T.Number + isnull(T.[To], 0)

I have not used From anywhere because it is unclear to me what values is possible in that column other then null and number+1.
And a version where you generate the numbers before filtering them out. The result is the same and I believe performance is not as good.
;with C as
(
  select T.Id,
         T.Number
  from @T as T
  union all
  select T.Id,
         C.Number + 1
  from @T as T
    inner join C
      on C.Id = T.Id
  where stuff(C.Number, 1, 3, '') < T.[To]
)
select Id, Number
from C
where Number in ('241113', '241100')

A: I know that you're using tsql, but out of curiosity I wanted to see how I could hack together a solution in pgsql:
create schema arrays;
set search_path = 'arrays';

create table ranges
(
    "Id"     bigint primary key,
    "Number" int not null,
    "From"   int,
    "To"     int
);

insert into ranges("Id", "Number", "From", "To") values
    (1,  241100, null, null),
    (2,  241110,  111,  115),
    (3, 2411200, 1281, 1293);

create view ranges_gen as
select
    "Id",
    (row_number() over(partition by "Id") - 1 + "Bottom") as "Number"
from
(
    select
        "Id",
        coalesce(round("Number", -length("From"::text)) + "From", "Number") as "Bottom",
        unnest(array_fill(0, array[coalesce("To" - "From" + 1, 1)]))
    from ranges
) as ranges_duped;

select * from ranges_gen;


text:
Q: Not understanding the code written in jenkins file i have found the following code in a jenkins file in my project. i am new to aws and docker and not understanding the logic behind this code, guys help me out on what is happening here
            sh "docker run --rm -i -e AWS_ACCESS_KEY_ID -e AWS_SECRET_ACCESS_KEY -e AWS_REGION " +
               '--name "${CONTAINER_ID}" "${IMAGE_TAG}" ' +
               "node -r esbuild-runner/register ./scripts/restartExecution.ts " +

               (params.DryRun? "--dry-run " : "") +
               "--started-after ${StartedAfter} " +
               (params.StartedBefore? "--started-before ${params.StartedBefore} " : "") +
               "--state-machine-arn ${params.StateMachineARN} " +
               "--status ${params.Status} "

A: It is pretty straightforward
docker run --rm -i -e AWS_ACCESS_KEY_ID -e AWS_SECRET_ACCESS_KEY -e AWS_REGION '--name "${CONTAINER_ID}" "${IMAGE_TAG}" '

The docker run command first creates a container layer over the specified image, and then starts it using the specified command.(from docs)
Pass the three
AWS_ACCESS_KEY_ID
AWS_SECRET_ACCESS_KEY
AWS_REGION

as environmental variables.
Sometimes it is useful to show the commands that a shell script will execute,that is why dry-run was added.
More about options in official docs
-rm remove container after it exits
-i interactive mode


text:
Q: Load different pages within one html-page? I'm building an admin page using Bootstrap. In the admin page I have a side-menu and a content-block, and I want to both change the current menu-item to the class "active" when clicked, and show different content depending on the menu-item. At the moment I have different html pages for each menu-item. I find this pretty inconvenient though, since if I want to change something within the side-menu, or other things that all pages have in common, I have to make the same changes to every html-script. Therefore, I'm thinking of having one parent html-page that shows different content depending on what menu-item is clicked. Pretty easy stuff, although there are very many ways to do this e.g. using an iframe, using JS either showing and hiding different divs, or to load content with links, among many others.
What are the downsides and upsides of the different approaches, and which one is most commonly used?
Here's some sample code:

            Overview

            Theme

    Content

A: This question doesn't have a lot to do with bootstrap.
A lot of frameworks allow for template pages so that you don't need to repeat the code that is common to each page. I'd highly recommend using some sort of template or a framework that will allow it.
I'd definitely avoid iframes. Using Javascript frameworks is a good solution. I'd check out frameworks like meteor js or angular js that will allow you to create single page applications and easily change the main content of a page without a page reload.


text:
Q: Plotly: How to re-position ticktext close to the zero-line? Plotly seems to place the x and y ticks on the periphery of a graph by default however I have a graph which its y zero-line is in the middle. I'd like for the tick to be right beside the y axis instead but I fail to find a command to make that happen. Is it at all possible?

A: To my knowledge there is no direct way to do this at the moment. But if you use the correct combination of xaxis zeroline and annotations for the y-values, you can get this:

The code snippet below takes the max and min for the y-values, builds a list of that interval with a defined number of steps, and inserts annotations for those steps. It's not very elegant, it fails a bit when you try to zoom, but it works. At least now you don't have to try a similar approach yourself.
Complete code:
import plotly.graph_objects as go
import numpy as np

x = np.arange(-4,5)
y=x**3

yticks=list(range(y.min(), y.max(), 14))
#yticks.append(y.max())9

fig = go.Figure(data=go.Scatter(x=x, y=y))

fig.update_layout(xaxis = dict(zeroline=True,
                               zerolinecolor='firebrick',
                               title_text = "x zeroline",
                               title_standoff = 4))

fig.update_layout(yaxis = dict(zeroline=True,
                               showgrid=False,
                               title_font = {"size": 20},
                               tickfont= dict(color='rgba(0,0,0,0)')))

for i, m in enumerate(yticks):
    fig.add_annotation(dict(font=dict(color='firebrick',size=12),
                                        x=0.066,
                                        y=yticks[i],
                                        showarrow=False,
                                        text=str(yticks[i])+' -',
                                        textangle=0,
                                        xanchor='right',
                                        xref="x",
                                        yref="y"))

fig.show()


text:
Q: What is correct course of action when finding free software projects whose executables are spreading a virus Today I found a GPLed project on SourceForge whose executables are spreading a virus. This fact has been pointed out several times in reviews of the project and the infected executable is still available for download. Apparently, older executables are not infected, so the project itself does not seem to be made with malicious purpose in mind.

There is no preferred way to contact developers and forums for the project are dead.

What should I do?
A: If you can't get in touch with the developers, then contact SourceForge.  Report the problem, give them detailed information they can use to verify the issue, and they'll (probably) take it down.  They're a reputable site and I imagine they wouldn't want to be associated with malware.

A: I would start by sending an email to the project maintainer and developers.

A: The State of Projects
Old popular, and no longer maintained and forgotten projects can often be used as a vector to spread viruses if someone is able to compromise the account and upload a new compiled version. The same has often been done with automatic update systems - even worse as they'll deliver themselves and often install an update on the users' systems without the end user knowing.
Possible Actions to Take
Maintainers and Developers
You can try to contact the developer/maintainers(s) but if it's an old project it's unlikely that they will respond. If their account has been compromised then you'll be giving them a heads up or left shouting at a wall.
Platform / Delivery Network
You may have a better chance removing the malicious code by contacting the platform that is hosting the software. I myself haven't tried to directly contact a platform like Sourceforge or NPM. The likelihood that you receive a response back is often tied to the size of the business and if it has been monetized -- if it's a one person show then good luck!
The more information you have to verify your takedown request the more likely and speedily it should happen.
The Community & Your Voice
Often you may try the above steps and get here feeling powerless, but if you're able to leave a comment or review on the software that may be the best thing you can do. Even though many end users will still download the software blindly or previously trust the software.

Extra: Recently & Future Prevention
Stop Reading Here™ or Continue ¯\_(ツ)_/¯
There was a highly used NPM package that the original maintainer was done with - as many open source projects reach in their life cycle. Someone reached out asking to maintain it. Surely this must feel like a nagging burden lifted from a developer's shoulders. Unfortunately the new maintainer released malware to steal crypto wallets.
Ironically I heard about this through word of mouth and reading the issue opened on the github repository before reading an article about it or seeing it show up in the npm audit. This goes to show that your voice on a public platform really can have an impact.
Our meetup group had a quick talk around what the community could do to prevent such a thing, and whose responsibility it is to prevent such from happening.
Platform / Delivery Network
Making it npm's responsibility would require a monetized situation in place which would suck, or maybe it would only be available to businesses - but then everyone else would benefit for free?
Source Maintainer
As open source maintainers we need to be mindful of the consequences of our actions. If you've been an open source maintainer it can become a chore as your intrinsic value you get from the project diminishes. It would be hard to say no to someone that seemingly has the energy you once had to keep your project moving forward. One thing to note is that some platforms allow for a review process before publishing if the correct permission levels are in place. In this instance the project's ownership was completely handed over, you should try not to do this unless you absolutely trust the person/entity - even still this feels like it's not a clean way of conducting the continuation of software that has been established and trusted. People could also make their on forks of code but then that can get messy. Sometimes the best course of action is to archive a project, deprecate it and try to move users towards a new library/project instead.
Community & Consumers
Current infrastructure could use some features to help out.
For instance releases could be verified, approved, or flagged by the community, just like how torrents can be rated up or down by the community so others can make quick decisions before they take the plunge. A high negative rating could flag a package and warn consumers about it and future installs.
As a consumer who blindly installs software and updates to it, it is your responsibility to watch what you're consuming. You can use package managers that have version locking in place to help negate this. Unfortunately I doubt many people spend the time required to review the 100's of packages they're installing when they lay down a good'ol npm install. Some businesses go through a vendor process when software changes; I would hope no business does this for NPM packages (it could seriously halt development), but this was an option brought up.
Money $$$
Nobody wants to pay for free open source software, but if those who were writing code were rewarded for their contributions they may be more motivated to maintain their software and community image. Money could come directly from the consumers or as a trickle down for the platform it's being delivered on. As much as I would hate to see it, I could see libraries following the same path as CI platforms - free for open source but cost for private/business - this could be handled with licensing, but developers don't want to waste time becoming licencing professions either (maybe they could be simplified and straight forward).


text:
Q: How to add a Menu Bar into a Window Frame? [QT with C++] I'm a beginner in C++ and I started learning how to use QT components through code at MVS IDE. I still don't know if that was the best option to begin, but since I'm a java programmer, I made the path I made with Java (Swing components). So, my problem is, how to comunicate two class  of my code, since in one I made the window frame and in the other I made my menu bar?
In java I would make something like:
JFrame frame = new JFrame();
JMenu menu = new JMenu();

frame.add(menu);

Anyway, This is my code:
#include "Header.h"

class MainWindow{

    private:

        QWidget *widget;

    public:

        void buildWindow(QApplication& app){

            widget = app.desktop();
            QMainWindow *main_window = new QMainWindow();
            QWidget *mainWid = new QWidget(main_window);
            MyMenuBar myMenuBar(mainWid);
            main_window->setWindowState(mainWid->windowState() | Qt::WindowMaximized);
            main_window->setWindowTitle("QT Trainning");
            main_window->show();
        }

};

class MyMenuBar:QMainWindow {

    public:

    MyMenuBar(QWidget* mainWid){

         QAction *quit = new QAction("&Quit", this);

         QMenuBar *menu = new QMenuBar(mainWid);
         QMenu *file;

         menu->addMenu(file);
          file = menuBar()->addMenu("&File");
            file->addAction(quit);

          connect(quit, SIGNAL(triggered()), qApp, SLOT(quit()));
    }

};

int main(int argc, char *argv[])
{
   QApplication app(argc, argv);

   MainWindow frame;

   frame.buildWindow(app);

   return app.exec();
}

I tryed to create an Instance of MenuBar inside the Window class but wans't so helpfull and to be honest most of the materials I found to deal with QT interface they supose that you are using the QT GUI...Any tips about how to solve the problem or what should I really do to practice C++??
Thanks in advance

A: You should specify access specifier for inheritance,otherwise default mode is public.
Also, if you are going to have all the classes in the same file the ordering is important(i think). In your case MyMenuBar should come before MainWindow. So, it is a better practice to have different components in different headers and then include them as necessary.
Here is the code for the case where you need two classes separately:
class TrainingMenu:public QMainWindow {

public:

        TrainingMenu(QMenuBar *menubar){
            QAction *quit = new QAction("&Quit", menubar);

            QMenu *file;

            file = menubar->addMenu("&File");
            file->addAction(quit);

            connect(quit, SIGNAL(triggered()), qApp, SLOT(quit()));
        }

};

class MainWindows:public QMainWindow{

private:
    TrainingMenu* _menu;
public:
    MainWindows(QMainWindow *parent = 0):QMainWindow(parent) {
        _menu=new TrainingMenu(MainWindows::menuBar());
        this->setWindowTitle("Qt training");
        this->setWindowState(Qt::WindowMaximized);
        this->show();
    }

};

int main(int argc, char *argv[])
{
   QApplication app(argc, argv);
   MainWindows window;

   return app.exec();
}

A: This example should be good enough. You do the following:

*

*Create a QMenu with the top widget as a parent

*Add submenu QMenu instances to the root level menu


text:
Q: Unrecognized field "className" , @JsonTypeInfo The conversion from json to java object is failing.It failing after updating to jackson version 2.9.7.
 @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include =
     JsonTypeInfo.As.PROPERTY, property = "className")
 public class DefaultValidator implements Validator {}

  ObjectMapper objectMapper=new ObjectMapper();
  objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
  objectMapper.configure(SerializationFeature.FAIL_ON_UNWRAPPED_TYPE_IDENTIFIERS, false);
  objectMapper.setVisibilityChecker(VisibilityChecker.Std.defaultInstance()
            .withFieldVisibility(JsonAutoDetect.Visibility.ANY)
            .withGetterVisibility(JsonAutoDetect.Visibility.NONE)
            .withCreatorVisibility(JsonAutoDetect.Visibility.NONE));
  obj = objectMapper.readValue(jsonBody, clazz);`

UIRowInput{private DefaultValidator rowCommmonValidator;}
Following is the exception :

Unrecognized field "@class" (class com.fe.core.validator.DefaultValidator), not marked as ignorable (0 known properties: ]) at [Source: (StringReader); line: 1, column: 3043] (through reference chain: com.ui.request.input.UpdateGraphInputRequest["graphInput"]->com.model.ui.graph.UIGraphInput["nodeInputs"]->java.util.ArrayList[0]->com.model.ui.graph.item.node.UINodeInput["nodeInputs"]->java.util.ArrayList[0]->com.model.ui.graph.item.node.UINodeInput["lineItemInputs"]->java.util.ArrayList[0]->com.model.ui.graph.item.lineItem.UILineItemInput["tabInput"]->com.model.ui.graph.item.lineItem.matrix.UITabInput["rowInputs"]->java.util.ArrayList[0]->com.model.ui.graph.item.lineItem.matrix.UIRowInput["rowCommmonValidator"]->com.fe.core.validator.DefaultValidator["@class"])

Thanks!!


text:
Q: What is this combinator? I used a combinator to calculate the average of a list of numbers...
const myCombinator = f => g => h => x => f(g(x))(h(x));
I could then use it like...
const div = a => b => a/b;
const sum = a => a.reduce((a, n) => a + n, 0);
const length = a => a.length();

const average = myCombinator(div)(sum)(length);

console.log(average([1, 2, 3, 4, 5, 6, 7, 8, 9]));

However, I'm not sure which combinator this is from a list like... http://www.angelfire.com/tx4/cus/combinator/birds.html
I was told initially that it's a Blackbird combinator but I don't think that is the case? Is that correct?
Is it a "named" combinator? If so, do you know which one it is?
From the comments
Blackbird is defined like... blackbird :: (c -> d) -> (a -> b -> c) -> a -> b -> d
However, I think my function is doing like...
myCombinator :: (b -> c -> d) -> (a -> b) -> (a -> c) -> a -> d
i.e. it returns a function that takes an a and returns a d. a is passed into two functions which creates b and c. They are then passed into a function that returns d.
After the above comment
I found it! From @evolutionxbox link I found the Starling_ combinator...
starling_ :: (b -> c -> d) -> (a -> b) -> (a -> c) -> a -> d
Which is exactly what I had written above :D

A: Thanks to the helpful link from @evolutionxbox I was able to find the Starling_ combinator which is defined as...
starling_ :: (b -> c -> d) -> (a -> b) -> (a -> c) -> a -> d
In my case...

*

*a -> b is my sum function that takes the array and returns a number.

*a -> c is my length function that takes the array and return a number.

*b -> c -> d is my div function that takes two numbers and divides them.

This is the first time I feel like I've understood combinators properly now. :)
Thanks for the help :)


text:
Q: How much does Celestia know about Zecora? Have the two - Princess Celestia and Zecora - ever met in the canon works? (comics including).
I guess Princess Celestia might know of Zecora from Twilight's friendship reports, and possibly from Luna (who did meet her during Nightmare Night, if briefly.) Zecora would be unlikely not to hear about the ruler of the land. Does the canon indicate any other connections between the two? Appearing within sight range from each other, learning about each other from other sources, or such? How much can I expect they know of each other?

A: Zecora and Celestia have appeared in the same episode 4 times (Swarm of the Century, Magic Duel, and Princess Twilight Sparkle parts 1 and 2), but as far as I'm aware have never appeared on-screen at the same time, nor met in the secondary media (novels/comics).

A: From an EqD interview with Faust,

"If we had penned more adventure stories, the only difference I can think of is that perhaps you would have seen more of Luna and Zecora.  Zecora was designed to be a sage and mentor to whom the ponies could go for information about their quests.  She was designed to be a second mentor to Twilight, but that didn't come to pass. And Luna, though good, was meant to be associated with darkness and night - and these are considered (by some) to be iffy themes for a show for young girls - so she had to slide to the wayside."

It would seem that Celestia would have known more about Zecora if Faust's idea had come to pass.

A: UPDATE: Season 7 finale has rendered the Journal of the Two Sister de-facto non-canon. This means that every consideration based on its content is now technically obsolete. The original answer is left for historical purpose, but its contents probably now reference non-canonical sources.

I will try and double-check all the comics I can get reference for, but it is worth noticing that zebras are specifically referenced in the book "The Journal of the Two Sisters", which is nothing more than a real world version of the book with the same name in the show.
While its "canon status" is unclear (I for one have once read some claiming that state that the show producer said all comics are intended to be canon unless they contain mayor error that need to be rectified - the most famous example of this begin an issue of the IDW comic having Twily mother begin the author of the Daring Do books), the Journal has a lot of interesting info if you are willing to incorporate it in your fan works.
The book describes how Celestia and Luna became princesses, how they discover the Tree of Harmony (surprise: in the book, Star swirl is said to be fully able to time travel at wish, has minor control on his age via the same spell, already knows the tree and probably knows about our Twily too..) and some other minor details about their life I won't list now for sake of brevity. What is important is that the book has an interesting passage. Not only Luna becomes friend of a manticore she meets in the Everfree (does this remember anyone something?), she and her sister discover a small village of zebras hidden in the forest.
If you take this one as canon, not only they should know about Zecora in the first place, but they should also know what happened of the other zebras that once lived here. The show make you assume that Zecora moved here from a distant country, but the book seem to indicate that she at least had a reason to move there if not even begin the last one of that same old tribe.
Sadly, there is not much more to be drawn from the little infos in the books for now (let me check, maybe some recent comic explored this scenario a little further), but I think you may still want to check the Journal if you can grab a copy. While it does not contain a direct evidence that may solve your doubt, it can at least provide some ideas as how to incorporate your fan works with the main canon.
Side notice:
I don't have many information about this one specifically yet, but it seem that one of the recent chapter books had Luna and Zecora interact directly to solve some issues. If that is the case, it is worth noticing that the chapter books can be considered canon too, to the point that the show even acknowledged one of them during season 5. I will try to update this post as soon as I can get some more info.


text:
Q: Making multilayer accordions with pure JS and using nextElementSibling New to Javascript. I recently posted a question about creating multiple multilayer accordions. I got some great feedback, but someone mentioned that if my HTML was set up correctly, I could achieve the same goal by using nextElementSibling and thus have much cleaner JS.
I figured out how to do this using only queryselect. See the below example:
HTML:

dropdown one

dropdown two

content content content content

CSS:
.mainAccordion {
    background-color:lightblue;
    width:200px;
    margin:auto;
    padding:3%;
}
.mainAccordion :nth-child(1){
    background-color: blue;
    padding:3%;
    cursor:pointer;
    color:white;
}

.mainAccordion :nth-child(2){
    background-color:yellow;
    cursor:pointer;
    max-height:0;
    overflow:hidden;
}

.mainAccordion :nth-child(3){
    font-weight:bold;
    max-height:0;
    overflow:hidden;
}

And the JS:
var mainAccordion = document.querySelector(".mainAccordion").addEventListener("click", function(e) {
    if (e.target.nextElementSibling.style.maxHeight) {
        e.target.nextElementSibling.style.maxHeight = null;
    } else {
        e.target.nextElementSibling.style.maxHeight = e.target.nextElementSibling.scrollHeight + "px";
    }
});

This works as intended. However, when I introduce multiple multilayer accordions and switch to "querySelectorAll", it stops working. Also depending on the browser, I sometimes get an error message saying my "addEventListener" is not a function.
See below:
HTML:

dropdown one

dropdown two

content content content content

dropdown one

dropdown two

content content content content

CSS:
body {
    display:flex;
    width: 900px;
    margin:auto;
}
.mainAccordion {
    background-color:lightblue;
    width:200px;
    margin:auto;
    padding:3%;
}
.mainAccordion :nth-child(1){
    background-color: blue;
    padding:3%;
    cursor:pointer;
    color:white;
}

.mainAccordion :nth-child(2){
    background-color:yellow;
    cursor:pointer;
    max-height:0;
    overflow:hidden;
}

.mainAccordion :nth-child(3){
    font-weight:bold;
    max-height:0;
    overflow:hidden;
}

and JS:
var mainAccordion = document.querySelectorAll(".mainAccordion").addEventListener("click", function(e) {
    if (e.target.nextElementSibling.style.maxHeight) {
        e.target.nextElementSibling.style.maxHeight = null;
    } else {
        e.target.nextElementSibling.style.maxHeight = e.target.nextElementSibling.scrollHeight + "px";
    }
});

I've tried changing "querySelectorAll(".mainAccordion") to getElementsByClassName("mainAccordion") but also doesn't work.
Is forEach somehow involved?
Note: I know you can also achieve the same goal by toggling a class that has the "max-height:0;overflow:hidden". However, this was how I was initially taught to do accordions.
This is for my own practice.
I appreciate the help.

A: Try this:
let accordionElements = document.querySelectorAll(".mainAccordion");

    accordionElements.forEach(element => {
        element.addEventListener("click", function(e) {
            if (e.target.nextElementSibling.style.maxHeight) {
                e.target.nextElementSibling.style.maxHeight = null;
            } else {
                e.target.nextElementSibling.style.maxHeight = e.target.nextElementSibling.scrollHeight + "px";
            }
        })
    });

It's because with querySelector() an HTML Element is return. With querySelectorAll() it's a NodeList. In your sample code you try to attach an event to a node list which is not possible.
You need to loop inside and then attaching the event to each HTML Element inside.

A: i think that the problem is that the querySelector() returns the first Element within the document that matches the specified selector. then the event listener will be applied to the first element found.
the querySelectorAll() returns a list. you could use it with forEach like this
  var mainAccordion = document.querySelectorAll(".mainAccordion");
  console.log(mainAccordion);
  mainAccordion.forEach(accordion => {
    accordion.addEventListener("click", function(e) {
      if (e.target.nextElementSibling.style.maxHeight) {
        e.target.nextElementSibling.style.maxHeight = null;
      } else {
        e.target.nextElementSibling.style.maxHeight =
          e.target.nextElementSibling.scrollHeight + "px";
      }
    });
  });


text: Q: Functoriality of sheaf Cohomology Let $f:Y\rightarrow X$ be a morphism of schemes. I would like to construct a natural map of homologies $$H^{q}(X,F)\rightarrow H^{q}(Y,f^{*}(F))$$ where $F$ is a sheaf on X. My idea is to take an injective resolution $I^{\bullet}$ of $F$ and $J^{\bullet}$ an injective resolution of $f^{*}(F)$. Of course the resolution $I^{\bullet}$ is flasque, so I think if I prove that $f^{*}(I^{\bullet})$ is flasque then I am done because there is a map $I^{\bullet}\rightarrow f_{*}f^{*} I^{\bullet}$. But I am stuck on how to do this. Any ideas?


text:
Q: Finding mix string fix format data from text file from c# regular expression I have text file which has data such as:
I and  team discussed and decide for JobNo ACK33938Y9   . Need to validate it . Next no : JIK24928Z9.

I need to extract data similar to ACK33938Y9 and JIK24928Z9, which have a fixed pattern. Each text file contains different data with the same fixed pattern.
I have tried using this c# regular expression, but it does not give me the desired result.
^[A-Y][A-Y][A-Y]{1}\d{1}d{1}d{1}d{1}d{1}[A-Z]{1}

Can someone please point out what I am missing?

A: You can try this:
[A-Y]{3}\d{5}[A-Z]\d

Sample Code:
    string pattern = @"[A-Y]{3}\d{5}[A-Z]\d";
    RegexOptions options = RegexOptions.Multiline;

    foreach (Match m in Regex.Matches(input, pattern, options))
    {
        Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
    }

Run the code here


text:
Q: Errors: document type does not allow element "div" I have errors in my code:
document type does not allow element "div" here; missing one of "object", "applet", "map", "iframe", "button", "ins", "del" start-tag

And my code:

What is wrong?

A: I just wrote


text:
Q: Finding APL symbols on the keyboard I use GNU APL on Debian 10. My Apple keyboard is configured to input APL characters using the right Alt key and the latter is remapped to the right Command key:
setxkbmap se,apl -variant ,dyalog -option grp:switch -option lv3:rwin_switch

I can now type APL characters like ⍴ (rho) and ⍳ (iota) with RightAlt+R and RightAlt+I respectively. However, many APL symbols have a less intuitive placement on the keyboard so I would like to see where each symbol is located. I have tried using xkeycaps* but it shows no APL characters. Any clues?
*I use the following keyboard setting

PC -> 105 key, wide Delete, tall Enter -> XFree86; Swedish

A: GNU APL has a command ]KEYB which shows an APL keyboard layout for people that can't remember all the keys. The command does not exactly show the keyboard layout in use but rather a fixed text file with a common layout. But you can change the text that is being displayed so that it shows exactly your keyboard layout.


text:
Q: Does $x_n$ posses a weak$^* -$ convergent sequence by banach-aluoghlo Theorem? Let $X$ be a Banach space with the dual $X^\ast$. Let $\{x_n\}_{n=1}^{\infty}$ be a norm-bounded sequence in $X^\ast$, then can we claim that $x_n$ posses a weak$^\ast$-convergent subsequence by Banach-Alaoglu Theorem?

A: Yes, if $X$ is separable, no in general. See the Wikipedia page, e.g.
Beware that a compact space need not be sequentially compact. And IIRC, $X=\ell^\infty$ is an example where this happens for the dual ball.


text:
Q: RSA/ECB/PKCS1 padding Encryption in SAP ABAP I have a requirement where I need to do Encryption of my Private Key using Public Key(provided by third party) with RSA/ECB/PKCS1 Encryption
The Public Key is already Padded.
I am generating the private key using cl_sec_sxml_writer=>generate_key( cl_sec_sxml_writer=>co_aes256_algorithm_pem ). Is this the correct way to generate a new key or we can have any random string as a private key?
This private key will be used to encrypt a data string using AES/ECB/PKCS7 padding encryption and then convert to BASE64 and send it via API call. For AES/ECB/PKCS7 padding, I am using the classes provided by following https://github.com/Sumu-Ning/AES. pfb implementation below:
CALL METHOD zcl_aes_utility=>encrypt_xstring
  EXPORTING
    i_key = lv_xstr
    i_data = lv_pwd_xstr
  * i_initialization_vector =
    i_padding_standard = zcl_byte_padding_utility=>MC_PADDING_STANDARD_PKCS_7
    i_encryption_mode = zcl_aes_utility=>mc_encryption_mode_ecb
  IMPORTING
    e_data = lv_encrypt

My query is , how do I encrypt the private key using public key and RSA/ECB/PKCS1 Encryption.
The public key is of length 399 chars and something like this
DfP4hVgyXMSNWJFWakwo44p1PMyRKSmFG+UGq
I have checked other blogs that asks to use standard fm SSF_KRN_ENVELOPE but I am not able to understand how to use it.
Please help. Let me know in case of any further details required.


text:
Q: a 'geek', a 'computer addict'? As I see some people, especially internauts, just by thinking that they had posted a video in youtube, or they have a facebook account, or they've created a blogger website etc..., they simply call themselves 'geeks'.
Then, according to Merriam Webster , there are two possible definitions of 'geek' :

*

*a person who is socially awkward and unpopular : a usually intelligent person who does not fit in with other people

*a person who is very interested in and knows a lot about a particular field or activity

So, that's what makes me confused!
Does the term 'geek' stands for a facebook addict, generally computer addict ?

A: The computer magazines that I have worked at use geek as a code word for "at least somewhat knowledgeable computer enthusiast." The fuzziness of the definition is intentional, since the bigger the geek tent is, the more readers can be squeezed into the magazines' vaguely clubbish, vaguely exclusive category of admirable and welcome readers.
No doubt you could find a similar process at work with the term innovator in business executive magazines, the term audiophile in what used to be called stereo magazines, the term connoisseur in wine magazines, and the term aficionado in bullfighting magazines: Objectively the word may seem to set the qualifying bar extremely high, but writers and editors are actually quite willing to give a pass to any reader who self-identifies as a member in good standing. And of course the self-flattering status extends far beyond any encouragement that magazines may offer.
If you want to label yourself a geek, regardless of your actual level of computer knowledge and computing skill, who's going to stop you? It's not as though you have to earn certification first. And to the extent that this arrangement falls short of (or even seems to debase) the lexicographically established definition of the term, it's part of a long tradition of such broadening—and eventually dictionaries will adjust to accommodate the new, less exacting meaning.

A: I would be a little suspicious of how geeky things that have labelled themselves as "geeky" actually are. Often self-assigned labels like that are marketing in some form and reflect who they want to attract rather than necessarily being an accurate description.
As for the two definitions listed in the question, in my view the second definition is the more relevant to the use of geek or geeky in the context that the question appears to focus on. Not that the two definitions are mutually exclusive, there's in fact a great deal of overlap.
Then there's of course also the never ending geek vs nerd debate, where the line is definitely blurry and where the typical definitions yet again have a good deal of overlap. I'll take the risk of dealing with these terms as almost synonymous, which will quite possibly upset someone.
More to the point, I don't think that having a Facebook account or even posting videos on Youtube qualifies as geeky in itself, both are quite normal these days (Facebook more so) and being geeky isn't really about the medium used for expressing yourself unless there's actually something to that choice of medium.
For instance, amateur radio as a medium may qualify as geeky/nerdy as the people involved are enthusiasts that have some knowledge of the technology, equipment, etc. but the average Facebook addict does not typically have any particular insight with regard to Facebook, they barely chose the medium in the first place and they could just as well have used something else.
Either way, I think that the main question really has to be: what content are these potential geeks actually posting? Are they expressing their enthusiasm and insight on some topic? Does their knowledge go beyond just scratching the surface? Then there's a good chance that they can be classified as geeks (and/or nerds), regardless whether they are talking about the lore of Lord of the Rings, the optimal strategies in some computer game, electronics design, computer hardware, car tuning, sports statistics, carpentry, etc.
Just as a point of reference, here's a Youtube channel that I would consider a prime example of a geeky/nerdy (by the second definition of geek from the question): EEVBlog.
As a note regarding the first definition of geek from the question, there's of course the possibility that someone who is a bit socially awkward prefers interacting with others online but  that's quite possibly hard to tell from their online behavior and it's probably not something they would go out of their way to advertise.


text:
Q: Accessing another class I've just started learning Java and this is the first thing I've written with it.
But I have problems getting into the concept of classes and thus I'm getting several errors.
I have two files; the first one is Book.java
If I try to compile the code I get 15 Errors, some of those because I return NULL where I am unable to do so. But I want to look for a solution for the other Errors first. All of them say 'cannot find symbol', because it apparently cannot access the other class.
Both of the files are in the same directory.
I've read that I have to create a Book class in the BookStore files main method and access it with that, but I don't know how to do that in this case.
I hope you can help me with my problem.
J.

A: There are multiple things that i can instantly spot there,
1. null instead of NULL
2. You did not explicitly implement the constructor for Book.
When  you create a Book instance you need to use
Book book = new Book();

Note that the constructor has to be the same name as the class which is in this case "Book"
3. This is just a note and not something wrong, but take a look at the HashMap data structure. Might help a lot instead of loops.

A: That Book class isn't the best choice.  Try this:
public class Book {
    private final String name;
    private final String isbn;
    private final double price;

    public Book(String name, String isbn, double price) {
        this.name = name;
        this.isbn = isbn;
        this.price = price;
    }

    public String toString() {
        return String.format("name: '%s' ISBN: %s price %10.2f", this.name, this.isbn, this.price);
    }
}

A: Line 2 of your "main" method should be creating a "new" Bookstore, just like the line above it is doing. As for the first line of "main" though; you're creating a new book, and then never using it anywhere, so it can be removed.
This should remove at least 1 error and 1 warning from your list of errors. It would be helpful if you listed all the errors your compiler is giving though, so I'm not guessing.


text:
Q: Find the list from list of lists whose avg is closest to a given number in python? Given l = [ [3,4,5], [30,40,50], [300,400,500] ] and a number 45
foo(l, 45) should return [30,40,50] since it's avg is closest to 45.
What's a good way to write such a function "foo"?
EDIT :
Here's my code.. (not tested yet)
def _avg(l):
    return reduce(lambda x,y: x+y, l)/len(l)

def foo(clusters, point):

    return min(clusters, key=lambda x: abs( _avg(x) - point) )

A: Find the min of a generator expression that generates abs(sublist_average - target_average) values.
l = [[3,4,5],[30,40,50],[300,400,500]]
avg = 45
result = min(((i,abs(sum(x)/len(x)-avg)) for i,x in enumerate(l)),key=lambda x:x[1])
#result = (1, 5.0)

print('the minimum delta, found at index {}, is {}'.format(*result))
#the minimum delta, found at index 1, is 5.0

A: How would you do this on paper? You'd start by computing the average of the first one, take the difference, and save off the index of the smallest distance so far. The simplest solution, is probably the best, most understandable solution.

A: Written very verbosely...
import sys
def closest_average_to_num (list_of_lists, num):
    closest_list = []
    lowest_diff = sys.maxint
    for list_of_interest in list_of_lists:
        avg = sum(list_of_interest) / float(len(list_of_interest))
        if (lowest_diff > abs(avg - num)):
             lowest_diff = abs(avg - num)
             closest_list = list_of_interest
    return closest_list

Example Output:

>>> closest_average_to_num ([ [3,4,5], [30,40,50], [300,400,500] ], 45)
[30, 40, 50]


text:
Q: JavaFX FXML injection timing In my GUI program I have an accordion with GridPanes which are injected into a controller. After the stage is shown however, one of the GridPanes (the last one of a large number of panes to be injected) has a null value and causes a nullpointerexception. It has been declared in the controller with the FXML tag.
If I pause the program in the debugger and then proceed, the GridPane is not null, but causes an "Exception in Application start method".
Has anyone ever come across this type of behaviour? Is it possible that there is a timing (different threads) problem?


text:
Q: How to fetch values from nested array in mongodb I am using mongodb database for storing data and using mongoose for making schema.Below is my schema:
expense.js
const mongoose = require('mongoose');

const ExpenseSchema = new mongoose.Schema({

  payerid:{
      type: String,
      required: true
  },
  paid:{
    type: Number,
    require: true
  },
  owers:[
      {
     owerid:{
       type:String
     },
     amt:{
       type: Number
     }
    }
  ],
  name:{
    type: String,
    required: true
  },
  amount:{
      type: Number,
      require: true
  }
});

const expense = mongoose.model('expense',ExpenseSchema);
module.exports = expense;

Here is my database structure:

I want to fetch the owerid and amt values from the array.How can I  fetch this I am not getting idea.Someone let me know.

A: You can do it like this:
const Expenses= require('../models/expense');

const getExpense = async (expenseId) => {
  try {
    const expense = await Expenses.findById(expenseId);
    // Now, you can access owers array of the document
    console.log(expense.owers);
    return expense.owers;
  } catch (error) {
    console.log('ERROR: ', error);
  }
}


text:
Q: R optparse and short flag arguments I can't get optparse to work with short arguments. What's wrong with this?
library("optparse")
packageVersion("optparse")
option_list = list(
  make_option(c("-f", "--file"), action = "store", type="character", default=NULL)
)
opt_parser = OptionParser(option_list=option_list)
parse_args(opt_parser, args=c("--file=anyfile.txt")) # this works
parse_args(opt_parser, args=c("-f anyfile.txt")) # but this does not

[1] '1.7.1'
Error in getopt_options(object, args) :
  Error in getopt(spec = spec, opt = args) :
  short flag "f" requires an argument, but has none

A: args is a character vector. From help:

A character vector containing command line options to be parsed. Default is everything after the Rscript program in the command line. If positional_arguments is not FALSE then parse_args will look for positional arguments at the end of this vector.

args=c("-f", "anyfile.txt")


text:
Q: Need LWJGL Setup Guide For Eclipse Every time I look online the download is not in the same format as the current version, which leads to following the instructions and not being able to use the libraries I need. I'm new to lwjgl but fluent in java if someone could help me set up lwjgl I would be every appreciative. More specifically, the download is not broken up into folders like many that I see in tutorials.

A: rightclick on Project > Properties > Java Build Path > add exterlnal jars...
Now navigate to the downloaded and extracted LWJGL-Folder and select all .jar files inside. And press Add and then Apply. Now it should work fine.


text:
Q: Properly handling unique keys in a hash I realize hashes have unique keys already, but my question is aimed at a particular use case (that I feel may be common) regarding hashes.
I have a google map (v3) on my website. I load a bunch of locations from my database, and throw markers on the map at each location. I had an issue in my application where I was seeing duplicate markers for every location. I decided to add a check at the top of my add marker function, to use a hash of previously placed markers (stored by location).
markers = {};

function addMarker(latlng) {
  if (!markers.hasOwnProperty(latlng)) {
    markers[latlng] = true;
  } else {
    return;
  }

  // do other stuff
}

This works, but it feels hacky. Adding the unused boolean value to each hash key/pair just doesn't feel right, because it's technically not used... I just need the key half.
Is there another approach to accomplish the same idea?


text:
Q: Mocking decorators in python with mock and pytest How to patch my custom decorator with monkeypatch or pytest.mock? i manage to mock it by doing (answer to this question):
package.decorator = mytestdecorator
The problem is that it breaks some other tests where i actually need that decorator to work.

A: You have to control complete lifecycle of your mocked decorator and revert the decorator back to original state.
It can be done in few different ways:

*

*context manager which builds the mocked decorator, and reverts it back by __exit__.

*setup and teardown functions for your test, teardown must revert the decorator.

*pytest fixture with finalizer

*pytest fixture with yield expression.

Personally I like the @pytest.yield_fixture as it keeps the code short and as soon as you realize, that all what comes after yield statement in the fixture code is cleanup code, things are very clear to do.


text:
Q: Dimension errors in neural network in Keras I am trying to implement a neural network where I merge/concatenate a fully connected neural network with a convolution neural network. But when I fit the model, I get the following error:

ValueError: All input arrays (x) should have the same number of
  samples. Got array shapes: [(1, 100, 60, 4500), (100, 4500)]

I have two different inputs:

*

*image(dimensions: 1,100,60,4500) where 1 is the channel, 100: # of sample, 60*4500 (dimension of my image). This goes to my convolution neural network

*positions(dimensions: 100,4500): where 100 refers to samples.
Dimension for my output is 100,2.
The code for my neural network is:
###Convolution neural network
b1 = Sequential()
b1.add(Conv2D(128*2, kernel_size=3,activation='relu',data_format='channels_first',
              input_shape=(100,60,4500)))
b1.add(Conv2D(128*2, kernel_size=3, activation='relu'))
b1.add(Dropout(0.2))

b1.add(Conv2D(128*2, kernel_size=4, activation='relu'))
b1.add(Dropout(0.2))

b1.add(Flatten())
b1.summary()

###Fully connected feed forward neural network
b2 = Sequential()
b2.add(Dense(64, input_shape = (4500,), activation='relu'))
b2.add(Dropout(0.1))
b2.summary()

model = Sequential()

###Concatenating the two networks
concat = concatenate([b1.output, b2.output], axis=-1)

x = Dense(256, activation='relu', kernel_initializer='normal')(concat)
x = Dropout(0.25)(x)
output = Dense(2, activation='softmax')(x)

model = Model([b1.input, b2.input], [output])

model.compile(loss=keras.losses.categorical_crossentropy,
              optimizer=keras.optimizers.Adam(),
              metrics=['accuracy'])

history = model.fit([image, positions], Ytest, batch_size=10,
              epochs=1,
              verbose=1)

Also, the reason why my 'image' array is 4 dimensional is because in the beginning it was just (100,60,4500) but then I ran into the following error:

ValueError: Error when checking input: expected conv2d_10_input to
  have 4 dimensions, but got array with shape (100, 60, 4500)

And upon googling I found out that it expects # of channels as an input too. And after I added the # of channel, this error went away but then I ran into the other error that I mentioned in the beginning.
So can someone tell me how to solve for the error (the one I specified in the beginning)? Help would be appreciated.

A: It is not a good practice to mix Sequential and Functional API.
You can implement the model like this
i1 = Input(shape=(1, 60, 4500))

c1 = Conv2D(128*2, kernel_size=3,activation='relu',data_format='channels_first')(i1)
c1 = Conv2D(128*2, kernel_size=3, activation='relu')(c1)
c1 = Dropout(0.2)(c1)
c1 = Conv2D(128*2, kernel_size=4, activation='relu')(c1)
c1 = Dropout(0.2)(c1)
c1 = Flatten()(c1)

i2 = Input(shape=(4500, ))
c2 = Dense(64, input_shape = (4500,), activation='relu')(i2)
c2 = Dropout(0.2)(c2)

c = concatenate([c1, c2])

x = Dense(256, activation='relu', kernel_initializer='normal')(c)
x = Dropout(0.25)(x)
output = Dense(2, activation='softmax')(x)

model = Model([i1, i2], [output])

model.summary()

Note the shape of i1 is shape=(1, 60, 4500). You have set data_format='channels_first' in Conv2D layer hence you need 1 in the beginning.
Compiled the model like this
model.compile(loss='categorical_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])

Placeholder data
import numpy as np

X_img = np.zeros((100, 1, 60, 4500))
X_pos = np.ones((100, 4500))
Y = np.zeros((100, 2))

Training
history = model.fit([X_img, X_pos], Y, batch_size=1,
              epochs=1,
              verbose=1)

A: You number of samples (batch size) should always be the first dimension. So, your data should have shape (100, 1, 60, 4500) for image and (100, 4500) for positions. The argument channels_first for the Conv2D layer means that the channels is the first non-batch dimension.
You also need to change the input shape to (1, 60, 4500) in the first Conv2D layer.


text:
Q: Why is CollectionChanged not threadsafe? I'm working on a WPF application and found that property changed notifications on binded properties can happen from a background thread, however for making any change to an observablecollection(like adding or removing item) has to happen from a UI thread. My question is why is it so? Both INotifyPropertyChanged and INotifyCollectionChanged are subscribed by UI controls, then why an exception for INotifyPropertyChanged?
For example:
 public class ViewModel : INotifyPropertyChanged
    {
        ObservableCollection<Item> _items = new ObservableCollection<Item>();

        private string _name;
        public string Name
        {
            get { return _name; }
            set
            {
                _name = value;
                //Can fire this from a background thread without any crash and my
                //Name gets updated in the UI
                InvokePropertyChanged(new PropertyChangedEventArgs("Name"));
            }
        }

        public void Add(Item item)
        {
            //Cant do this from a background thread and has to marshal.
            _items.Add(item);
        }

        public event PropertyChangedEventHandler PropertyChanged;

        public void InvokePropertyChanged(PropertyChangedEventArgs e)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null) handler(this, e);
        }
    }

NOTE: CollectionChanged event from a background thread crashes the app, however PropertyChanged event from a background thread updates the UI without any issues and yes, this is in .NET 4.0

A: This problem is not related to thread safety. The issue is that the CollectionChanged event is raised from a worker thread, which means the handlers are executed in that same thread, and when a handler tries to touch the UI you have an exception because that's only allowed from the UI thread.
The same would also happen for the PropertyChanged event if the situation were identical, there is no special treatment being given to either event.
If you need to touch the UI from within your event handlers then you have to either make sure the event is raised on the UI thread or else the event handlers have to check with Dispatcher.CheckAccess if marshalling changes to the UI thread is needed and Dispatcher.BeginInvoke to do so.

A: Most likely you mean the binding mechanisms.
Binding does not work directly with the CLR property and the PropertyChanged event.
Binding uses reflection for its work.
These are in order of priority: PropertyDescriptor, PropertyInfo, DependencyProperty, and DynamicPropertyAccessor.
You can see it here: PropertyPathWorker.SetValue(object item, object value).
For the same reason, if a property changes ONLY by bindings, then it will be monitored regardless of the presence of the INotifyPropertyChanged interface.
Also, the use of reflection allows you not to worry in which flow the observed property will be changed.
In the case of collections, binding is also insensitive to the stream in which this collection will be assigned to the monitored property.
BUT monitoring of changes in the collection (INotifyCollectionChanged and IBindingList) is no longer provided by the binding mechanism, but by the internal logic of the ItemsControl class.
There is already a direct subscription to observation events, this makes this logic sensitive to the thread in which the collection will change.
If it is not a UI thread, then the observation will be destroyed, or even an exception will be thrown.
It is enough just to be convinced of this.
Demo example.
Class ViewModel with random collection change.
public class RandomCollectionViewModel
{
    public ObservableCollection<int> Numbers { get; }
        = new ObservableCollection<int>() { 1, 2, 3 };
    private static readonly Random random = new Random();
    private readonly Timer timer = new Timer();

    public RandomCollectionViewModel()
    {
        timer.Interval = 500;
        timer.Elapsed += (s, e)
            => Numbers[random.Next(Numbers.Count)] = random.Next();
        timer.Start();
    }
}

XAML using bindings to display collection items:
<StackPanel>
    <FrameworkElement.DataContext>
        <local:RandomCollectionViewModel/>
    </FrameworkElement.DataContext>
    <TextBlock Text="{Binding Numbers[0]}"/>
    <TextBlock Text="{Binding Numbers[1]}"/>
    <TextBlock Text="{Binding Numbers[2]}"/>
</StackPanel>

XAML using ItemsControl to display collection items:
<StackPanel>
    <FrameworkElement.DataContext>
        <local:RandomCollectionViewModel/>
    </FrameworkElement.DataContext>
    <ItemsControl ItemsSource="{Binding Numbers}"/>
</StackPanel>

These examples clearly show the difference in the work of bindings and ItemsContol.


text:
Q: How do you split linestrings from a shapefile at 10km vertices? I have a shapefile of river segments that I've imported into R. The segments range in length from 5-115km. I want to split the segments that are over 10km into 10km chunks. So I use st_segmentize. But this doesn't actually split a long line into multiple new shorter lines, which is what I want... Is there a way to do this? I think st_segmentize just adds vertices every 10km. So I just need to split the lines at the vertices.
Code so far:
library("sf")
rivers = st_read("./YukonMain4_copy.shp", layer = 'YukonMain4_copy')
seg = st_segmentize(rivers, units::set_units(10,km))

Thanks for your help!


text:
Q: Sonar deprecated rule flags the use of 'subscribe' as deprecated httpResp.subscribe({
 next: this.someMethod.bind(this)
})

Sonar ("Deprecated APIs should not be used" rule) flags the use of subscribe with:
"subscribe is deprecated: Use an observer instead of a complete callback"
This is in regards with the RXJS6 changes where the use of subscribe(callback) is considered deprecated. I've changed the call as stated here https://stackoverflow.com/a/55472361 but I still get the line flagged.
Does anyone know why?


text:
Q: How to escape display: -webkit-box; declaration in LESS? Escaping in LESS, either through e or ~ works pretty well in most of the cases. However, the declaration display: -webkit-box; doesn't show in the resulting CSS, even after using e or ~.
All other declarations of that class is present but display: -webkit-box;
What am I missing?

A: display: -moz-box / -webkit-box
Per MDN

This property is a non-standard extension. There was an old draft of the CSS3 Flexbox specification that defined a box-flex property, but that draft has since been superseded.

They also state:

Warning: This is a property for controlling parts of the XUL box model. It does not match either the old CSS Flexible Box Layout Module drafts for 'box-flex' (which were based on this property) or the behavior of '-webkit-box-flex' (which is based on those drafts).

Basically, don't use it...it has almost no browser support (except older versions of Firefox)


text:
Q: Howto specify library location when compiling How do I specify the location of a library when running ./configure ?
I have searched around and think the answer lies in setting LDFLAGS and CPPFLAGS, but I,m not sure how to do it.
Specifically, I have compiled libx264 and I now want to compile libav and enable libx264 support, but dont know how to point ./configure to my libx264 include and lib folders.
Thanks.

A: There are two ways to pass configuration variables to ./configure, and it depends quite a bit on the specific project, so you have to check the documentation.
The first one is to use the --with... options that the author of the script have decided to provide. For example, xcircuit has to be configured like this in 14.04:
./configure --with-tcl --with-tk --with-tcllibs=/usr/lib/x86_64-linux-gnu/ --with-tklibs=/usr/lib/x86_64-linux-gnu/

The other way is passing an environment variable to the script (in configuration stage) or to the Makefile (in the compilation phase):
CPPFLAGS=-Wall ./configure

or
CPPLAGS=-Wall make

In summary, it's really up to how the author wrote the software. You should refer to the specific documentation, in you case, of libav.

A: Thanks for the pointer. I did more reading and discovered how to do this. The solution is two-fold.

*

*Compile x264 with '--enable-shared' as well as '--enable-static'. Without specifying '--enable-shared', the library was never found.

*Specify the location of the 'lib' and 'include' files generated by the x264 make process like this :-
./configure --extra-ldflags="-L/path/to/extra/lib" --extra-cflags="-I/path/to/extra/includes" --enable-x264 ..etc  ..etc
I have now successfully compiled libav, with x264 support, and have the following binaries :-
avconv, avplay, avprobe, avserver, ffmpeg.
Off course I am sure if I had just installed libav using apt-get I would have saved myself a lot of trouble, but as this was a learning process I think I have learned a lot.


text:
Q: 32bit integer scaling with no overrun Hi I have a following values:
uint32_t value = 1230000;
uint32_t max_value = 1234567;

Now, I would like to perform scaling:
uint32_t scaled = value * 1000000 / max_value;

The problem is if I use 32bit integer it will overrun for such big numbers.
On the other hand I cannot use 64bit. Any idea how to properly implement mentioned scaling?
EDIT
Just to mention, I am working on STM32 - a 32-bit micro-controller, where performing 64-bit multiplication and division is extremely costly. Therefore I would like to avoid them.

A: You can do it by seeing scale as a base-1000 number: value = value_high*1000 + value_low. Calculate value_high's and value_low's contribution to scaled separately, storing the intermediate values as a fraction: scaled = scaled_int + scaled_remainder/max_value
uint32_t value_low = value%1000;
uint32_t value_high = value/1000;
uint32_t scaled_int, scaled_remainder;

uint32_t low = value_low * 1000000;
scaled_int = low / max_value;
scaled_remainder = low % max_value;

scaled_int += value_high * 810;  // pre-calculated 1000*1000000 / max_value
scaled_remainder += value_high * 730;  // pre-calculated 1000*1000000 % max_value
scaled_int += scaled_remainder / max_value;
scaled_remainder = scaled_remainder % max_value;

Also, you don't have to use base 1000, base 1024 might be a bit faster. As long as the 4th and 8th line don't overflow at their maximum value, it should work.

A: you can declare scaled as unsigned long long type  like below & then do explicit typecast accordingly.
unsigned long long scaled = (unsigned long long)value * 1000000 / max_value; /* make either operand of unsigned long long type explicitly */
printf("%llu\n",scaled);

A: if your translater can support 64bit,then
uint32_t scaled =(uint32_t)((uint64_t)value * 1000000 / max_value);

if support float,then
uint32_t scaled =(uint32_t)(value *1.0 / max_value* 1000000);

There will be a little loss of precision.

A: The fastest way of scaling is using the 2 power scale factors.
Even you have two numbers scaled using different scale factors - the arithmetic is trivial.
example:
uint32_t scaledDiv(uint32_t a, uint32_t b, uint32_t *sclef)
{
    *sclef = __builtin_clz(a);
    a <<= *sclef;
    return a/b;
}

A: The problem is of form: value/max_1 = x/1000000.
Without solving this in closed form, the closest x can be calculated iteratively using bisection.
 uint32_t step=max_value>>1;
 uint32_t v=0, x=0, step2=1000000/2 << 12;
 // step2 has been scaled to add extra precision
 while(step) {
    if (value > v+step) { v+=step; x+=step2; }
    step>>=1; step2>>=1;
 }
 x=(x+2048)>>12; // scale down and round

The result will finish in 32 iterations.


text:
Q: Keyframes opacity with image css I have created a double sided box, that when you hover, shows the flip side. I have added in a keyframe that goes from opacity: 0 to opacity: 1 to create a fade effect on hover.
It works to flip the card, however when you move the cursor off the box to return to it's original state, the image does not fade out, and you can see the background of the image when you should not. Please refer to the example below.

.catInner3 {
  display: grid;
  grid-template-columns: repeat(1, 1fr);
  grid-template-rows: repeat(1, 280px);
}

p {
  color: white;
}

.iprodBox {
  background-color: #ffffff;
  width: 330px;
  height: 230px;
  cursor: pointer;
  transition: 1s;
  box-shadow: 3px 1px 6px rgba(0, 0, 0, 0.25);
}

.iprodImg {
  height: 80%;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.iprodImg img {
  object-fit: contain;
  height: 70%;
  width: 70%;
}

.iprodTitle {
  height: 20%;
  width: 100%;
  background-color: #184e77;
  box-shadow: 3px 1px 6px rgba(0, 0, 0, 0.25);
  display: flex;
  align-items: center;
  justify-content: center;
  transition: 1s;
}

.iprodDesc {
  position: relative;
  bottom: 80%;
  height: 100%;
  width: 100%;
  text-align: center;
  align-items: center;
  justify-content: center;
  display: none;
}

.iprodBox:hover>.iprodDesc {
  display: flex !important;
  animation: fade 1s;
}

.iprodBox:hover>.iprodImg img {
  display: none !important;
  animation: fade 1s;
}

.iprodBox:hover>.iprodTitle {
  display: none !important;
  animation: fade 1s;
}

.iprodBox:hover {
  background-color: #184e77;
}

Test Title

Test Title

Test Text


text:
Q: What exactly is VBScript, and what books/online resources could I use to learn it? I have some programming knowledge, I can write console applications in Python, Java, and I can do both console and GUI programs with VB.net. Since I know VB.net, I though I should learn VBScript. I read online that it is a language used on Internet Explorer, but the tech department at my school writes applications in a text editor and saves them as a .vbs and runs them on the computer(no browser needed). I have used this method to make a simple Message Box(MsgBox"message here",4,"title here"). Is this a single language able to be used in both environments, or are these two separate things?

A: I read online that it is a language used on Internet Explorer...
Yes, VBScript can be used as an alternative to JavaScript. But, in practice, nobody uses VBScript for web application development because it works only in Internet Explorer.
...but the tech department at my school writes applications in a text editor and saves them as a .vbs and runs them on the computer(no browser needed).
Yes, and many problems can be solved with VBScript. VBScript is a complete programming language and it can access the COM subsystem in Windows. What I like about VBScript is that it is available on all Windows systems. So, it is wonderful solution when you have restrictions that prohibit you from installing other language interpreters/runtimes such as the Java JRE, Python, Perl, Ruby, etc.
For an example of what you can do with VBScript, see this example which demonstrates reading a key from the Windows Registry.
And check out my post here for a pointer to downloading Microsoft's authoritative VBScript reference as a Windows help file.
All that said, Microsoft has pretty much stopped enhancing VBScript and is putting its energy into PowerShell. PowerShell is very much aimed at System Adminstrators and it is an exceptionally capable language when used for that purpose. However, the last time I looked, PowerShell was weak with respect to creating your own classes. (Or at least it was awkward.) As an application developer, though, when I am solving a problem with VBScript, I typically make use of classes via the Class keyword extensively. A lot of folks don't know this, but you can do object-oriented programming in VBScript, and I do so often.
Check out this example that shows how you can develop your own classes via the Class keyword in VBScript.


text:
Q: Group and Count in Linq issue I am working on a C# project using LINQToSQL,But right now I am having a problem with the following query:
var groupByQuery =  (from c in db.Customers
                            join o in db.Orders on c.CustomerID equals o.CustomerID into lf1
                            from or in lf1.DefaultIfEmpty()
                            group c by c.CustomerID into g
                            select new
                            {
                                CustomerID = g.Key,
                                Count = g.Count()
                            }
                            ).OrderBy(x => x.Count);

As you can see I am doing a LEFT OUTER JOIN and grouping by the CustomerID, and everything goes well so far. But when I see the results I realize that the Customers that does not have any Order, has a "1" in their Count field.
Why is that? The Count field is supposed to have a "0" in these cases, What am I doing wrong?
I found this questions here:
linq-count-query-returns-a-1-instead-of-a-0
linq-to-sql-joining-query-returning-1-instead-of-0
but none of them has been helpful to me, I hope someone can help, thank you in advance.

A: There will still be a record, even if it's null - a set that contains "NULL" is still a row - that's why it's saying there is 1 record. If you give the Count method an argument for what  records to count, it should work better.
Count = g.Count(a => a.SomeNullableField != null)

A: You're making things too complicated.  join...into performs a group join, so the Orders are grouped by CustomerId within your first two lines of code.  This should work:
var groupByQuery =  (from c in db.Customers
                     join o in db.Orders on c.CustomerID equals o.CustomerID into lf1
                     select new
                     {
                         CustomerID = c.Id,
                         Count = lf1.Count()
                     }
                     ).OrderBy(x => x.Count);


text:
Q: Flutter with continous location listen in background android Since the release of Flutter, I'm really curious about it's UI. I have existing android code with MVP + Volley network. Currently, the android location update works even in doze mode and updates it's location correctly in the background.
Is there any way like geocoder of flutter?. It can listen to the fusedlocationapi but not sure about background listening. Please suggest a better way in flutter or should I use the android way to update its location and save it.
Thanks


text:
Q: how to validate on form repeater jquery i have form repeater ,and i need to validate specific field before submit.
here's my code

Amount
<input tclass="form-control split-amount{{ $index }}"
name="split_amount" type="number" id="amount_split">

the form is inside table , so it keep repeated for every row.

i need whenever any field add cannot submit the form before the
addition of all this field is equal some number .

i have tried this
@section('custom_script')

     @endsection

A: here's my answer for this problem

function ind(i){

    $(document).ready(function(){
var el = $(".splite"+i).change(function(){
        var amo = 0;
for(var it = 0;it< el.length;it++){
    amo += parseFloat(el[it].value);
}
console.log(amo);
var am = $("#total"+i);
am = parseFloat(am[0].value);
if(amo == am){
    $("#sub"+i).removeAttr('disabled');
}else{

    $("#sub"+i).attr('disabled',true);
}

$("#split_amount_p"+i).html(amo);
$("#orignal_amount_p"+i).html(am);
if((am - amo) == 0){

$("#difference_amount_p"+i).html(0).css('color','green');
}else{
$("#difference_amount_p"+i).html(am - amo).css('color','red');

}
// console.log(am);
    });
});
}
 function addButton(index){
   ind(index);
 }
  function removeButton(index)
  {
     setTimeout(function(){

   ind(index);
   },500);
 }

</script>


text:
Q: Why does my light text have a strong anti-alias I am having some display weirdness with @font-face fonts.
If the font is coloured white or a light colour like yellow, it appears to have strong anti-alias applied to it, something I don't appear to be able to control, is it just my eyes?
font declaration
Full @font-face
@font-face {
    font-family: 'Lobster1.4';
    font-weight: normal;
    font-style: normal;
    src: url('fonts/Lobster-1.4/Lobster-1.4.eot') format('eot');
    src: url('fonts/Lobster-1.4/Lobster-1.4.eot?#ieFix') format('eot'),
         url('fonts/Lobster-1.4/Lobster-1.4.svg#Lobster1.4') format('svg'),
         url('fonts/Lobster-1.4/Lobster-1.4.woff') format('woff'),
         url('fonts/Lobster-1.4/Lobster-1.4.ttf') format('truetype');
}

use:
.zone-text span {
    font-family: 'Lobster1.4';
    font-weight: normal;
    font-size: 1.3rem;
    color: #3C3C3B;
}

looks like:

with everything else same, just switching color to white it completely changes the font like it's a different typeface
like this:

Any idea why this could be or is it something I just have to live with.
//edit
with larger text (3rem) it's definitely still happening but I think it's more apparent as smaller sizes.

A: It's because of the red background:
All A lot of colors on red background:
http://bcn.boulder.co.us/community/tools/colors/sccscred.htm
And here you can have grades for you contrast:
http://snook.ca/technical/colour_contrast/colour.html
You will notice Contrast Ratio is under 4.5 and Colour Difference is below 500.
Also Brightness Difference barely crosses 125 at 145.
Where black on white is:

Contrast Ratio: 21 Colour Difference: 765 Brightness Difference: 255