Change mouse over with HTML source

Question: On a SharePoint page I have this:

I want the mouse to change when the mouse goes over "Ulm", "Oberkochen" etc.
When I edit the webpart and click on Edit Source, the following shows up:

         Ulm

         Oberkochen

         Taufkirchen

         Wetzlar

         Friedrichshafen

         Kiel

         Köln

To register yourself to a seminar please click on this icon
   . To register someone else to a seminar, please click on this icon
   .

I wasn't able to find anything on the Internet, but does someone know what I have to write in the source to get the mouse to change whenever the mouse hovers over "Ulm" etc.?
Comment: @EGC Sorry, you're totally right. It works! Thanks a lot man
Comment: Add `.dd13:hover {
 cursor: pointer;
}` to the `
Comment: Your question was regarding changing the mouse. If you're having issues navigating to the page, there is something incorrect in the `onClick` function and the url being passed
Answer: Use this css code for changing mouse hover effect
According to your code you can write in style in two conditions.
table class="dd13" & td class="dd13" both are same.

[Link Different Cursors] : https://www.w3schools.com/cssref/pr_class_cursor.asp

Change mouse over with HTML source


Internals of a Linux system call

Question: What happens (in detail) when a thread makes a system call by raising interrupt 80? What work does Linux do to the thread's stack and other state? What changes are done to the processor to put it into kernel mode? After running the interrupt handler, how is control restored back to the calling process?
What if the system call can't be completed quickly: e.g. a read from disk. How does the interrupt handler relinquish control so that the processor can do other stuff while data is being loaded and how does it then obtain control again?
Comment: There are also a couple of other ways to make system calls these days. You can make a regular function call into a specially mapped memory page. You can use the SYSENTER or SYSCALL instructions.
Comment: I guess a good exercise would be to check out the source. Maybe start at kernel 0.0.1 and move upwards.
Answer: A crash course in kernel mode in one stack overflow answer
Good questions! (Interview questions?)

What happens (in detail) when a
thread makes a system call by raising
interrupt 80?

The int $80 operation is vaguely like a function call. The CPU "takes a trap" and restarts at a known address in kernel mode, typically with a different MMU mode as well. The kernel will save many of the registers, though it doesn't have to save the registers that a program would not expect an ordinary function call to save.

What work does Linux do to the
thread's stack and other state?

Typically an OS will save registers that the ABI promises not to change during procedure calls. The stack will stay the same; the kernel will run on a per-thread kernel stack rather than the per-thread user stack. Naturally some state will change, otherwise there would be no reason to do the system call.

What changes are done to the
processor to put it into kernel mode?

This is usually entirely automatic. The CPU has, generically, a software-interrupt instruction that is a bit like a functional-call operation. It will cause the switch to kernel mode under controlled conditions. Typically, the CPU will change some sort of PSW protection bit, save the old PSW and PC, start at a well-known trap vector address, and may also switch to a different memory management protection and mapping arrangement.

After running the interrupt handler,
how is control restored back to the
calling process?

There will be some sort of "return from interrupt" or "return from trap" instruction, typically, that will act a bit like a complicated function-return instruction. Some RISC processors did very little automatically and required specific code to do the return and some CISC processors like x86 have (never-really-used) instructions that would execute dozens of operations documented in pages of architecture-manual pseudo-code for capability adjustments.

What if the system call can't be
completed quickly: e.g. a read from
disk. How does the interrupt handler
relinquish control so that the
processor can do other stuff while
data is being loaded and how does it
then obtain control again?

The kernel itself is threaded much like a threaded user program is. It just switches stacks (threads) and works on someone else's process for a while.
Comment: +1 - These are the kinds of answers that make SO ... well ... SO :)
Comment: Good answer. Not interview questions - I'm just interested!

On the last point, does the system call give up execution voluntarily or does it get interrupted by some hardware timer interrupt? Thanks.
Comment: The kernel will generally work steadily on the system call but if it requires I/O ops then these will probably be interrupt-driven. So, the kernel will start the I/O op, and then switch to another process (very much like thread switching, as noted) until the interrupt comes in. The kernel will note that the system-calling PID is runnable again. It will put it on a run queue and then next time the  scheduler decides it's time for someone new to run, it will come off the queue. Often, it's the only runnable process there anyway.
Answer: To answer the last part of the question - what does the kernel do if the system call needs to sleep -
After a system call, the kernel is still logically running in the context of the same task that made the system call - it's just in kernel mode rather than user mode - it is NOT a separate thread and most system calls do not invoke logic from another task/thread. What happens is that the system call calls wait_event, or wait_event_timeout or some other wait function, which adds the task to a list of tasks waiting for something, then puts the task to sleep, which changes its state, and calls schedule() to relinquish the current CPU.
After this the task cannot be run again until it gets woken up, typically by another task (kernel task, etc) or interrupt handler calling a wake* function which will wake up the task(s) sleeping waiting for that particular event, which means the scheduler will soon schedule them again.
It's worth noting that userspace tasks (i.e. threads) are only one type of task and there are a few others internal to the kernel which can do work as well - these are kernel threads and bottom half handlers / tasklets / task queues etc. Work which doesn't belong to any particular userspace process (for example network handling e.g. responding to pings) gets done in these. These tasks are allowed to go to sleep, unlike interrupts (which should not invoke the scheduler)
Answer: http://tldp.org/LDP/khg/HyperNews/get/syscall/syscall86.html
Comment: this is x86-specific answer thus too limited to be considered general.
Answer: This should help people who seek for answers to what happens when the syscall instruction is executed which transfers the control to the kernel (user mode to kernel mode). This is based upon x86_64 architecture.
https://0xax.gitbooks.io/linux-insides/content/SysCall/syscall-2.html

Internals of a Linux system call


Vector valued functions

Question: What is a vector valued function ? Vectors are just $n-tuples$ , and then how are we able to describe geometrical shapes using them ?
Is a vector function such that it outputs $n-tuples$ using other $n-$tuples and complex numbers and then you get geometrical shapes according to how you interpret these $n-tuples$ , for example ,input vectors are shifts and final output vectors and position vectors . This is only pure interpretation , if you interchanged this interpretation you won't be getting the same shape as before and in the end , it is just $n-tuples$ we are getting , and then shape is how we interpret them and nothing else ?
And if it is true , why don't books mention this ? That shapes are determined according to how we are interpreting certain $n-tuples$ in our space and we have these specific interpretations defined for this geometric space, like from now on we will interpret input vectors are shifts and final output vectors and position vectors/points and this set of points will be our plane but vectors have no role in this , it is just our interpretation in this particular case .
Answer: A vector-valued function is one where the result is a vector.  In the finite-dimensional case, this is an $n$-tuple.  The domain might be vectors of the same size, or of a different size, or a scalar.  In the first case, one can interpret the function as a vector field.  In the last case, one can interpret the function as a curve in space.  All of these have geometric interpretations and are well-studied.
Comment: Yes , but somehow books don't mention when to take a vector as point or a shift in plane in a particular direction . And if we don't specify that the whole interpretation changes . Like take the case of vector equation of a line .
Comment: isn't this fact kind of pre-assumed in describing shapes using vectors ?
Comment: I don't agree that a vector in a finite dimensional space is necessarily an $n$-tuple (nor does the base field have to be the real numbers). This is a false impression that is somehow spread through the educational system.
Comment: It can always be made into an $n$-tuple via the basis representation theorem, so we may assume this without loss.

Vector valued functions


is there such thing a Bittorent passive tracking?

Question: Hi I want to make an application that if given a torrent file (or hash) can give the number of peers without being active (i.e not responsible) in the process that allow the sharing of a file (for legal reason obviously). whether by being a "passive" (passive as define previously) tracker or a bittorrent client that counts "All time" peers (i.e. number of download for a torrent). Can it be done? I know some trackers keep track of download but I don't know if those who "seem not to" actually do as well. I look for something that can track the number of unique-ip transfers from when the torrent was added to the tracking system or something that count download (complete).
Answer: It's not possible to determine all peers just from a tracker. There can be multiple trackers for each torrent, and they may not store complete, fresh, or even truthful information. Additionally there's no obligation for peers to be honest with their trackers. There are also alternatives to centralized trackers, such as DHT and PEX. There's no guarantee that all peers are participating in the same DHT network. Peers might even establish disjoint PEX communities.
In short, you might make a best effort attempt at determining the total swarm participation for a particular torrent by checking trackers and querying DHT. But to be as thorough as the technology will allow, you'd actually have to participate in the swarm with all manner of transports and protocol extensions currently in use such as uTP and encryption, and scrape each peer for further peers and download states. Of course the BitTorrent community is familiar with such attempts to scrape data, and there a lot of security measures in place to prevent exploitation in this way. Examples include IP blocklists, and heuristics on peer behaviour.


The equation of a plane perpendicular to another plane

Question: Suppose that I want to find the equation of the plane that is perpendicular to the plane $8x-2y+6z=1$ and passes through the points $P_1(-1,2,5)$ and $P_2(2,1,4)$.
I can think of two methods to find the normal vector to the plane.
Method 1: Since the plane is orthogonal to $8x-2y+6z=1$, then the normal vector of the plane should be orthogonal to $(8,-2,6)$. So one normal vector would be $(1,1,-1)$.
Method 2: Find the cross product of $(8,-2,6)$ and $\mathbf{P}_1\mathbf{P_2}$.
I think there is something wrong with method 1 but I can not spot it.
Could you please clarify this for me?
Comment: In method 1, you find the normal of the vector and then you need to find $d$.You need only one point to do that (i.e $P1$ or $P2$), so if they gave you two points, then there is probably something wrong there. (Usually, there is no useless or unused data in math questions...)
Comment: @Eminem there are an infinite number of planes through one point which are perpendicular to a given plane (rotate about the point with axis normal to the plane).
Comment: Method 1 gives you the direction of a line in your original plane. There is no reason why this direction should be orthogonal to the plane you require. Method 2 will work though as you now have 2 directions in the plane you have to find.
Comment: @Paul But if you have the normal of the plane, you have to find $d$ to complete the task. So here, if the normal is $(1,1,-1)$ than the equation is $x+y-z+d=0$. Then you put $P1$ or $P2$ there to find $d$, and that is it, right?
Comment: @Eminem (1, 1, -1) is just one direction in the original plane. It is a normal to some plane alright, but there is no reason to suppose that it is normal to the plane through $P_1$ and $P_2$. Infact, it can't be, as those two points give different values for d.
Answer: The method (2) is correct since the normal vector to the searched plane have to be orthogonal to the vector $P_1-P_2= (-3,1,1)$ and to the normal vector to the given plane $ (8,-2,6)$.
For the method (1) note that an orthogonal vector to $ (8,-2,6)$ has components such that: $(8,-2,6)(x,y,z)^T=0$ so you can fix only one component from this equation and the other two can be fixed imposing that the plane pass through the two given points.


ScrollPane doesnt "know" when to expand

Question: I'm not sure how to call this problem but you will definitely understand what I mean...
at least I hope you will.
To start with: I have my Pane with a ScrollPane in it. This Pane also contains two Buttons on which I can create rectangles in my ScrollPane.
I can drag those Rectangles around and they can be moved out of view. This far everything works as it should be except the ScrollPane. Usually you had the ScrollPane expand his Scroll so you can, if you let go of the Rectangle, scroll to that Rectangle and grab it again but nice and friendly JavaFX doesnt know how to expand the Scroll so I cant get to this Rectangle again.
Or I just miss some important part (which is the more likely thing to happen)
Some words to my Code: I don't think that its a problem in my existing code but more a problem that needs a workaround. The only things that I changed for the ScrollPane are that I set the ScrollBarPolicy to always and set the ScrollPane Pannable but this is consumed when I click on a Rectangle so I can move them and don't pan the ScrollPane.

What you see above is one Rectangle in its full size and one which is partly out of the ScrollPane boundaries but the ScrollPane doesn't expand the ScrollBar.
Doesn't matter how far I move that Rectangle away from those boundaries the Scrollbar won't change which is bad for this is the only reason I chose a ScrollPane and also, I think, the only (easiest) pane to achieve this "editor like" view.
Yea so thank you for at least reading this far and like always sorry for my broken English ^^. I hope you can give me a advice on how to fix this problem!
EDIT:
Here a minimal example:
Controller.java
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;

import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.ScrollPane.ScrollBarPolicy;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Rectangle;

public class Controller implements Initializable{
    @FXML ScrollPane actionWin;
    Rectangle r;
    Double orgTranslateX, orgTranslateY, orgSceneX, orgSceneY, newTranslateX, newTranslateY, offsetY, offsetX;
    int i = 50;
    List<Rectangle> recs = new ArrayList<Rectangle>();

@Override
public void initialize(URL arg0, ResourceBundle arg1) {
    actionWin.setPannable(true);
    actionWin.setHbarPolicy(ScrollBarPolicy.ALWAYS);
    actionWin.setVbarPolicy(ScrollBarPolicy.ALWAYS);
}

@FXML
public void createEntity(){

       Pane container = new Pane();

        // Button 1
        r = new Rectangle();
        r.addEventHandler(MouseEvent.ANY, event -> {
            if(event.getButton() != MouseButton.MIDDLE) event.consume();
        });

        r.setOnMousePressed(onMousePressedEventHandler);
        r.setOnMouseDragged(onMouseDraggedEventHandler);
        r.setX(i);
        r.setY(i);
        r.setWidth(50);
        r.setHeight(20);
        i+=30;
        recs.add(r);

        for(Rectangle rec : recs){
            container.getChildren().add(rec);
        }

        actionWin.setContent(container);
        try {
            AnchorPane root = (AnchorPane) FXMLLoader.load(getClass().getResource("Main.fxml"));
        } catch (IOException e) {
            e.printStackTrace();
        }
}

EventHandler<MouseEvent> onMousePressedEventHandler = new EventHandler<MouseEvent>() {
    @Override
    public void handle(MouseEvent arg0) {
        orgSceneX = arg0.getSceneX();
        orgSceneY = arg0.getSceneY();
        orgTranslateX = ((Rectangle) (arg0.getSource())).getTranslateX();
        orgTranslateY = ((Rectangle) (arg0.getSource())).getTranslateY();
    }};

EventHandler<MouseEvent> onMouseDraggedEventHandler = new EventHandler<MouseEvent>() {
    @Override
    public void handle(MouseEvent arg0) {
        offsetX = arg0.getSceneX() - orgSceneX;
        offsetY = arg0.getSceneY() - orgSceneY;
        newTranslateX = orgTranslateX + offsetX;
        newTranslateY = orgTranslateY + offsetY;
        ((Rectangle)(arg0.getSource())).setTranslateX(newTranslateX);
        ((Rectangle)(arg0.getSource())).setTranslateY(newTranslateY);
    }};
}

Main.fxml
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.ScrollPane?>
<?import javafx.scene.control.Separator?>
<?import javafx.scene.control.Spinner?>
<?import javafx.scene.layout.AnchorPane?>

<AnchorPane fx:id="root" maxHeight="720.0" maxWidth="1280.0" minHeight="720.0" minWidth="1280.0" prefHeight="720.0" prefWidth="1280.0" xmlns="http://javafx.com/javafx/8.0.141" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.Controller">
   <children>
      <Button fx:id="createEntity_B" layoutX="14.0" layoutY="14.0" mnemonicParsing="false" onAction="#createEntity" text="Create Entity" />
      <ScrollPane fx:id="actionWin" layoutX="14.0" layoutY="39.0" prefHeight="672.0" prefWidth="996.0" />
   </children>
</AnchorPane>

Main.java
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;

public class Main extends Application {
    public void start(Stage primaryStage) {
        try {
            AnchorPane root = (AnchorPane)
            FXMLLoader.load(getClass().getResource("Main.fxml"));
            Scene scene = new Scene(root);
            primaryStage.setScene(scene);
            primaryStage.setResizable(false);
            primaryStage.show();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

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

Wrap these three classes in a package called "application" and you're good to go.
Comment: *"I don't think that its a problem in my existing code but more a problem that needs a workaround."* I do think you're wrong. Post a [mcve].
Comment: Example added to question
Answer: You're using translateX and translateY to determine the new position of the Rectangles.
Transforms like the translate properties are not taken into account when the parent determines it's size. The child is treated as if it was located at (layoutX, layoutY). You need to modify those properties, if you want the Pane to be resized properly.
Some other things in the createEntity seem odd though:

You recreate the Pane instead of creating it once in the fxml.
You load a fxml that never seems to be used.

Also you should prefer the primitive type double to the reference type Double unless you're not doing any arithmetic operations or comparisons.

<AnchorPane fx:id="root" maxHeight="720.0" maxWidth="1280.0" minHeight="720.0" minWidth="1280.0" prefHeight="720.0" prefWidth="1280.0" xmlns="http://javafx.com/javafx/8.0.141" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.Controller">
   <children>
      <Button fx:id="createEntity_B" layoutX="14.0" layoutY="14.0" mnemonicParsing="false" onAction="#createEntity" text="Create Entity" />
      <ScrollPane fx:id="actionWin" layoutX="14.0" layoutY="39.0" prefHeight="672.0" prefWidth="996.0">
          <content>
              <Pane fx:id="container"/>
          </content>
      </ScrollPane>
   </children>
</AnchorPane>

@FXML
private Pane container;

@FXML
public void createEntity() {
    class DraggedHandler implements EventHandler<MouseEvent> {

        double offsetX;
        double offsetY;

        @Override
        public void handle(MouseEvent event) {
            Node source = (Node) event.getSource();
            Point2D pt = source.localToParent(event.getX(), event.getY());
            source.setLayoutX(pt.getX() + offsetX);
            source.setLayoutY(pt.getY() + offsetY);
        }

    }

    Rectangle rect = new Rectangle(i, i, 50, 20);
    i += 30;
    container.getChildren().add(rect);

    rect.addEventHandler(MouseEvent.ANY, event -> {
        if (event.getButton() != MouseButton.MIDDLE) {
            event.consume();
        }
    });

    DraggedHandler handler = new DraggedHandler();
    rect.setOnMouseDragged(handler);
    rect.setOnMousePressed(evt -> {
        Node source = (Node) evt.getSource();
        Point2D pt = source.localToParent(evt.getX(), evt.getY());
        handler.offsetX = source.getLayoutX() - pt.getX();
        handler.offsetY = source.getLayoutY() - pt.getY();
    });
}

Comment: Thanks a lot! The fxml i never used was for refreshing the whole GUI. Dont know why i needed it but this works without.

ScrollPane doesnt "know" when to expand


How to retrieve a cookie's expiry date with javascript

Question:
Possible Duplicate:
How to get cookie expiration date / creation date from javascript?

I haven't been able to find a solid answer to this issue. I have a cookie set to expire in 15 days after a user signs in. I would like to let the user know how many days are left each time they re-visit the page.
How is this possible?
Answer: If you can't retrieve it via server-side first, then you have to resort to using client-side tricks because you can't access this directly on the client-side. The trick is by using localStorage to store the cookie meta information, you an achieve this. For example, when setting the cookie, do the following:
<code>document.cookie = 'mycookie=blah;expires=[expiredate];';
localStorage['mycookie'] = JSON.stringify({
   expires : '[expiredate]',
   otherdata: whatever
});
</code>
You can then check its meta data as you like. If the cookie does not exist, meaning its not in document.cookie , you should erase the localStorage for that cookie in your script.
The best way to do this is via server-side and output this as some var to the page if you must but for sure, don't store more information about the cookie in other cookies as this will only bloat the request unnecessarily.
Comment: How would you even detect is server side first?


Almost nondecreasing sequence

Question: Let $\{a_n\}$ be a real sequence. Suppose
$$\forall j~\exists n_j:n>n_j\Rightarrow a_n-a_{n+1}<\dfrac1{2^j}$$
I wonder if there has to be a $\max_{j}\{n_{j+1}-n_j\}$ or the gaps can go to infinity.
Answer: $\frac12,\frac14,\frac14,\frac18,\frac18,\frac18,\frac1{16},\frac1{16},\frac1{16},\frac1{16},\frac1{32},\dots$, so $\frac1{2^n}$ occurs $n$ times.
The "gaps" will clearly get bigger and bigger.
Comment: That's exactly what I wanted!

Almost nondecreasing sequence


Testing for difference in means between two groups for which each measurement has a unique associated uncertainty

Question: I am wondering what type of statistical test would be appropriate to test for a difference in means between two groups for which each measurement has a different uncertainty. For example, I want to see if there is a significant difference in height when comparing men and women, but each person was measured using a different type of ruler (let's say one ruler only measures up to a precision of 1 cm, another to 1 mm, etc). So, I would have a set of measurements like:
m = [170 cm, 150 cm, 200 cm]
w = [150 cm, 120 cm, 170 cm]
u_m = [1 cm, 0.5 cm, 0.1 cm]
u_w = [0.1 cm, 0.25 cm, 1 cm]
where order is preserved (i.e., u_m[1] is the uncertainty of m[1]).
What type of test could tell me if there is a significant difference in means (outputting a significance value) with the associated uncertainties taken into account?
Answer: If it's precision in the sense of "could be any value between a and b" (and the ends of the intervals aren't necessarily less likely than the middle) with a and b different for each observation, then over could treat this as interval censored data. If you'd like to treat this as measurements e.g. with a normally distributed error that's sometimes wider or narrower, then a normal likelihood with known for SD works. There's specialized software for all of these (e.g. survival analysis tools for the first, meta regression for the second). Alternatively, the brms R package covers both. Within these you uses a regression with suitable terms such as group (plus the assignment mechanism to group, e.g. randomisation strata or propensity scores).
Thereafter, you just use a likelihood ratio test or the like based on the likelihood, or in a Bayesian setting look at the posterior for the group coefficient.


Unable to get variables from different files

Question: Im trying to get data from my database and echo it with a variable, but I have a problem with that. When I try to get my variables from different files it shows me this error:

Undefined variable: con in.

Here some codes:
Code from functions.php:
include "authentication.php";

function GetData() {
$id = session_id();
$result3 = mysqli_query($con,"SELECT * FROM accounts where id='$id'");
while($row3 = mysqli_fetch_array($result3));
{
$email=$row3['email'];
$fullname=$row3['fullname'];
$usualname=$row3['usualname'];
$lastname=$row3['lastname'];
}
}

Code from authentication.php:
$DATABASE_HOST = 'localhost';
$DATABASE_USER = '***';
$DATABASE_PASS = '***';
$DATABASE_NAME = '***';

$con = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASS, $DATABASE_NAME);
if ( mysqli_connect_errno() ) {

    die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}

This also happens when I try to get variables from other files..
Here you get some screenshots of the error from different files and different variables:

Both files are in the same directory called PHPscripts:
Comment: Where is the location of `authentication.php`? Is that file  included properly?
Comment: @Talk2Nit It's in the same folder as function.php
Comment: Possible duplicate of [Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?](https://stackoverflow.com/questions/16959576/reference-what-is-variable-scope-which-variables-are-accessible-from-where-and)
Answer: This looks like a problem of scoping.
Remember that in PHP, variables in the global scope cannot be accessed from a function. You must explicitly do something like global $con; inside the function GetData() before you try to access $con.
From a system design point of view this isn't the best approach. It will make it hard to keep track of your variables. You won't know who (which part of your script) is accessing that global and you won't know how it is being modified or in what order. This can lead to some bugs that are very difficult to identify.
Answer: require_once dirname(__FILE__) . auth.php;

Require_once or require with Unix full path works like a charm. Replace include stroke in your code.


Initialize a struct inside a union (C++)

Question: I'm creating a very limited, domain-specific x86 assembler in C++ (Visual Studio 2010) that dynamically generates instructions, writes it to memory, and executes it, all at runtime. First I write them to a temporary byte stream, and then write the entire stream to executable memory in one memcpy.
I use the following code for constructing a movsd [imm32], xmm1 instruction:
typedef unsigned char byte;
enum SSE2Register;

void WriteValueToMemory(double* dest, SSE2Register source)
{
    union
    {
        struct
        {
            byte insts[4];
            double* dest;
        };

        byte bytes[8];
    } movsd =
    {
        // movsd [imm32], xmm1
        0xF2, 0x0F, 0x11, // Opcode
        0x05 + (8 * source), // ModR/M
        dest // imm32
    };

    _stream.Write(movsd.bytes, sizeof(movsd.bytes));
}

This code works: the three opcode bytes and the ModR/M byte are written to insts, the destination (imm32) is written to dest, and bytes contains the entire instruction in raw bytes, ready to be written to the instruction stream.
However, I am curious as to whether this method of initializing the union is safe/portable. Is it OK to initialize the four values of insts and the value of dest within a single set of braces?
In other words, is this the correct, portable way of doing this, or should I do it a different way?
Thanks!
Comment: That isn't the correct, portable way, but it's very very close.
Comment: BTW: If you want to be consistent with intels manuals and most online resources I'd call probably call it either `movsd m64, xmm` or `s/imm32/disp32`.
Answer: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx

Anonymous Structures
A Microsoft C extension allows you to declare a structure variable
  within another structure without giving it a name. These nested
  structures are called anonymous structures. C++ does not allow
  anonymous structures.
You can access the members of an anonymous structure as if they were
  members in the containing structure.

However, you don't need a union for what you're doing.
void WriteValueToMemory(double* dest, SSE2Register source)
{
    struct
    {
        byte insts[4];
        double* dest;
    } movsd =
    {  // movsd [imm32], xmm1
        0xF2, 0x0F, 0x11, // Opcode
        0x05 + (8 * source), // ModR/M
        dest // imm32
    };

    _stream.Write(&movsd, sizeof(movsd));
}

Comment: I like that! The only thing I had to change was the `_stream.Write()` call: I had to cast `&movsd` to `byte*`, since the signature of `Write` is `(byte arr[], int arrSize)`, but it works, and it's portable. Thanks!
Comment: Remember, a anonymous struct is _not_ portable.  If you still have the union, you'll have to name the struct.
Comment: Wouldn't your way of doing it in a single `struct` be C++ compliant, since it is declared as `movsd`? Or would I actually have to declare it as a namespace-wide type to use it in other compilers?
Comment: Yes, my code is portable, since it has a name.  The rule is: "You can't have an unnamed structure inside of another structure/union."


Is there a name for arranging a triple-meter piece into quadruple meter?

Question: Is there a technical name for when a piece originally in triple meter is arranged into quadruple meter? (Usually this is done by doubling the first a beat.)
For example, the quadruple-meter arrangement in Biden's inauguration ...
X: 1
T: The Star-Spangled Banner: Biden Inauguration
M: 4/4
L: 1/4
K: Gb
d/B/ | G2 B d | g3 b/>a/ | g2 B =c | d3 ||

... of the triple-meter "Star-Spangled Banner":
X: 2
T: The Star-Spangled Banner: Triple Meter
M: 3/4
L: 1/4
K: Gb
d/B/ | G B d | g2 b/>a/ | g B =c | d2 ||

I've heard similar treatments of "Silent Night" and "Away in a Manger" in shopping mall background music.
Comment: Usually doubling *a* beat - often not the first.
Comment: Answer - no specified term.
Comment: Was it really in G flat?
Comment: @phoog Yep, at least it wasn't In F# :0
Comment: @JohnBelzaguy - someone told me it was in Lydian - due to that #4...
Comment: @Tim how did they explain the slew of natural 4's in the middle and last 8? :)
Comment: They couldn't. It was just the #4 (we know it's modulated), but they hadn't read that far...
Answer: I've encountered the term metric expansion in at least two sources: a dissertation on Dream Theater by McCandless, and a rather famous book by Jason Yust called Organized Time.
In both instances, the idea is of starting with some particular metrical prototype and expanding at least one section of it. Here, it's the first beat of each measure that's being expanded, thus moving the piece from 3/4 into 4/4.
I can't say it's a term thrown around everyday, but the dissertation is not well known and Yust's book is relatively new (2018). Perhaps with time more musicians will use it.


Can properly written code using mutex be still volatile?

Question: I've been doing pretty basic stuff with std::thread without any particular reason, simply in order to learn it. I thought that the simple example I created, where few threads are operating on the same data, locking each other before doing so, worked just fine, until I realized that every time I run it the returned value is different, while very close to each other, I am pretty sure they should equal each other. Some of the values I have received:

21.692524
21.699258
21.678871
21.705947
21.685744

Am I doing something wrong or maybe there is underlying reason for that behaviour?
<code>#include <string>
#include <iostream>
#include <thread>
#include <math.h>
#include <time.h>
#include <windows.h>
#include <mutex>

using namespace std;

mutex mtx;
mutex mtx2;

int currentValue = 1;
double suma = 0;

int assignPart() {
    mtx.lock();
    int localValue = currentValue;
    currentValue+=10000000;
    mtx.unlock();
    return localValue;
}

void calculatePart()
{
    int value;
    double sumaLokalna = 0;
    while(currentValue<1500000000){
        value = assignPart();
        for(double i=value;i<(value+10000000);i++){
            sumaLokalna = sumaLokalna + (1/(i));
        }
        mtx2.lock();
        suma+=sumaLokalna;
        mtx2.unlock();
        sumaLokalna = 0;
    }
}

int main()
{
    clock_t startTime = clock();
    // Constructs the new thread and runs it. Does not block execution.
    thread watek(calculatePart);
    thread watek2(calculatePart);
    thread watek3(calculatePart);
    thread watek4(calculatePart);

    while(currentValue<1500000000){
        Sleep(100);
        printf("%-12d %-12lf \n",currentValue, suma);
    }
    watek.join();
    watek2.join();
    watek3.join();
    watek4.join();
    cout << double( clock() - startTime ) / (double)CLOCKS_PER_SEC<< " seconds." << endl;
    //Makes the main thread wait for the new thread to finish execution, therefore blocks its own execution.
}
</code>
Comment: `while(currentValue<1500000000)` is unprotected, in *both* cases it is used. You also don't need a mutex for this, you should be able to structure this with an `std::atomic_int`. Either that or I'm totally not seeing what this is trying to do.
Comment: As far as I can tell, it's fine.  Your output appears to be the time it takes to execute, which is unlikely to be the same every time, since you are spawning several threads that have to interact via the mutex.
Comment: By "the returned value", do you mean the final value of `suma`? Your code isn't printing that; it prints various intermediate values (which could be anything, and give undefined behaviour since you read it without locking the mutex), and the overall time taken (which will vary from run to run). Perhaps you could update the code to print exactly what you're asking about.
Comment: Isn't it still wrong as we are reading currentValue: `while(currentValue<1500000000)` and entering into loop (which will change value of `currentValue`) without locking `mtx`?
Comment: The values that you show, are those values for `currentValue`? If so, should you not printf currentValue _after_ joining the threads?
Comment: Where does your output come from? The only two outputs - `printf` and `cout` do not match what you had shown. Is it something done at the end but is not pasted it?
Comment: The output I mention is the value of suma when currentValue reaches 1500000001.
Comment: @KrisVandermotten is correct, when I changed the code so that it prints the value after joining the threads, it works just fine. Thank You!
Comment: WhozCraig, only thing I am trying to do is to discover the possibilities I have, I am aware that atomic_int would do just fine in this situation.
Comment: You should be using `std::lock_guard`, **not** calling `mtx.lock()` and `mtx.unlock()`. That's how C++11 mutexes are intended to be used, not via manual locking. Use the tools provided. There is a race condition on `currentValue`, the `main` thread must lock the mutex to read `currentValue`, or you could make it a `std::atomic`. `Sleep` is not portable, you can use `std::this_thread::sleep_for()` instead.
Answer: Your loop
<code>while(currentValue<1500000000){
    Sleep(100);
    printf("%-12d %-12lf \n",currentValue, suma);
}
</code>
is printing intermediate results, but you're not printing the final result.
To print the final result, add the line
<code>    printf("%-12d %-12lf \n",currentValue, suma);
</code>
after joining the threads.


Firebase Múltiplas Cláusulas

Question: Estou querendo fazer uma consulta com múltiplas cláusulas where, com o banco de dados Firestore, porém me retorna um erro, fiz uma pesquisa rápida eu vi que o Firestore só deixa fazer uma única cláusula where em uma coleção; eu tentei fazer uma consulta separada e depois junta-las, mas sem sucesso. Ele acaba por retornar os dados duplicados.
No exemplo abaixo eu tenho uma loja, e nessa loja eu tenho alguns produtos, o usuário pode fazer uma filtragem pelo "nome do produto" e também pelo "preço do produto"
O erro que eu obtenho quando tento fazer esta operação é esta exception:
All where filters with an inequality (<, <=, >, or >=) must be on the same field. But you have inequality filters on 'FieldPath([name_product])' and 'FieldPath([price])'.

Quando tento utilizar um método como este:
db.collection('store')
  .where('name_product', isGreaterThanOrEqualTo: 'name_product')
  .where('name_product', isLessThanOrEqualTo: 'name_product' + "\uf8ff")
  .where('price', isGreaterThan: '10000')
  .snapshots();

O exemplo a acima foi escrito em linguagem Dart.
Answer: Você não pode passar múltiplas condições para o where(). Mas você pode chamar o where quantas vezes for preciso.
veja este exemplo (em inglês)
Comment: Por favor, adicione mais detalhes para expandir sua resposta, como um código que funcione ou citações de documentação.

Firebase Múltiplas Cláusulas


IIS Manager - Connect to Another Server (Win7 to Win2008 server)

Question: I am running Windows 7 Ultimate.  If I open up IIS Manager, I see a list of "connections" on the left hand side.  In previous versions, I would be able to select an option to "connect to another server" or "connect to another machine", but there is no such option visible anywhere here.  The only thing in the list is my local machine.
Even in the address bar, if I manually type in the server location (\servername, even tried just servername), nothing happens (it just reverts back to my current local computer)
The documentation at http://technet.microsoft.com/en-us/library/cc732466%28WS.10%29.aspx seems to imply the very same steps... but there is just no button or menu option anywhere to do this.  Am I missing something?  I'm not even seeing a grayed out menu option.
EDIT: Under the "File" menu, I see 2 options:

Save Connections (grayed out)
Exit

Under the "Connections" pane, I see 1 button, grayed out.  When I hover the mouse, it simply says "Up", appears to be usable if I browse into an element in my local computers IIS settings
If I right click inside the pane itself, I see

Refresh
Add website (to the current host)
Start
Stop
Rename
Switch to Content View

UPDATE: I downloaded and installed the Remote Server Administration tools from http://www.microsoft.com/downloads/details.aspx?FamilyID=7D2F6AD7-656B-4313-A005-4E344E43997D&displaylang=en, and I enabled everything listed under "Remote Server Administration Tools" under "Turn Windows Features On or Off".  Still nothing.
Comment: Course, now I get access denied errors (401) when trying to connect, even though I have "enabled remote connections" with "windows credentials only"... but I suppose that's another issue
Comment: @Matt - I have the same problem. I've taken the liberty to add pics; hope that's OK. Win 7 Enterprise, 32-bit, UAC turned off.
Comment: @pcampbell Thanks!! I actually tried doing screen shots, but alt-printscreen would result in the menus going away before the screen shot, and I didn't have any software handy to do the trick.
Comment: @pcampbell Check my answer below ... found the problem
Answer: Turns out I needed to install "IIS Manager for Remote Administration", which is discussed (and available for download) at http://www.iis.net/expand/IISManager.  Why this is not part of the Windows 7 "Remote Administration Tools" I'm not sure.  But after installing this I get the additional "connect" options.
Comment: I didn't see your answer before I posted mine. Good for you that you found the solution.
Comment: I already have IIS Manager for Remote Administration installed, yet I am experiencing this same problem when, just days ago, I was not. I did however, attempt to reinstall IIS for RA _again_ but now it's telling me that it isn't compatible with my system (I can't remember the exact message, but whatevs)
Comment: The link in the answer no longer works. I found this link through google https://www.microsoft.com/en-us/download/details.aspx?id=41177 After installing that and restarting my computer I get the "Connect to a Server..." option.
Answer: In Windows 8 (or Windows 7), you can use the Web Platform Installer to install the IIS Manager for Remote Administration. It's under 2MB.

The latest version should be available.
Answer: 01/01/2018: Was unable to install IIS Manager for Remote Administration v1.2 via the Web Platform Installer (Web PI). Web PI consistently failed suggesting the file it downloaded may have been tampered with.
Instead I had to wade through this site to download and install it:
https://www.microsoft.com/en-us/download/details.aspx?id=41177
Comment: Have this problem except the link you provided it is also now returning a 404. So there is currently no source that I can find to download this damn file!
Answer: In the IIS Manager, try going to File->Connect to a Server.  You're saying that's not there?
Comment: That is correct.  Under File I see 2 options, 1) A grayed out "save connections", and exit.
Answer: Have you tried running IIS Manager as Administrator?  You need to be at an administrator to remotely connect to a server via IIS Manager.
Comment: As soon as you said that, I thought "that *must* be the problem".  Alas, no luck.  Interestingly, when I click "run as administrator", it doesn't prompt me, like other programs when I try to run as admin.  I thought it must've been kicking off from something resident in memory from previous launches, so I rebooted completely, and it still didn't ask me to approve the app running as admin.
Comment: Check this link out - it'll help you enable your tools for remote admin via IIS Manager. http://learn.iis.net/page.aspx/159/configuring-remote-administration-and-feature-delegation-in-iis-70/
Comment: The first half of that is for the target machine... when it finally discusses how to initiate the connection it says "In IIS Manager, click File and then click Connect to a Site (or Connect to an Application). " which is exactly what is missing for me.  Their screen shot looks different (has more buttons) than I see.
Answer: Have you tried looking for the IIS remote administration tools - that's what I had to get used to when managing 2008 boxes remotely.
Comment: isn't that what IIS Manager is?
Comment: Not sure cos it's been a while since I looked at 2008 - these any good? - http://www.microsoft.com/downloads/details.aspx?FamilyID=7D2F6AD7-656B-4313-A005-4E344E43997D&displaylang=en
Comment: Gave it a shot (updated question) - no luck.  Even turned on *every* feature inside "Turn Windows Features on or off -> Remote Admin Tools"
Answer: I had to install the IIS remote administration tool (as stated by Matt, and suggested by several others).  However, after the install, I ran into the same problem that Matt listed: when I tried to connect to the sites, I kept getting a 401 error message.
I did a complete reboot of the system; when I logged back into the system and then tried IIS remote administration tool again, this time I was able to connect to the external site.  Not sure if the reboot solved the problem or if it was something else, but hopefully this will help someone else facing the same issue.
Answer: Just thought I'd let people know my experience. I already had "IIS Manager for Remote Administration" however, I was also stuck with the OPs screenshots. No way to connect or add new connections etc.
My issue was that I guess something went a little "off" with my upgrade to Windows 10. I ran the "repair" option and this solved my issue.


Java Thread StackOverflowError

Question: ...
Thread showWordThread = new Thread() {
    public void run() {
            try {
                sleep(config.delayTime * 1000);
            } catch (Exception e) {
                System.out.println(e.toString());
            }
            this.run();
        }
    };
    showWordThread.run();
}

...
It had run for about 5 minutes before error occured:
Exception in thread "Thread-2" java.lang.StackOverflowError.
Why?
I had tried this:
Thread showWordThread = new Thread(new Runnable() {
        public void run() {
            while (true) {
                try {
                    Thread.sleep(config.delayTime * 1000);
                } catch (Exception e) {
                    System.out.println(e.toString());
                }
            }
        }
    });
    showWordThread.start();

But error still occured.
Comment: What you call `this.run`, this statement has not any good reason!!!
Comment: I want to call it(with something inside) every 1 minute.
Comment: Ok,I wrote my answer , I hope it useful for you.
Answer: Others have explained that you should use a while loop instead. You're also trying to call the run method inside your anonymous class declaration. Additionally, you should call start, rather than run - when the new thread has started, it will call run automatically. I'd actually suggest implementing Runnable rather than extending Thread, too. So you want:
Thread showWordThread = new Thread(new Runnable() {
    @Override public void run() {
        while (someCondition) {
            try {
                Thread.sleep(config.delayTime * 1000);
                // Presumably do something useful here...
            } catch (Exception e) {
                System.out.println(e.toString());
            }
        }
    }
});
showWordThread.start();

Alternatively, consider using a Timer or ScheduledExecutorService.
Comment: @hnimnart: If it's the same error, then it must be in some code you haven't shown us. The code above will *not* result in stack overflow.
Comment: @hnimnart: So not the same error :) If it's a different error, I suggest you start a new question. No point in mixing the two.
Comment: @user2910110: Please don't use comments to draw attention to unrelated questions like this.
Answer: You are calling run method as recursively. Java holds call information(such as parameters) in stack memory so when you are calling a method recursively and there isn't any end point, stack memory will consumed and StackOverflow exception throws.
Maybe you want increasing Heap Size of JVM but this solution don't solve your problem and StackOverflow will occurred .
I guess you want run a thread continually. I recommend following code:
Thread showWordThread = new Thread()
{
    public void run()
    {
            try
            {
                sleep(config.delayTime * 1000);
            }
            catch (Exception e)
            {
                System.out.println(e.toString());
            }
            // this.run(); this snnipet code  make error
        }
    };
    showWordThread.run();
}

Answer: Your code have infinity recursive, you should change the code to:
    Thread showWordThread = new Thread() {
        public void run() {
            while (true) {
                try {
                    Thread.sleep(config.delayTime * 1000);
                } catch (Exception e) {
                    System.out.println(e.toString());
                }
            }
        }
    };
    showWordThread.start();

Comment: @Jeffrey, my mistake, forgot to remove the recursive call
Comment: This is still infinite recursion.
Comment: But I want to do something in "every 1 minute"
Answer: Don't call run() from within the run() method. That'll definitely produce a stack overflow because you keep reentering the same method with no exit condition. Instead use a while loop.
Thread showWordThread = new Thread() {
    public void run() {
        while(condition) {
            try {
                sleep(config.delayTime * 1000);
            } catch (Exception e) {
                System.out.println(e.toString());
            }
        }
    };
    showWordThread.start();
}

Comment: The end of this is somewhat dodgy - your `run()` call should be `start()`, and the semi-colon after the brace should be one brace later.
Comment: Whoops. blind copy/paste. Thanks. +1 to your answer since you posted your identical while I was still typing ;)
Answer: Your function calls itself each time you run it.
That results in a stack overflow.
Comment: What should I do now? I want to run it every 1 minute.
Answer: Maybe because you call run method (this.run()) from itself?

Java Thread StackOverflowError


How well does $Q(z|X)$ match $N(0,I)$ in variational autoencoders?

Question: At train time, the KL divergence term drives $Q(z=\mu(X)+\epsilon \times\Sigma(X) | X)$ toward $N(0,I)$, where $\epsilon\sim N(0,I)$. It can't drive $Q(z|X)$ to exactly $N(0,I)$ because the reconstruction loss of the encoder/decoder pair would explode (the $Q(z|X)$ network would destroy all information about $X$).
Therefore when we run the system at "generator time" using only the decoder and sampling $z$ from $N(0,I)$, won't this poorly represent the training set because $Q(z|X)$ over the training set is too different from $N(0,I)$? For example $Q(z|X)$ might look like $N(0,2\times I)$, or it might even have some nonlinear hard-to-sample shape.
edit1: To clarify and ask a more well defined question: If the distribution of Q(z|X) is significantly different from N(0,I), why do we sample from N(0,I) when generating samples? Won't this yield samples that poorly represent the training set?
edit2: Even more clarification. This image shows the 10 MNIST digits mapped into a 2D latent space. You can see it does not match $\mathcal{N}(0,I)$. This image is based on 2 latent dimensions and 2 hidden layer encoder, each with 500 nodes.
Answer: It's ok for $Q(z|X)$ to be different from $\mathcal{N}(0, I)$, because when we sample from the VAE, we're not trying to reconstruct $X$ anymore. Instead, we're trying to sample some $X \sim \mathcal{X}$ where $\mathcal{X}$ is the distribution of all images in the dataset.
Imagine of the latent space were actually a uniform distribution over the  interval $(0,10)$, and we were autoencoding MNIST digits. Suppose that images with 1 in them happened to have $Q(z|X)$ distributed around $(0,1)$, images with 2 happened to be around $(1,2)$, etc.
Then for any particular $X$, $Q(z|X)$ is not close to matching the uniform distribution. However, as long as the mixture $\frac{1}{n} \sum_i Q(z|X_i)$ reasonably covers and matches the uniform distribution, it's reasonable to sample $z \sim U(0,10)$ and then run the decoder, because the $z$ you got is probably close to $\mu(X)$ for some $X$.
edit: To answer the question of why we might expect the mixture of $Q(z|X)$ to be approximately $\mathcal{N}(0,I)$, note that we can decompose $P(z) = \int P(z|X) p(X) dz = E\left[ P(z|X) \right]$. By definition, $z \sim \mathcal{N}(0,I)$. However, when we approximate $P(z|X)$ with the encoder $Q(z|X)$, we end up with something slightly different.
Minimizing the VAE loss is equivalent to maximizing $\log P(X) - \mathcal{D}_\text{KL}(Q(z|X) || P(z|X))$. So we're simultaneously maximizing the log likelihood of the data while also encouraging $Q(z|X)$ to be as close to $P(z|X)$ as possible. As a result, we should end up with  very close to $\mathcal{N}(0,I)$.
Comment: But we can compute the KL divergence between N(0,I) and Q(z|X) in closed form if both are Gaussian, which is what we typically do. Once trained, the distribution of Q(z|X) will look like a quilt of 10 Gaussians for MNIST (analogous to the picture you described for MNIST on the uniform distribution), and the mixture will be bigger than N(0,I). I guess we have to manually inspect this mixture distribution in the latent space and try to come up with a way to sample it. On the other hand, this blog claims that we should sample from N(0,I) at generator time, not Q(z|X).
Comment: the blog: https://towardsdatascience.com/teaching-a-variational-autoencoder-vae-to-draw-mnist-characters-978675c95776
Comment: I edited my answer to answer your question on why you might expect the "quilt" to be approximately N(0,I)
Comment: @shimao I think it is misleading to say $KL(Q(z|x) \Vert P(z))$ is a regularizer term in some tutorials, it is simply a term in the lower bound. Moreover, for generative purposes, the only thing that we care about is $P(x) = \int P(x|z)P(z)$. $P(z)$ is the prior and we get $P(x|z)$ by training, so we don't actually care about $Q(z|x)$.
Comment: @me_Tchaikovsky i'm not exactly sure what you're getting at -- but there is indeed value in knowing how close $Q(z|x)$ comes to $P(z|x)$, because that determines whether it makes sense to sample from VAEs in the straightforward way (sampling the latent space and then running the decoder)
Comment: @shimao I'm not saying $Q(z|x)$ is unimportant since we start from $KL(Q(z|x) \Vert P(z|x))$, the $KL(Q(z|x) \Vert P(z))$ shows up simply because we decompose $P(z|x)$ by Bayes' rule, yet the $P(z)$ can also be absorbed by $E_{z ~ Q}(log(P(x|z))$. So I think there is not a direct relation between how good $Q(z|x)$ approxiamtes $P(z)$ and how good the VAE generates samples.
Comment: @me_Tchaikovsky I agree with what you are saying. However, if $q(z|X)$ does not come close to matching $P(z)$ and we sample from the $P(z)$, and decode to get an image, the image may not look like any of the training data at all, since the decoder has not seen any similar inputs before.
Comment: @shimao You are right, I forgot we are effectively approximating $p(x)$ by $E_{z \sim q(z|x)}(p(x|z))$ :-)
Answer: The answer is two-fold:
(1) The encoder network needs to be expressive enough (wide enough and deep enough) to be able to map the nonlinear input space to something close to $\mathcal{N}(0,I)$.
(2) In addition to (1) (I added a 3rd hidden layer to the MNIST example I described in the question), when I increase the number of latent dimensions, I observe that the mapping of the training data into the latent space becomes closer to $\mathcal{N}(0,I)$. In hindsight this is not super surprising, because the system is able to store information across more dimensions, so each individual latent dimension can get closer to $\mathcal{N}(0,I)$.
Answer: As a complement to shimao's answer, which boils down to "the mixture of $q(z|x)$ is reasonably close to the $N(0,I)$ distribution", it is worth noting that nowadays, at least in in the context of using VAEs for generative modeling of images, it is common practice to train another model (after the VAE training is done) which learns the actual $q(z)$ distribution rather than supposing it's "close enough" to the fixed prior.
This training is typically carried out via an autoregressive neural network, which allows in turn to easily sample from this "true" $q(z)$ once that network is trained. This is the process used in VQ-VAE, VQ-VAE-2 and DALL-E for example.
To quote from the VQ-VAE-2 paper (section 3.2) :

Fitting prior distributions using neural networks from training data
has become common practice, as it can significantly improve the
performance of latent variable models. This procedure also reduces the
gap between the marginal posterior and the prior. Thus, latent
variables sampled from the learned prior at test time are close to
what the decoder network has observed during training which results in
more coherent outputs.
Answer: Also, we sample $z$ from the prior and decode it because we made the assumption that $p_{\theta}(x) = \int p_{\theta}(x|z)p(z) dz$. Therefore, sampling from $p_{\theta}(x)$ is equivalent to sampling from the joint $p_{\theta}(x,z)$ then discarding $z$.


how to override setters when implementing Interface with properties using TypeBuilder C#

Question: What I'm doing is creating a dynamic type from System.Data.DataTable through reflection. But i'm stuck when implementing an Interface to my dynamic type created by TypeBuilder.
My Interface looks like this
public interface ICustomViewCols
{
    int? CardId { get; set; }

    DateTime? OutDate { get; set; }

    string HospCode { get; set; }
}

And my TypeBuilder looks like
var aName = new AssemblyName("UniWeb.CustomView");
var ab =
    AssemblyBuilder.DefineDynamicAssembly(aName,
        AssemblyBuilderAccess.RunAndCollect);
var mb =
    ab.DefineDynamicModule(aName.Name + ".dll");

var tb = mb.DefineType(
    "CustomViewModel",
    TypeAttributes.Public);

tb.AddInterfaceImplementation(typeof(ICustomViewCols));

foreach (var obj in cols)
{
    var col = obj as DataColumn;
    var propType = GetNullableDataType(col.DataType);
    var propName = col.ColumnName;

    if (propName == "HospCode" || propName == "CardId" || propName == "OutDate")
    {
        var getMethod = typeof(ICustomViewCols).GetProperty(propName).GetGetMethod();
        var setMethod = typeof(ICustomViewCols).GetProperty(propName).GetSetMethod();

        var currGetPropMthdBldr = tb.DefineMethod($"get_{propName}",
            MethodAttributes.Public | MethodAttributes.Virtual,
            propType, Type.EmptyTypes);
        var getIl = currGetPropMthdBldr.GetILGenerator();
        getIl.Emit(OpCodes.Ret);
        tb.DefineMethodOverride(currGetPropMthdBldr, getMethod);

        var currSetPropMthdBldr = tb.DefineMethod($"set_{propName}",
            MethodAttributes.Public | MethodAttributes.Virtual,
            null, new[] { propType });
        var setIl = currGetPropMthdBldr.GetILGenerator();
        setIl.Emit(OpCodes.Ldarg_0);
        setIl.Emit(OpCodes.Ldc_I4_1);
        setIl.Emit(OpCodes.Ldarg_1);
        setIl.Emit(OpCodes.Callvirt, setMethod);

        setIl.Emit(OpCodes.Ret);
        tb.DefineMethodOverride(currSetPropMthdBldr, setMethod);
    }
    else
    {
        var field = tb.DefineField(propName, propType, FieldAttributes.Public);
        var property = tb.DefineProperty(propName, PropertyAttributes.None, propType,
            new Type[] {propType});
        var GetSetAttr = MethodAttributes.Public | MethodAttributes.HideBySig;
        var currGetPropMthdBldr =
            tb.DefineMethod($"get_{propName}", GetSetAttr, propType, new Type[] {propType}); // Type.EmptyTypes);
        var currGetIL = currGetPropMthdBldr.GetILGenerator();
        currGetIL.Emit(OpCodes.Ldarg_0);
        currGetIL.Emit(OpCodes.Ldfld, field);
        currGetIL.Emit(OpCodes.Ret);

        var currSetPropMthdBldr =
            tb.DefineMethod($"set_{propName}", GetSetAttr, null, new Type[] {propType});
        var currSetIL = currSetPropMthdBldr.GetILGenerator();
        currSetIL.Emit(OpCodes.Ldarg_0);
        currSetIL.Emit(OpCodes.Ldarg_1);
        currSetIL.Emit(OpCodes.Stfld, field);
        currSetIL.Emit(OpCodes.Ret);

        property.SetGetMethod(currGetPropMthdBldr);
        property.SetSetMethod(currSetPropMthdBldr);
    }
}
var customViewType = tb.CreateType();

And this works only for the getters in my interface but not work for the setters. It throws an exception of System.InvalidOperationException: Method 'set_HospCode' does not have a method body. Could anybody help me out?
Answer: Here's the follow up for my question. I changed my Interface with only getters.
public interface ICustomViewCols
{
    int Id { get; }

    DateTime? OutDate { get; }

    string HospCode { get; }
}

And then I just implement the getters of the interface and consider the setters as property setters.
    private Type CreateDynamicTypeFromDataColumn(IEnumerable<DataColumn> cols)
    {
        //naming
        var aName = new AssemblyName("UniWeb.CustomView");
        var ab =
            AssemblyBuilder.DefineDynamicAssembly(aName,
                AssemblyBuilderAccess.RunAndCollect);
        var mb =
            ab.DefineDynamicModule(aName.Name + ".dll");

        var tb = mb.DefineType(
            "CustomViewModel",
            TypeAttributes.Public);

        tb.AddInterfaceImplementation(typeof(ICustomViewCols));

        foreach (var col in cols)
        {
            var propName = col.ColumnName;
            var propType = propName == nameof(ICustomViewCols.Id)
                ? col.DataType
                : GetNullableDataType(col.DataType);

            var field = tb.DefineField(propName, propType, FieldAttributes.Public);
            var property = tb.DefineProperty(propName, PropertyAttributes.None, propType,
                new Type[] {propType});
            var propertyAttr = MethodAttributes.Public | MethodAttributes.HideBySig;

            //implement interface getter
            if (propName == nameof(ICustomViewCols.HospCode)
                || propName == nameof(ICustomViewCols.Id)
                || propName == nameof(ICustomViewCols.OutDate))
            {
                var getMethod = typeof(ICustomViewCols).GetProperty(propName).GetGetMethod();

                var currGetPropMthdBldr = tb.DefineMethod($"get_{propName}",
                    MethodAttributes.Public | MethodAttributes.Virtual,
                    propType, Type.EmptyTypes);
                var getIl = currGetPropMthdBldr.GetILGenerator();
                getIl.Emit(OpCodes.Ret);
                tb.DefineMethodOverride(currGetPropMthdBldr, getMethod);
            }

            //set property getter
            else
            {
                var currGetPropMthdBldr =
                    tb.DefineMethod($"get_{propName}", propertyAttr, propType,
                        new Type[] {propType});
                var currGetIL = currGetPropMthdBldr.GetILGenerator();
                currGetIL.Emit(OpCodes.Ldarg_0);
                currGetIL.Emit(OpCodes.Ldfld, field);
                currGetIL.Emit(OpCodes.Ret);
                property.SetGetMethod(currGetPropMthdBldr);
            }

            //set property setter
            var currSetPropMthdBldr =
                tb.DefineMethod($"set_{propName}", propertyAttr, null, new Type[] {propType});
            var currSetIL = currSetPropMthdBldr.GetILGenerator();
            currSetIL.Emit(OpCodes.Ldarg_0);
            currSetIL.Emit(OpCodes.Ldarg_1);
            currSetIL.Emit(OpCodes.Stfld, field);
            currSetIL.Emit(OpCodes.Ret);

            property.SetSetMethod(currSetPropMthdBldr);
        }

        return tb.CreateType();
    }

And it works.


example of preorder on a set

Question: A binary relation $\preceq$ on $X$ is a preorderr if
1) it is reflexive, i.e. $x \preceq x$ for $x \in X$;
2) it is transitive, i.e. $x_{1}, x_{2}, x_{3} \in X$, $x_{1} \preceq x_{2}$ and $x_{2} \preceq x_{3}$ imply $x_{1} \preceq x_{3}$;
Unlike the simple order, the preorder (quasiorder) is not necessary antisymmetric (antisymmetric means $x_{1}, x_{2} \in X$, $x_{1} \preceq x_{2}$ and $x_{2} \preceq x_{1}$ imply $x_{1} = x_{2}$) and two elements can be noncomparable.
Could you, please, give an example of a preorder?
Comment: You should write: a quasiorder is not *necessarily* antisymmetric. In particular, any order is a quasiorder.
Comment: thank you, @ J.-E. Pin, I have changed
Answer: Every partial order is by definition a quasi-order as well, since a quasi-order is not necessarily anti-symmetric, but nowhere we require that it is not anti-symmetric either.
A more useful example would be the following relation on subsets of $\Bbb N$: $A\subseteq^* B$ if and only if $A\setminus B$ is finite. Namely, $A$ is "almost a subset" of $B$ if up to a finite mistake, it is indeed a subset. I will let you verify that it is indeed a quasi-order, and of course it is not anti-symmetric, since for every finite set $A$, $A\subseteq^*\varnothing\subseteq^* A$.
Answer: The integers under divisibility.
More generally, for any integral domain, the divisibility relation is a quasi order which is a antisymmetric iff the unit group is trivial.

example of preorder on a set


Why syntax of innerText and setItem is different in JS?

Question: The syntax of setItem is like setItem(key, value) but the syntax of innerText is like innerText= "text". Why setItem is not used like setItem(key)=value? is there any technical reason?
Comment: `setItem` is a method, `innerText` is a property. `.setItem(..)` is a method call, you can't assign anything to it. You can in fact do `localStorage.key = value` instead, but it's less safe (at least in theory). Lots of OO languages have the same distinction, and getter and setter methods are often implemented to prevent invalid values.
Comment: To clarify terminology, you are talking about JavaScript **syntax** here. The word "grammar" in this context is incorrect usage.
Answer: The technical reason is because of the differences between what we call rvalue and lvalue. An rvalue is an expression that can occur on the right side of an assignement = operator. Likewise, an lvalue can occur on the left side. In this case, a function call like setItem(key) is an rvalue and cannot occur on the left side of =.
Answer: There are two common ways that DOM (and other) APIs expose functionality. One of them is by using = to assign to a property:
someElm.textContent = 'foo';
someElm.onclick = () => console.log('clicked');

The other common method is by calling a function:
localStorage.setItem(key, value);
someElm.addEventListener('click', () => console.log('clicked'));

That's just the way things are. Some developers find using one method or the other to be more convenient, compared to only having the option to use one of them.
Note that Storages also can be changed using =, without calling setItem. For example, the following two methods do the same thing:
sessionStorage.setItem('prop', 'val');
sessionStorage.prop = 'val';

The function-based method is very easy to understand - the object on which the method is called has that method as a property, and so can be invoked by passing the desired arguments.
The = based method is a bit weirder. What's happening underneath is the = is invoking a setter. You can see this if you examine the property descriptor:

console.log(Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'innerText'));

Here's an example of how to create such an API yourself:

const obj = {
  set prop1(val) {
    console.log('prop1 setter invoked with', val);
  }
};
obj.prop1 = 'val1';

// Another example:
Object.defineProperty(obj, 'prop2', {
  set: (val) => {
    console.log('prop2 setter invoked with', val);
  }
});
obj.prop2 = 'val2';


DNSSEC automatic signing isn't automatic

Question: I'm having trouble with getting DNSSEC automatic signing to actually be automatic. It fails to sign automatically (well, it does sign automatically, but apparently signs the wrong thing, see below). In addition, cryptic errors are occasionally generated at unpredictable times, and then seem to go away again.
The setup:
zone "example.com" in {
   # file "/etc/bind/zones/db.example.com";  # raw data comment out
   file "/etc/bind/zones/db.example.com.signed";
   key-directory "/etc/bind/keys";
   auto-dnssec maintain;
   inline-signing yes;
};

Then I sign the zone:
dnssec-signzone -o example.com -t -k ../keys/Kexample.com.+008+04309.key db.example.com ./keys/Kexample.com.+008+21996.key

and then update everything:
rndc reload
rndc reconfig
rndc loadkeys example.com
rndc signing -list example.com

Seems like everything worked. No errors, not even in syslog, and dig @ns.example.com example.com responds appropriately. As does dig @ns.example.com +dnssec +cd +multiline example.com. Looks healthy as a horse. Well, almost. When I look at the directory: ls -la /etc/bind/zones I see things that struck me as peculiar:
-rw-r--r-- 1 root root  4578 Apr 14 11:06 db.example.com
-rw-r--r-- 1 root bind 21189 Apr 14 13:01 db.example.com.signed
-rw-r--r-- 1 bind bind   512 Apr 14 13:01 db.example.com.signed.jbk
-rw-r--r-- 1 bind bind  4720 Apr 14 13:15 db.example.com.signed.signed
-rw-r--r-- 1 bind bind 67248 Apr 14 13:24 db.example.com.signed.signed.jnl

Signed signed files? Huh? OK, but everything works. Well, almost everything. Soon thereafter, I start seeing errors in syslog:
named[25494]: malformed transaction: /etc/bind/zones/db.example.com.signed.signed.jnl last serial 2021041421 != transaction first serial 2021041404
named[25494]: zone example.com/IN (signed): zone_sign:dns_journal_write_transaction -> unexpected error

This will appear in bursts, repeating once a minute, and then they go away for a while (no predictable pattern). They seem to go away when I say rndc sync -clean. A new copy of db.example.com.signed.signed shows up every so often, on unpredictable timescales: maybe after 5 minutes, maybe after half an hour, maybe after a few hours.
Whatever. We're all good now. Ignore things for a month, come back and find the DNSSEC signatures have expired!  How can that be? ls -la shows that the timestamps on db.example.com.signed.signed and db.example.com.signed.signed.jnl are recent: obviously, bind9 thinks that these need to be regularly updated. The timestamp on db.example.com.signed is old - a month old, and looking at it's contents, I see that, indeed, RRSIG SOA has a now-expired timestamp on it.
Obviously, something is wrong. Since having the double-signed db.example.com.signed.signed file seems wrong, and since db.example.com.signed was never automatically updated, I figure that, ah hah! I should not have manually signed things!  So I go back and edit the zone file to read:
zone "example.com" in {
   file "/etc/bind/zones/db.example.com";  # oh, maybe use this, the unsigned zone
   # file "/etc/bind/zones/db.example.com.signed"; # manual signing must be wrong.
   ...
};

But if I use the above, there is no combination of starting and stopping bind9 or issuing rndc commands that makes things work: nothing is signed, and the zone won't get served, and there are no errors. This includes trying rndc sign example.com which appears to do nothing: no errors, no messages, no changes to what is being served.
I can  certainly resolve the above by sticking the manual dnssec-signzone into a crontab file, but that seems to evade the whole point of "automatic signing". What's going wrong, here? What did I do wrong?
This is named -v version BIND 9.11.3-1ubuntu1.14-Ubuntu.
Comment: I *suspect* that you have some combination of zone files and journal files that are out of sync?
Comment: If you want bind to sign automatically, you must use the file without signature, like in the last example. No need to sign anything with any command : just "rndc reload ZONE" and the signature is applied and in functional. The signed file is added in the /etc/bind/zones directory but must not be used in the configuration
Comment: Hi @Dom Well, by the end, that's what I concluded. Tried that (described above) but no signed files ever show up, and the server won't serve anything at all (`dig` comes back blank). There aren't any error messages, either ... just that nothing happens and nothing is served.
Comment: Indeed, you are not supposed to use the old tooling like dnssec-signzone together with the newer automated signing (auto-dnssec maintain).  What does it mean that "dig comes back blank"? What does it say? And anything relevant in the logs? See https://ftp.isc.org/isc/dnssec-guide/html/dnssec-guide.html#easy-start-guide-for-authoritative-servers for reference
Comment: "dig comes back blank" == dig prints headers and a question section; there is no answer, authority or additional sections printed.
Answer: Your problem was that your zone configuration enabled the inline-signing option.
According to ISC:

With the release of BIND 9.9, ISC introduced a new "inline-signing" option for BIND 9, which allows named to sign zones completely transparently. A server can load or transfer an unsigned zone, and create a signed version of it which answers all queries and transfer requests, without altering the original unsigned version.

So BIND was expecting the file option in the zone config to be the unsigned file, which it would then transparently sign and manage for you.
Answer: I found a "nuclear option" that appears to restore the system into a state consistent with documentation. It consists of the following steps:
service bind9 stop

Halt the daemon while we work on things. The other nameservers will pick up the slack.
Next, remove autogenerated/cached files:
rm -r /var/cache/bind/*

This directory contains assorted auto-generated files. These appear to contain stale data that interferes with the interpretation of the zone files and the ZSK/KSK state (i.e. contain cached values that are inappropriate). These will be recreated upon startup.
Next, edit all zone files (not just some of them!), and increment the serials by 50 to 100. This number needs to be large enough to avoid potential complaints about malformed transaction, last serial != transaction first serial. This large increment may need to be done more than once.
Edit  all zone files, convert any $INCLUDE statements to use absolute paths, instead of relative paths.  Although relative paths work just fine for unsigned zones, it seems that when a zone is signed, the relative path is misinterpreted (this smells like a bind9 bug to me... its hard to see why it would matter.).
There are also more autogenerated/cached files that are found in /etc/bind/zones; these should be removed.
rm *.signed *.jnl *.jbk

These files will all be recreated upon server startup. They contain cached information (such as the old serial numbers) that lead to spurious errors.
Do not use dnssec-signzone. This is not needed, and using it will generate files that conflict with automated zone signing.
Finally, restart the server.
service bind9 start

The above seems to be enough to clear out inconsistent cached data, and at this time, seems to be generating valid, signed zones, for me. It will take some number of TTL's and rollovers to see if things continue to work. For now, at least, behavior is consistent with documentation and with "common sense", for me.


Creating a shell script with diff function to compare multiple files

Question: I have five different files and all are in different directory, I want to check matching files and find out the unique files as well.
I am not sure how should I handle this.
Answer: You can use cksum ou md5sum to detect identical files :
 find . -type f | while read f; do md5sum "$f"; done > tmp.txt

 cat  tmp.txt | cut -d" " -f1 | while read c
 do  n=`grep $c tmp.txt | wc -l`
 if [ "$n" != "1" ]; then
    grep $c tmp.txt
 fi
 done | sort -u

Answer: You can look to the output of
chksum "path1/file1" "path2/f2" "p3/f3" "p4/f4" "p5/f5" | sort

You can also make a script looping through the files with
files=("path1/file1" "path2/f2" "p3/f3" "p4/f4" "p5/f5")
for i in {0..4}; do
    ((j=$i+1))
    while [ $j -le 4 ]; do
       diff "${files[i]}" "${files[j]}" >/dev/null
       if [ $? -eq 0 ]; then
           echo "${files[i]} and ${files[j]} are the same."
       else
           echo "${files[i]} and ${files[j]} are different."
       fi
       ((j++))
    done
done


Existence or non existence of uniformly convergent subsequence

Question: Consider the sequence of functions defined from $[0,1]$ to $\mathbb{R}$, given by $$f_n(x) = \frac{2x^2}{x^2+(1-2nx)^2}~,\quad \text{where} ~~n=1,2,\dots$$
I could conclude that this sequence of functions converges pointwise to zero. But supremum of $|f_n - f|$, (here $f=0$) does not converge to zero, hence convergence is not uniform.
But I'm not able to conclude if there exist a subsequence that converges uniformly or not.  Any help would be appreciated.
Thanks in advance.
Answer: The pointwise limit is  $f(0)=2, f(x)=0$ for $x \neq 0$. Every subsequence converges to the same limit. Since this limit is not continuous it follows that the convergence is not uniform.
Answer: I think not, because for every $n$ other than $0$, function $f_n(x)$ has a maximum at some point $x_{max}$ such that $$f_n(x_{max})=2$$


Help with $\lambda \in \Bbb C$ so that $f(z)= \lambda \cdot g(z)$ $\forall z \in \Bbb C$

Question: Let $f$ and $g$ be two entire functions, s.t. $|f(z)|\leq |g(z)|$ $\forall z \in \Bbb C$. I wanna show that it exists $\lambda \in \Bbb C$, with $|\lambda |\leq 1$ so that $f(z)= \lambda \cdot g(z)$ $\forall z \in \Bbb C$.
Let's observe $h:= \frac{f}{g}$, with $g$ not equal to zero. By assumption $\vert h \vert \leq 1$ so all the singularities of h, which are isolated by the identity principle, are removable by the Riemann extension theorem.
Why can we conclude this?
Comment: https://math.stackexchange.com/questions/613524/suppose-f-and-g-are-entire-functions-and-fz-leq-gz-for-all-z-i?rq=1
Comment: What you added is correct. Which part exactly is unclear to you?
Comment: Why are all the singularities of $h$ isolated by the identity principle? Maybe if I understand this, I will also understand the next sentence.
Comment: The zeros of $g$ are isolated (unless $g$ is identially zero).
Comment: Alright but how now the Riemann extensions theorem comes into the game? Is it because the limit of $h(z)$ when $z$ tends to the isolated zero exists because $h$ is bounded?
Comment: Yes. $h$ is bounded so that all its singularities are removable. That is Riemann's theorem.
Answer: As pointed out in the comments, either $g$ vanishes identically (and in this case the conclusion is trivial, since both $g$ and $f$ are $0$) or it has isolated zeroes.
In the latter case, the quotient $h$ is in modulus $\le1$ and defines an holomorphic function on the whole plane minus a discrete set (the zeros of $g$). By Riemann thm, as pointed out, $h$ extends across these isolated singularities to an entire function which is then bounded.
Then by Liouville theorem $h$ is constant, that is, $\exists \lambda\in\Bbb C$ such that $0<|\lambda|\le1$ such that $h\equiv\lambda$.
Since $h=f/g$ you get the conclusion.


Primary Key violation

Question: The below insert statement is not working saying:unique primary key violated ora-0001. Do you know why it is not working ?
primary key is the seq id
INSERT INTO VITA_TRANSACTION ( VTR_SEQ_ID,VTR_QUELLE_SEQ_ID,VTR_QUELLE,
  VTR_PROVIS_EXPORT_LOG_ID,VTR_DWH_EXPORT_LOG_ID,VTR_SYS_DATE,
  VTR_PROCESSSTATE,VTR_IMEI_NR,VTR_IMEI_ZUORDNUNG,VTR_ZUORDNUNG_DATE,
  VTR_IMEI_KNZ,VTR_SUBSCRIBER_NO,VTR_INSERT_TYPE,VTR_ERFASSUNG_DATUM,
  VTR_VOID_ACTIVATE,VTR_QUELLSYSTEM,VTR_VORGANG,VTR_STORNO,VTR_SALES_PRICE,
  VTR_ARTICLE_NO)
values (SEQ_VITA_TRANSACTION.nextval,418912,'M-ABVK',null,null,sysdate,
  'UM','352523003062648','352523003062648',
  to_date('20160118194708', 'YYYYMMDDhh24miss'),null,32927785,'AK',
  to_date('20160118000000', 'YYYYMMDDhh24miss'),'60000661','Activate',
  'Act','N',2000,'123123')

Comment: That's a little hard to understand but usually you omit the primary key from the statement if the column is set to auto increment
Comment: Which one exactly is the primary key here? I can see VTR_SEQ_ID and VTR_QUELLE_SEQ_ID and no just "seq_id".
Comment: the primary key here is VTR_SEQ_ID, isn't that SEQ_VITA_TRANSACTION.nextval increments the seq id to avoid violation ? I didn't write that code. I am trying to understand to know what is the problem with that violation
Comment: Do you have records in the table which were created with manually-set PKs, either before the sequence was created or in parallel? Are records *still* inserted without using the sequence - are you trying to mix both user-supplied and sequence values (which is a bad idea)? If not then you can reset your sequence higher than any existing PK value.
Answer: Primary Key violation usually occurs if you are inserting already exist values in the table. So you can check the records on the table VITA_TRANSACTION for the next sequence i.e SEQ_VITA_TRANSACTION.nextval, you can use following query:
Select
   count(*)
From **VITA_TRANSACTION**
where
   VTR_SEQ_ID = **SEQ_VITA_TRANSACTION.nextval**;

If the above query returns count as 1 then there is already a record for that sequence. Then try by increasing the sequence value or you can delete the record. It's your call.
Hope this answers your question.
Answer: PK violation means that your table already contains the id that your sequence is creating. Try check the value of SEQ_VITA_TRANSACTION.nextval and the max(VTR_SEQ_ID) from VITA_TRANSACTION:
select 'seq', SEQ_VITA_TRANSACTION.nextval from dual
 union all
 select 'tab', max(VTR_SEQ_ID) from VITA_TRANSACTION
Answer: This may not the exact answer to your question but I am trying to debug your problem.
ORA-0000
1: unique constraint (string.string) violated

Cause: An UPDATE or INSERT statement attempted to insert a duplicate key. For Trusted Oracle configured in DBMS MAC mode, you may see this message if a duplicate entry exists at a different level.

So duplicate entry already exists in VITA_TRANSACTION table.
First you should retrieve the current value of the sequence without increment it
Sample
SELECT last_number
  FROM all_sequences
 WHERE sequence_owner = '<sequence owner>'
   AND sequence_name = '<sequence_name>';

For detail follow this question How to retrieve the current value of an oracle sequence without increment it?
Then do a search in the VITA_TRANSACTION where VTR_SEQ_ID= retrieved current value + 1
I am quite sure you will get one row.Now to avoid this error you can increment  your sequence value by executing the below sql.
select SEQ_VITA_TRANSACTION.nextval from dual;

It will increment the value of your current sequence by 1(if your sequence INCREMENT BY 1) . Then try to again execute your insert query.

Primary Key violation


Improving the mean squared error of the ordinary least squares solution

Question: I have the following relationship that holds:
$y = a x_1 + b x_2$
Now I would like to determine constants $a$ and $b$ by performing tests.
Each test results in 10 values for $y$, $x_1$ and $x_2$. So I get the following set of equations:
$\underbrace{\begin{bmatrix}
y_1\\
y_2\\
\vdots \\
y_{10}
\end{bmatrix}}_{Y} = \underbrace{\begin{bmatrix}
x_{1,1} & x_{2,1} \\
x_{1,2} & x_{2,2} \\
\vdots & \vdots \\
x_{1,10} & x_{2,10}
\end{bmatrix}}_{X}\underbrace{\begin{bmatrix}
a\\
b
\end{bmatrix}}_A$
Now I use Matlab's lscov to obtain an ordinary least squares estimate for $a$ and $b$.
Some measurement sets provide really good results, while others don't. Now I would like to find out why this is the case, and what I can do to improve results.
When the results are good, the mean squared error which Matlab provides by using lscov is low. When the results are not good, the $mse$ is relatively high.
The mean squared error is given by :
$mse = Y'(I-X(X'X)X')Y$
Now I can change the input (which is closely related to the variable $y$) to my system to obtain different kind of measurements.
Now I wonder, can I simplify the equation for the $mse$ to find out how I can decrease the value for the $mse$, because now I don't directly see the consequences of a changing $Y$ and $X$ matrix.
Comment: What do you mean "you can change the input"? If you can, then just pick two $a,b$ and set $y=ax_1+bx_2$ for each data point $(x_1,x_2)$. Otherwise you can't make a set "more linear" without altering the data itself. If it's not linear than try another type of model perhaps.
Answer: First off, your formula should be:
$$mse = \frac 1{N-1}Y^T(I - X(X^TX)^{-1}X^T)Y$$
That is, with $(X^TX)^{-1}$ and divided by the number of measurements N minus 1, which is 9 in your case.
This formula always works to find the optimal solution.
The typical reason why it can give a bad result, is if your input gives no clue about the relation. For instance because all input is clustered at 1 point. The data needs to be spread around a bit.


C SECCOMP blocks or closes STDIN/STDOUT

Question: I am now implementing to run another program in child process after fork.
int main(int argc, char *argv[]) {
    pid_t pid = 0;
    int status;

    struct user_regs_struct regs;

    prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
    prctl(PR_SET_DUMPABLE, 0);

    scmp_filter_ctx ctx;
    ctx = seccomp_init(SCMP_ACT_KILL); // default action: kill

    // build rules for whitelist of system calls
    for (int i = 0; i < size_of_whitelist_syscall; i++) {
        seccomp_rule_add(ctx, SCMP_ACT_ALLOW, whitelist_syscall[i], 0);
    }

    pid = fork();

    if (pid != 0) {
        while (waitpid(pid, &status, 0)) {
            if (WIFEXITED(status)) {
                fprintf(stderr, "terminated with code %d\n", WEXITSTATUS(status));
                break;
            } else if (WIFSIGNALED(status)) {
                if (WTERMSIG(status) == 31) {
                    fprintf(stderr, "terminated by system call violation\n");
                } else {
                    fprintf(stderr, "terminated by signal %d\n", WTERMSIG(status));
                }
                break;
            }

            ptrace(PTRACE_GETREGS, pid, NULL, &regs);

            //fprintf(stderr, "%s(%lld) from pid %d\n", callname(REG(regs)), REG(regs), pid);

            ptrace(PTRACE_SYSCALL, pid, NULL, NULL);
        }
    } else if (pid == 0) {
        FILE *fp_in = freopen("std.in", "r", stdin);
        FILE *fp_out = freopen("std.out", "w", stdout);
        FILE *fp_error = freopen("err.out", "a+", stderr);

        ptrace(PTRACE_TRACEME, 0, NULL, NULL);

        seccomp_load(ctx);
        execl("/usr/bin/java", "/usr/bin/java", "Test", NULL);
        //execl("/usr/bin/python3", "python", "./test.py", NULL);
        //execl("./test.out", "./test.out", NULL);
        seccomp_release(ctx);

        fclose(fp_in);
        fclose(fp_out);
        fclose(fp_error);

    exit(0);
    } else {
    perror("failed to fork");
    }

    return 0;
}

int whitelist_syscall[] = {
    SCMP_SYS(access),
    SCMP_SYS(arch_prctl),
    SCMP_SYS(brk),
    SCMP_SYS(clone),
    SCMP_SYS(close),
    SCMP_SYS(dup),
    SCMP_SYS(execve),
    SCMP_SYS(exit_group),
    SCMP_SYS(fcntl),
    SCMP_SYS(fstat),
    SCMP_SYS(futex),
    SCMP_SYS(getcwd),
    SCMP_SYS(getdents),
    SCMP_SYS(getegid),
    SCMP_SYS(geteuid),
    SCMP_SYS(getgid),
    SCMP_SYS(getpid),
    SCMP_SYS(getrandom),
    SCMP_SYS(getuid),
    SCMP_SYS(ioctl),
    SCMP_SYS(lseek),
    SCMP_SYS(lstat),
    SCMP_SYS(mmap),
    SCMP_SYS(mprotect),
    SCMP_SYS(munmap),
    SCMP_SYS(openat),
    SCMP_SYS(prlimit64),
    SCMP_SYS(read),
    SCMP_SYS(readlink),
    SCMP_SYS(rt_sigaction),
    SCMP_SYS(rt_sigprocmask),
    SCMP_SYS(set_robust_list),
    SCMP_SYS(set_tid_address),
    SCMP_SYS(sigaltstack),
    SCMP_SYS(stat),
    SCMP_SYS(sysinfo),
    SCMP_SYS(write)
};

int size_of_whitelist_syscall = sizeof(whitelist_syscall) / sizeof(int);

As shown above, I am testing to run C/Python/Java programs which are just simple "Hello world".
seccomp_load(ctx);

execl("/usr/bin/java", "/usr/bin/java", "Test", NULL);
//execl("/usr/bin/python3", "python", "./test.py", NULL);
//execl("./test.out", "./test.out", NULL);

I allowed some whitelist system calls using seccomp.
Python and C programs are run and their output is redirected to files.
In case of Java, child process is terminated normally, but output is gone if I load seccomp. Otherwise, I see "Hello World" message.
Thank you.
Comment: I doubted buffered I/O, so I tried to fflush, but I don't see any difference.
Answer: I answer by myself.

I tried to run Java program on JVM. It doesn't send a correct signal to parent, so it seemed like everything was fine.
My problem was not related with I/O issues, buffered I/O, flushing or file descriptor.
I tested ALLOW rules by removing system calls line by line.

The following is the minimum system calls for JVM:
    SCMP_SYS(access),
    SCMP_SYS(arch_prctl),
    SCMP_SYS(brk),
    SCMP_SYS(clock_getres),
    SCMP_SYS(clone),
    SCMP_SYS(close),
    SCMP_SYS(connect),
    SCMP_SYS(execve),
    SCMP_SYS(exit_group),
    SCMP_SYS(fchdir),
    SCMP_SYS(fcntl),
    SCMP_SYS(fstat),
    SCMP_SYS(ftruncate),
    SCMP_SYS(futex),
    SCMP_SYS(getcwd),
    SCMP_SYS(getdents),
    SCMP_SYS(geteuid),
    SCMP_SYS(getpid),
    SCMP_SYS(gettid),
    SCMP_SYS(getuid),
    SCMP_SYS(kexec_load),
    SCMP_SYS(kill),
    SCMP_SYS(lseek),
    SCMP_SYS(lstat),
    SCMP_SYS(mkdir),
    SCMP_SYS(mmap),
    SCMP_SYS(mprotect),
    SCMP_SYS(munmap),
    SCMP_SYS(openat),
    SCMP_SYS(prctl),
    SCMP_SYS(pread64),
    SCMP_SYS(prlimit64),
    SCMP_SYS(pselect6),
    SCMP_SYS(read),
    SCMP_SYS(readlink),
    SCMP_SYS(rt_sigaction),
    SCMP_SYS(rt_sigprocmask),
    SCMP_SYS(rt_sigreturn),
    SCMP_SYS(sched_getaffinity),
    SCMP_SYS(sched_yield),
    SCMP_SYS(set_robust_list),
    SCMP_SYS(set_tid_address),
    SCMP_SYS(socket),
    SCMP_SYS(stat),
    SCMP_SYS(sysinfo),
    SCMP_SYS(uname),
    SCMP_SYS(unlink),
    SCMP_SYS(write)

C SECCOMP blocks or closes STDIN/STDOUT


jQuery slideToggle one div at a time instead of all independently

Question: I'm using the function below that toggles divs, and with it, any one of the entry-content divs can be opened or closed independently of all.
What would be great is if only one entry-content div would be open at any time. Clicking a closed entry-title div would close any other entry-content div and then open the one clicked. I need to stay with the html markup, as it is created dynamically by Wordpress. Is this possible?
Function:
jQuery(document).ready(function($) {
$(".entry-content").hide('slow');
$(".entry-title").click(function() {
$(this).parent().children(".entry-content").slideToggle(500); });
});

html

Post Title 1

Lorem Ipsum...

Post Title 2

Lorem Ipsum...

More of the same....

Answer: Just close them all up again every time one is clicked:
jQuery(document).ready(function($) {
$(".entry-content").hide('slow');
$(".entry-title").click(function() {
    $(".entry-content").hide();
$(this).parent().children(".entry-content").slideToggle(500); });
});

Example: http://jsfiddle.net/auUxk/
Comment: but if you toggle one already opened, it will show the div instead of hiding it, cause you hide it before.
Answer: Yes, you can just use this logic:
$(".entry-title").click(function() {
    // hide all entry title elements
    $('.entry-title').hide();
    // show the clicked one
    $(this).show();
});

You can adjust it to use toggle instead of hide/show.
I am usually doing this kind of logic by assigning special css classes to elements (its better to have things separated). So when I click element, I add a class to it. But then, when you click another element, you have to elements with that class, but you want only one. So you have to modify it. First remove that class from all elements with it, and then add it to clicked element.
$(".anyAffectedElement").click(function() {
    // remove any instances of special class
    $('.enabledElement').removeClass('eneabledElement');
    // add special class to clicked element
    $(this).addClass('enabledElement');
});

^ This is just a general logic how can you deal with things like this. In simple cases, that 'enabledElement' class just adds some special styling (like highlight).
Comment: Thanks for the explanation; I ended up going with the answer below for the toggle action.
Answer: I did not understand those examples which were given by others, but finally i have found the answer in another place, if anyone needs a solution simplier (or different) : http://jsfiddle.net/bipen/zBdFQ/1/
@markratledge - first you need to give id of your divs instead of classes...
$("#link1").click(function(e) {
  e.preventDefault();
  $("#div1").slideDown(slow);
  $("#div2").slideUp(slow);
});

$("#link2").click(function(e) {
  e.preventDefault();
  $("#div1").slideUp(slow);
  $("#div2").slideDown(slow);
});


anyone found a really compelling use for powershell

Question: I've dabbled with powershell over the years and not really found a place where I couldn't do the job just a easily with a bit of python/cygwin/wmic/dos (read that last one as windows batch).
It's probably just familiarity with these other tools but I've not seen anywhere its been a real NEED to use powershell.
Comment: What kind of IT field are you in?  Are you considering PowerShell on maintaining Windows servers?  SQL Servers?  There are plenty of "NEED" cases depending on situations
Comment: I'm a developer that dabbles in IT now and then. I noticed more and more people using Powershell but couldn't see the why just yet.
Answer: See this post on SO, which is slowly becoming the canonical answer to this question.
Comment: I agree with you - I use what ever I need. However I think that the Ironpython (and DLR) seem to be a another solution to the one that Powershell solves and as such I've not found something the powershell really is a must for.
Answer: If you're an admin and you're going to manage Microsoft server applications in the near future - you'll need to learn powershell. That's just how it is ^^
Most new systems they're releasing are managed using powershell and the slow-ass UIs built upon that are often pretty useless and they all work by issuing powershell cmdlets in the background. As RainyRat already pointed out about Exchange 2007 - apply this concept to any upcoming or newly released Microsoft system and the picture will become more clear.
But sure, for regular maintenance scripting of old or existing systems today, it hasn't taken off yet. At least not in my book - mostly because you often want support for whatever you do in a lot of older systems like Windows 2003/XP without having to deploy a new "engine" as well. When platforms are upgraded to 2008+ and Win7+ it might become more useful in this regard as well.
Comment: Powershell does look like it's the "new thing", but don't underestimate Microsoft's ability to suddenly decide to change directions. They seem to do that fairly freqently.
Comment: Very true, though we'd still be stuck with a few years of application releases that need basic powershell skills to manage...
Answer: For regular admin stuff?  No, not yet - .BATs or (at a stretch) VBScript still do the job for me.  For managing Exchange 2007, however, it's rapidly becoming indispensable for me.  There's a whole raft of things in Ex07 that you can't actually do any other way, because they haven't written the GUI bits for them yet.
Answer: I've usually used VBScript for management tasks. However you end up relying on COM servers to do anything hard, many of which aren't standard on Windows so you have to buy (and remember to install) third party COM servers. In particular x64 causes problems because all my COM servers are 32 bit, so I end up having to run the x86 version of cscript from \windows\syswow64.
I have played with using C#, but it's compiled not interpreted so it's more hassle, and there's a fair bit of (programmer) overhead for simple tasks.
I'm far from up to speed with Powershell, but what it offers me is a one stop shop for doing everything. The standard commandlets are pretty comprehensive, and it intergrates with .Net pretty well for when you want something more unusual.
Preet, in you post you refer to using "a bit of python/cygwin/wmic/dos". Well me too, but that's four solutions, and you can replace them all by learning Powershell. There will still be the complicated scripts that I'll probably do in VBScript, but Powershell can do that majority of what I need.
JR
Comment: thanks John. Why does your name sound familiar? CIX?
Comment: Assuming you're the Preet who used to hang out in the development forums on Cix then yes, I used to be the moderator. I'm less of a developer and more of a server dude these days :-)


haproxy, capture length, and redirect

Question: I have an haproxy instance that redirects certain 301 GET requests.  Unfortunately, those requests are being truncated at 1024 bytes.
After much reading and experimenting, I believe the issue is the length of what is captured by capture.req.uri, which is 1024.  But I've not succeeded in increasing that number.  I'm quite open to pointers.
Here are the most relevant snippets from my haproxy.cfg:
global
    tune.bufsize 131072
        tune.maxrewrite 65536

defaults

frontend www-https
    bind 184.108.40.206:443 ssl crt /etc/haproxy/ssl/

    declare capture request len 16382
    declare capture response len 16382
    http-request capture capture.req.uri len 16382

    acl redirect_canonical ssl_fc_sni -i myname.example.com
    http-request  redirect  code 301  location  https://www.example.com%[capture.req.uri]  if\
 redirect_canonical

Many thanks for any suggestions.
Answer: Two lines for match and rewrite are then required.
First, a rewrite if the query string is present:
http-request redirect location %[path,map(/etc/haproxy/redirects.map)]?%[query] code 301 if { path,map(/etc/haproxy/redirects.map) -m found } { query -m found }

Then, a rewrite if the query string is absent:
http-request redirect location %[path,map(/etc/haproxy/redirects.map)] code 301 if { path,map(/etc/haproxy/redirects.map) -m found } ! { query -m found }

Your map file would be paths only.

haproxy, capture length, and redirect