text:
Q: Hölder inequality conditions for $L_p$ spaces? The Hölder inequality is the statement that if $f,g$ are measurable functions then
$$ \|fg \|_1 \le \|f\|_p \|g\|_q$$
if $p,q$ are such that ${1\over p}+ {1 \over q} =1$.
But it's not clear to me why, if both $\|f\|_p$ and $ \|g\|_q$ are finite, this implies that $\|fg\|_1$ is, too.

Is there an assumption missing in the statement on Wikipedia? (Like e.g. $f \in L_1 \cap L_p$.) Is there really no example of $f,g$ measurable such that $\|f\|_p$ and $ \|g\|_q$
  are finite but $\|fg\|_1 = \infty$?

I know that if the measure space $X$ is finite then there is an $L_p$ space inclusion $L_q \subseteq L_p$ if $p < q$. But finiteness is not in the assumptions of the Hölder inequality.

A: This is part of the point of Hölder's inequality. It shows that if $f\in L^p$, $g\in L^q$ and $\frac1p+\frac1q=1$ then $fg\in L^1$. To see "why" this holds, I suggest you examine a proof of Hölder's inequality. I can provide one if you do not have one.
EDIT: The proof relies on Young's inequality: if $x,y\ge0$ then $xy\le\frac{x^p}p+\frac{y^q}q$. This inequality is obvious if $x$ or $y$ are zero, so assume $x,y>0$. For any $t\in[0,1]$, we have
$$\log(tx+(1-t)y)\ge t\log(x)+(1-t)\log(y)$$
which can be seen by observing the graph of $\log$. Setting $t=\frac1p$, we get
$$\log\left(\frac{x^p}p+\frac{y^q}q\right)\ge \frac1p\log(x^p)+\frac1q\log(y^q)=\log(xy)$$
from which Young's inequality follows.
Now we prove Hölder's inequality. If $f$ or $g$ are zero then it is trivial, so assume $\|f\|_p,\|g\|_q>0$. Define $F=\frac f{\|f\|_p},G=\frac g{\|g\|_q}$. Then $F\in L^p,G\in L^q$ with $\|F\|_p=\|G\|_q=1$. Using Young's inequality, we have
$$\int_X|FG|\ d\mu\le\int_X\left(\frac{|F|^p}p+\frac{|G|^q}q\right)\ d\mu=\frac1p\|F\|_p^p+\frac1q\|G\|_q^q=1.$$
We have shown
$$\frac1{\|f\|_p\|g\|_q}\int_X|fg|\ d\mu=\int_X\left|\frac f{\|f\|_p}\frac g{\|g\|_q}\right|\ d\mu\le1,$$
so we are done. Note that by carefully keeping track of where equality occurs in Young's inequality, one can show that equality occurs if and only if $|f|^p$ and $|g|^q$ are linearly dependent as elements of $L^1$.

A:
not clear to me why, if both $\|f\|_p$ and $\|g\|_q$ are finite, this implies that $\|fg\|_1$ is, too.

Note that
$$ 1 < \infty $$
Therefore,
$$ \text{if $b=1$ and $a=\infty$ then $b < a$.} $$
Contraposing,
$$ \text{if $a\le b$ then it is not the case that $b=1$ and $a=\infty$.} $$
Now, Hölder's inequality assures us that if $a=\|fg\|_1$ and $b=\|f\|_p\|g\|_q$ then $a\le b$.  Therefore it is not the case that $\|fg\|_1=\infty$ and $\|f\|_p\|g\|_q = 1$.


text:
Q: Get results from two time intervals There is a query which brings back sales data for the last 7 days.
How to get the sales of the last 30 days as well (to see the sales for the last 7 days AND the last 30 days in the results)?
SELECT
  a.row_id,
  MAX(ad.new_value) - MIN(ad.new_value) AS sales7days
FROM
  _audit a
  LEFT JOIN _audit_data ad
    ON a.audit_id = ad.audit_id
WHERE ad.col = 'sales'
  AND a.triggered_datetime > NOW() - INTERVAL 7 DAY
GROUP BY a.row_id
ORDER BY sales7days DESC;

A: Perhaps with a CASE expression:
SELECT a.row_id
   ,  MAX(case when a.triggered_datetime > NOW() - INTERVAL 7 DAY
               then ad.new_value else NULL end)
    - MIN(case when a.triggered_datetime > NOW() - INTERVAL 7 DAY
               then ad.new_value else NULL end) AS sales7days
   ,  MAX(case when a.triggered_datetime > NOW() - INTERVAL 30 DAY
               then ad.new_value else NULL end)
    - MIN(case when a.triggered_datetime > NOW() - INTERVAL 30 DAY
               then ad.new_value else NULL end) AS sales30days
FROM  _audit a, _audit_data ad
WHERE a.audit_id = ad.audit_id AND ad.col = 'sales'
GROUP BY a.row_id;

A: SELECT
  d7.row_id,
  d7.salesdays, d30.salesdays
FROM
(
  Select a.row_id, MAX(ad.new_value) - MIN(ad.new_value) AS salesdays
  From _audit a
  LEFT JOIN _audit_data ad ON a.audit_id = ad.audit_id
WHERE ad.col = 'sales' AND a.triggered_datetime > NOW() - INTERVAL 7 DAY
GROUP BY a.row_id
) d7,
(
  Select a.row_id, MAX(ad.new_value) - MIN(ad.new_value) AS salesdays
  From       _audit a
  LEFT JOIN _audit_data ad ON a.audit_id = ad.audit_id
WHERE ad.col = 'sales' AND a.triggered_datetime > NOW() - INTERVAL 30 DAY
GROUP BY a.row_id
) d30

where d7.row_id = d30.row_id
ORDER BY sales7days DESC;

assume you want the same row id for both - and either value to show, you may or may not want to make it inner or outer joined and/or COALESCE the value fields (don't know enough about the data).

redpajama_set_name: RedPajamaStackExchange


text:
Q: ActionScript 2 Wall Collision I am making my Flash game but... the collisions are my very big problem. I tried every single website, but nothing works.
The code of the player is this:
    onClipEvent(enterFrame){
        if(Key.isDown(Key.RIGHT)) {
            this._x+=3
        }
            if(Key.isDown(Key.LEFT)) {
            this._x-=3
        }
            if(Key.isDown(Key.UP)) {
            this._y-=3
        }
            if(Key.isDown(Key.DOWN)) {
            this._y+=3
        }

    }

Collision:

    if(cityhallLeftWall.hitTest(Player._x+Player._width/2, Player._y, true)){
    Player._x -=0
    }
    if(cityhallRightWall.hitTest(Player._x-Player._width/2, Player._y, true)){
    Player._x +=0
    }
    if(cityhallTopWall.hitTest(Player._x, Player._y+Player._height/2, true)){
    Player._y +=0
    }
    if(cityhallBottomWall.hitTest(Player._x, Player._y-Player._height/2, true)){
    Player._y -=0
    }

The movieclip of the player is named "Player".
The movieclip of the building is named "cityhall".
So, I want for example when the movieclip Player touches the movieclip cityhall, the y and x speed to get 0 or something like that.
It's just impossible to find solution, so I decided to ask for help here.
Thanks :)

A: You should have the += be an equal repelling force to the player's speed, I.E. if your player hits a wall at x speed of 5 pixels per frame, the wall should add 5 pixels of speed to player in the opposite direction so you get a net movement of zero.

A: It's been a while since I did anything in AS2, but I'll have a go at this.
first, set up a variable for the player's speed.  It could look like this:
var speedX:Number = 0;

Now,in your enterFrame function, add this:
Player._x += speedX; //

Next, in each of your hitTest methods, do like this:
if(cityhallLeftWall.hitTest(Player._x+Player._width/2, Player._y, true)){
    speedX = 0;
}

You'll need to do likewise for the y direction.  I'm sure you can figure it out from here.  Cheers!

A: First the code, as most people aren't motivated to read without it(this in my test was placed in the movieclip Player or for me just movieclip P)
    onClipEvent(enterFrame){
    if(Key.isDown(Key.RIGHT)) {
        this._x+=3
    }
        if(Key.isDown(Key.LEFT)) {
        this._x-=3
    }
        if(Key.isDown(Key.UP)) {
        this._y-=3
    }
        if(Key.isDown(Key.DOWN)) {
        this._y+=3
    }
if(_root.cityhallLeftWall.hitTest(this._x-this._width/2, this._y, true)){
this._x +=3;
}
if(_root.cityhallRightWall.hitTest(this._x+this._width/2, this._y, true)){
this._x -=3;
}
if(_root.cityhallTopWall.hitTest(this._x, this._y-this._height/2, true)){
this._y +=3;
}
if(_root.cityhallBottomWall.hitTest(this._x, this._y+this._height/2, true)){
this._y -=3;
}
}

I tested this code and figured out your problems. This will get hard to understand in words so bear with me (don't have the reputation points to post images).
1.When testing for the right wall hit test you didn't use Player._x+Player._width/2 but Player._x-Player._width/2 this doesn't work as you tested the characters left edge against the right edged wall so the Player will be 'inside' the wall by the time he is pushed out.
2.You did the same mistake for the left wall, testing the right edge against it.
3.you aren't as mentioned by the other answers subtracting speed from the Player but subtracting 0 from the Player currents position this doesn't do anything,you have to subtract the amount the player is moving at in this case 3 in every direction(Up,Down,Left,Right).
4.Your collision checking lines aren't in the enter frame brackets and so would only be checked once at swf startup not every frame.
5.This isn't a mistake but a tip use while loops as with the current "if" you will notice if the player goes to the walls edge and manages to get inside somehow and is till pressing the directional key he can remain inside the wall but with while this can't happen.
Code for while loop:
     onClipEvent(enterFrame){
     if(Key.isDown(Key.RIGHT)) {
        this._x+=3
     }
        if(Key.isDown(Key.LEFT)) {
        this._x-=3
    }
        if(Key.isDown(Key.UP)) {
        this._y-=3
    }
        if(Key.isDown(Key.DOWN)) {
        this._y+=3
    }

while(_root.cityhallLeftWall.hitTest(this._x-this._width/2, this._y, true)){
this._x +=3;
}
while(_root.cityhallRightWall.hitTest(this._x+this._width/2, this._y, true)){
this._x -=3;
}
while(_root.cityhallTopWall.hitTest(this._x, this._y-this._height/2, true)){
this._y +=3;
}
while(_root.cityhallBottomWall.hitTest(this._x, this._y+this._height/2, true)){
this._y -=3;
}
}

hope this works and good luck.

A: The problem lies in the Player's coordinates. They are not global.
Try this in your collision function:
// store player's new local position in an object
var playerGlobalPosition = {
    x:Player._x,
    y:Player._y
};

// translate local position to global
Player.localToGlobal(playerGlobalPosition);

Then test against those global coordinates:
if(cityhallLeftWall.hitTest(playerGlobalPosition.x + (Player._width/2), playerGlobalPosition.y, true)){
    Player._x -= 3; // as mentioned before, replace those 0 values with 3
}

Explanation:
In the hitTest method the x and y coordinates are defined in the global coordinate space. So if our coordinates (Player._x and Player._y) are local, we should translate them to the global space before applying the method.
More here and here


text:
Q: Simple Web Service adding two numbers I have created a simple Webservice function as shown below;
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ws;
import javax.jws.WebService;
/**
 *
 * @author Joe
 */
@WebService()
public class Add2Int {
public int add(int a, int b) {
    return (a+b);
}
}

and I have created a very simple gui that allows the user to enter 2 numbers and which should output the result however this does not work?  I tried it without the gui and it works but when i build the gui it does not work?  here is my code for that side of things
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package myjavawsclient;
//import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

/**
 *
 * @author Joe
 */
public class Calculator extends JFrame implements FocusListener {
    JTextField value1 = new JTextField("", 5);
    JLabel plus = new JLabel("+");
    JTextField value2 = new JTextField("",5);
    JLabel equals = new JLabel("=");
    JTextField sum = new JTextField("", 5);

    public Calculator() {
        super("The Calculator");
        setSize(350,90);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        FlowLayout flow = new FlowLayout(FlowLayout.CENTER);
        setLayout(flow);
        // add the listners
        value1.addFocusListener(this);
        value2.addFocusListener(this);
        // set up sum field
        sum.setEditable(true);
        //add componets
        add(value1);
        add(plus);
        add(value2);
        add(equals);
        add(sum);
        setVisible(true);
    }

    public void focusGained(FocusEvent event){
        try { // Call Web Service Operation
            ws.Add2IntService service = new ws.Add2IntService();
            ws.Add2Int port = service.getAdd2IntPort();
            // TODO initialize WS operation arguments here
            int result = 0;
            int result2 = 0;
            result = Integer.parseInt(value1.getText());
            result2 = Integer.parseInt(value2.getText());

            int total = port.add(result, result2);
            sum.setText("" +total);

            //float plusTotal = Float.parseFloat(value1.getText()) +
                Float.parseFloat(value2.getText());

        } catch (Exception ex) {
            // TODO handle custom exceptions here
            //value1.setText("0");
            //value2.setText("0");
            //sum.setText("0");
        }
    }

    public void focusLost(FocusEvent event){
      focusGained(event);
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        // TODO code application logic here

        Calculator frame = new Calculator();
    }
}

I am not getting any errors I am just not getting any result from the 2 numbers, for example 1+1=2 but with my application it allows the user to enter 1 + 1 = ? but where the question mark is nothing gets shown.
I was wondering if anyone could solve this problem for me. Oh and I am using NetBeans and GlassFish App server with WSDL
Joe

A: You should declare add as a webmethod.
try following:
   @WebMethod public int add(int a, int b){
    return (a+b);
    }

A: My Fault! I forgot to start the App Server


text:
Q: Is infrequent syncing in DVCS trunk based development similar to a long-lived feature branch in GitFlow? I'm working on a project and trying to understand the differences and trade-offs between variations of trunk based development and feature branching like git flow so I can help implement an appropriate solution for the team.
Would the first diagram of GitFlow below also be a representation of Trunk Based Development? Not how TBD should be practiced (second image), but rather what would occur if two developers were working on their local copy of master and only infrequently merging / pushing with the remote master.
If the main benefit from TBD is to avoid semantic and textual merge conflicts that are difficult to solve by integrating frequently with the trunk then I see these benefits diminishing as merge frequency diminishes.
Most of the images of Trunk Based Development I look for contain references to short-lived feature branches but I want to better understand what committing directly to master would look like.
Images from https://martinfowler.com/bliki/FeatureBranch.html

I did find a reference that says that trunk-based development in DVCS is basically the same as feature branch development, the difference being where unmerged changes are stored (on a remote feature branch, or local copy of trunk). So if this is true, then the answer to my question would be 'yes', because infrequent merges on either a local trunk copy or remote branch would be long-lived branches.

https://devops.com/feature-branching-vs-feature-flags-whats-right-tool-job/

A: Everyone knows what GitFlow is and there is nothing in GitFlow which says your feature branches should be long lived.

But trunk based development is comparatively undefined.

The problem with any form of collaborative development is that two people working on one thing need to take each other changes into account if they want the whole thing to work.
That means the longer you keep your work to yourself the more problems you will have when you come to merge it into everyone else's changes.
Branching solutions like GitFlow have been developed to help with this problem. They allow you to work on your thing and manage the merging in of other changes over time to minimize the problem of the 'big merge'.
Frankly, the trunk based development approach as laid out by https://trunkbaseddevelopment.com/ boils down to "make smaller feature branches!"
You can do that with any branching model. The main difference in their diagrams is the lack of a development branch. But given the presence of release branches and the common lack of any work on master in GitFlow I don't think this will make much of a practical difference.
"Smaller Feature Branches" is a fine goal, but the purpose of branching models is to help you when you can't avoid them! TBD is not clear on how it solves actual real life problems
The main reason for people looking at TBD is that Google has said they do it. But a closer inspection of what they actually said leads me to believe that what they do is not really comparable to 'using git with no branches'

*

*They started off with Perforce.
If you have ever used perforce you will know that it is one step above Visual Source Control. Branches in perforce are not like branches in git

*They now have a custom source control system
So terms like repository, branching and committing don't mean the same as in git

*They have 25000 developers and do 16000 commits each day.
This is a super high number for a single repository. But a super low number per developer. I did at least 20 commits today and it was a (very) slow one.

*Every commit goes through code review
OK so here we get to the detail. Basically these commits are more like feature branch merges rather than commits. Each developer works on a 'local copy' (feature branch) which when completed is submitted for review and merging
So the big question which doesn't seem to be answered is:

*

*If there are 666 commits per hour and it takes 1.5 days to get my code committed. How do you merge it with the 23976 commits from other developers which happened since I started coding?
Reading between the lines, I think we can assume that:

*

*Their 'monolith' 'single repository' is not a single compiled application

*There are automated ways of determining if there is a potential merge conflict and altering the developers. Essentially allowing them to 'lock' sections of code

So in summary I would answer your question by saying, we all have the same problem and doing smaller changes solves it.


text:
Q: Difference between init() and main() method in java I want to know the difference between init and main method of java

A: The main method is used as an entry point for applications, the init method is used as an entry point for applets and servlets.

A: static void main is usually the declaration for a method which allows an entry point for launching the Java file/application. however, main can also be used to name any random method.
while init is one of the many random names which can be selected for naming a method [satisfying the basic rules for naming methods]. typically, programmers, in Java or any other programming language, like to name a method init if there's some initialisation routine to be run.

A: init method is used when servlets or applets is initialize while main method is used for entry point of program....
If there is first time request for servlet then first of all servlet's init method is called and also some properties may be initialize at that time
While when you start your application main is entry point for that .......means main is first process for your application


text:
Q: java.lang.IllegalStateException: Circular dependencies cannot exist in RelativeLayout Helo All,
I am stuck in an error regarding circular dependencies for Relative Layout. Could anyone help me where I went wrong?
I am using multiple activity xmls but the error is occuring when 1st activity is being executed.
Here is my Relative layout code :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#5fb0c9"
android:orientation="vertical"
android:scrollbarAlwaysDrawVerticalTrack="true">

<TextView
    android:id="@+id/login_title"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="16dp"
    android:layout_marginTop="22dp"
    android:gravity="center_horizontal"
    android:text="Account Login"
    android:textColor="#fff"
    android:textSize="26sp"
    android:textStyle="bold" />

<RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/login_title"
    android:layout_marginLeft="30dp"
    android:layout_marginRight="30dp"
    android:layout_marginTop="70dp"
    android:background="#fff"
    android:elevation="4dp"
    android:orientation="vertical"
    android:padding="20dp"
    android:id="@+id/relativeLayout">

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:paddingTop="30dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentTop="true"
        android:weightSum="1">

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/editText_username"
            android:layout_gravity="center_horizontal"
            android:layout_weight="0.14"
            android:hint="USER NAME"/>

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/editText_location"
            android:layout_weight="0.17"
            android:hint="LOCATION"/>

        <Button
            android:id="@+id/user_confirm"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_margin="22dp"
            android:background="#d67601"
            android:text="CONFIRM"
            android:textAllCaps="false"
            android:textColor="#fff"
            android:textSize="18sp" />
    </LinearLayout>
</RelativeLayout>

<ImageButton
    android:id="@+id/user_profile_photo"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:background="@drawable/user_profile_image_background"
    android:elevation="6dp"
    android:src="@drawable/pro"
    android:layout_below="@+id/login_title"
    android:layout_centerHorizontal="true" />

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/images"
    android:orientation="vertical"
    android:scrollbarAlwaysDrawVerticalTrack="true">

    <Button
        android:id ="@+id/node_scan"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="NODE SCAN"
        android:onClick="Scan"
        android:background="@drawable/button_bg_rounded_corners"
        android:padding="15dp"
        android:shadowColor="#ffffff"
        android:textColor="#ffffff"
        android:layout_marginTop="105dp"
        android:layout_below="@+id/contents"
        android:layout_alignParentEnd="true"
        android:layout_alignParentStart="true" />

    <Button
        android:id ="@+id/post"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="POST"
        android:onClick="post"
        android:background="@drawable/button_bg_rounded_corners"
        android:padding="15dp"
        android:shadowColor="#ffffff"
        android:textColor="#ffffff"
        android:layout_alignTop="@+id/next"
        android:layout_alignParentEnd="true" />
    <Button
        android:id ="@+id/next"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="NEXT"
        android:onClick="next"
        android:background="@drawable/button_bg_rounded_corners"
        android:padding="15dp"
        android:shadowColor="#ffffff"
        android:textColor="#ffffff"
        android:layout_alignParentBottom="true"
        android:layout_alignParentStart="true"
        android:layout_marginBottom="73dp" />
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/contents"
        android:layout_gravity="center_horizontal"
        android:layout_weight="0.14"
        android:hint=""
        android:background="#fcfbfb"
        android:layout_alignParentStart="true"
        android:layout_above="@+id/post"
        android:layout_below="@+id/node_scan" />
    <Button
        android:id ="@+id/quit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="QUIT"
        android:onClick="quit"
        android:background="@drawable/button_bg_rounded_corners"
        android:padding="15dp"
        android:shadowColor="#ffffff"
        android:textColor="#ffffff"
        android:layout_alignTop="@+id/post"
        android:layout_centerHorizontal="true" />

</RelativeLayout>

Thanks in Advance,
Alby

A: android:layout_below="@+id/login_title"

Here should be "@id/..." (whithout a plus sign), because it is a reference to an existing ID.
https://developer.android.com/guide/topics/ui/declaring-layout.html#id

A: The error was fixed after removing the below from Edit Text field: android:layout_above="@+id/post" android:layout_below="@+id/node_scan"


text:
Q: Grails validation errors disappear from service to controller When I do custom rejectValue in a service method grails loses that error(s) between service method and return to controller. This seems to happen when updating a row instance, but not when creating one.
In service
def specialValidation(petInstance){
       if(petInstance.petType.requiresStateId && !petInstance.StateId){
           petInstance.errors.rejectValue('StateId','StateId required');
       }
       println petInstance.errors //shows 1 error
       return petInstance;

}

In controller
...
   petInstance.properties=params;
   petInstance=petService.specialValidation(petInstance);
   println petInstance.errors //shows 0 errors

How is the error being lost when the instance changes hands from service to controller?

A: It can be because of transactional service. Service opens separate transaction for each method and clears entities after method end. You can find this mentioned in docs(read the last paragraph of part )
I had the same problem. Than I've added NotTransactional annotation to validation method, and it helped. Errors were saved.

A: Well I did something simular :
 orderService.validate(order, params)
 if (order.hasErrors()) {
      return render(view: 'create', model: [order: order])
}

In the Service I do some validation like this:
if (end.before(start)) {
        order.errors.rejectValue("end", '', 'ERROR');
}

The different to yours is that i didn't set the errorCode but the message at itself, have a look at the rejectValue Methods:
void rejectValue(String field, String errorCode);
void rejectValue(String field, String errorCode, String defaultMessage);

You could also try to use the rejectValue method like me, maybe it helps.

A: I found you can also avoid this by using
 MyDomain.read(id)

instead of
MyDomain.get(id)


text:
Q: What is the nature of "LGWR: Setting 'active' archival for destination LOG_ARCHIVE_DEST_2"? I'm not sure when this started, but for the time being the primary database instances in a physical standby configuration logs this message on every redo log switch.
******************************************************************
LGWR: Setting 'active' archival for destination LOG_ARCHIVE_DEST_2
******************************************************************
LGWR: Standby redo logfile selected to archive thread 2 sequence 306
LGWR: Standby redo logfile selected for thread 2 sequence 306 for destination LOG_ARCHIVE_DEST_2

I'm not sure what this indicates, but I do associate this message with a standby database becoming available after downtime or network outage. E.g. the (optional) archive destination was deferred, but has now become active.
Similarly, on the standby instance, I'm seeing the following on every log switch:
Primary database is in MAXIMUM PERFORMANCE mode
Re-archiving standby log 6 thread 2 sequence 308
RFS[212]: Assigned to RFS process 8304
RFS[212]: Selected log 8 for thread 2 sequence 309 dbid 18783000 branch 804771032

Again, this is a log message I associate with a disruption in the delivery of archived redo logs or a change of delivery mode (changing the log destination parameters or the protection mode).
Any idea what may be causing these to be logged repeatedly on every log switch?
Update:
I now  have a working theory: I think this will happen if real time apply have been used at all, and thus indicates that LGWR is waking up to do some archival work. Previously, I believe ARCH would take care of log transport and archival but activating real time apply may have forced a configuration change.
So far, I have found no evidence of this change being visible in data dictionary or parameter set, just the changes in alert log messages (which happened to coincide with a test involving real time apply on the standby).
If this is the case, any idea how to reverse the change now that real time log apply is disabled and no longer required?


text:
Q: PHP's Float Precision Causing Problems With Small Numbers I have an ojbect $order that has a member function amount() that adds up the sum of the line items (all floats) then returns the value (again, as a float).
var_dump(array(
    $order->amount() * 100.0,
    intval($order->amount() * 100.0),
));

result:
Array
(
    [0] => 7500
    [1] => 7499
)

The values of the line items are all under 1000 and never have more than 2 decimal points...
What is the best way to deal with decimal values in PHP, since the lack of precision is causing problems for me...
EDIT: To better illustrate:
echo "Addition: " . intval((172.45 - 72.45 - 25.0) * 100);

Result:
Addition: 7499


text:
Q: How to move a table content to the top of the screen? I am still new to iOS and Swift and I am using Swift4 and Xcode9 to edit an iOS project which is made with a prior versions of Xcode and Swift (Xcode8 and Swift3). In the project there is a TableViewController used. So the problem is when I open the project in Xcode9 and run it, it shows some space on the top. I tried changing y values, but didn't work. My questions are,

*

*How to solve the upper mentioned problem. (There is a question like this in Stack Overflow already. But it's not due to different Xcode version. But I even tried all the suggestions in the answers. But none of them worked for me.)

*When there is a text label or something on the top of the table content, I can remove that space, from the top, but it goes to in between that label and the table added. And the label is unable to get a click action or something when it's moved to the top. How to solve that?
Any suggestion/ answer will be highly appreciated. Thank you!

A: You can try this
 if #available(iOS 11.0, *) {
    yourTableView.contentInsetAdjustmentBehavior = .never
 }

A: Ok I'm going to attempt to answer your question but I wasn't totally positive since you didn't include any code or screenshots.
Firstly. If you mean that there seems to be a gap between where the tableView starts and where the first cell is displayed, this is correct. You can fix that by doing:
tableView.contentInset = .zero

this means that any content inside the tableView starts goes all the way to the edges.
Now for the label receiving touches. You want to look at user interaction enabled values on the storyboard:

Whenever you have views that stack on top of each other, the view UNDER will not receive touches if the view on top has user interaction enabled. If you want a touch to bleed through another view you either can
1) avoid the issue by not stacking views on top of each other (often unavoidable, like putting a label on a view and wanting the background view to do something)
2) turn off the user interaction on the view on top so the view on bottom gets the touch

A: tableView.setContentOffset(CGPoint.zero, animated: true)
this code will move


text:
Q: java.util.ConcurrentModificationException on CollectionOfElements I seem to get a ConcurrentModificationException when I have a CollectionOfElements inside an Embedabble.
If would like to have it like that, however If I change Route from Embedabble's to Entity than everything works fine. I have even tried adding @Version, but that doesn't seem to work.
Here are a snippet of my classes.
Kart.java:
@Entity
public class Kart {

@Id @GeneratedValue
private Long id;

@Column(nullable=false,length=256)
@NotNull
@Length(max=256)
private String name;

@OneToOne(cascade=CascadeType.ALL)
private File file;

@Version
private int version;

@CollectionOfElements
private Set<Route> route;

Route.java:
@Embeddable
public class Route {

@Parent
private Kart kart;

@NotNull
@Column(nullable = false, length = 256)
private String name;

@NotNull
@Column(nullable = false)
private Boolean visible = Boolean.valueOf(true);

@CollectionOfElements
private Set<Coordinates> coordinates;

@Version
private int version;

Coordinates.java:
@Embeddable
public class Coordinates {

@NotNull
private int x;

@NotNull
private int y;

@Parent
private Route route;

@Version
private int version;

I have generated Hashcode/equals for Coordinates and Route

A: Check this JIRA entry.
ConcurrentModificationException when collection of embeddable contains a collection
It's a known bug in the Annotation Binder. And the issue lies in Hibernate Core which doesn't support collections in collections of embedded.

A: I can't give you any Hibernate-specific advice - but ConcurrentModificationExceptions often mean that a collection is being modified inside its iterator, such as
for (String s : myStringCollection)
{
    if (s.startsWith("XXX"))
    {
        myStringCollection.remove(s);
    }
}

Normally you can avoid this by explicitly creating an Iterator and calling its remove() method instead of the Collection's - but if this is internal Hibernate code you won't have that option.

A: The usage of "@CollectionOfElements" and "@Embeddable" is confusing.  I assume you want Route and Coordinates to be separate tables?  If so, they really shouldn't be @Embeddable.  @Embeddable represents something that can be embedded into the parent table.  As an example, to use composite keys you typically use an @EmbeddedId as your PK, which links to a class which is @Embeddable.
Since you mention that switching to Entity seems to fix the problem, I think you should switch Route and Coordinate to separate Entities.  Then you will have a much more standard model setup which should clear your problem.


text:
Q: Are there some similar phrases or words like "hail" as in "hail the king"? "Hail" has meaning to praise, to greet. But replacing this words doesn't seem to fit well like "praise the king" , "greet the king". I want some words (or phrases ) which might fit well and sound good too. :)
Edit1 : I haven't done intense research on this word. Just visited some websites ( like thesaurus.org , dictionary.com, (Meaning of "hail to the king")) to find some similar words. But hardly any of those did sound good to me(like greet the king, praise the king ). I doubt imperative verbs would fit in well there.
Edit 2: I actually want words which will fit well in place "Hail" as in "Hail Hydra".  Fill this gap :  ____ hydra

A: What about Exalt? Means to hold someone in very high regard. Sounds regal to my ear, and it's odd enough that I think it might be able to "blend in" in a way a common word like praise wouldn't.
You might also check thesaurus.com: http://www.thesaurus.com/browse/exalt?s=t
Here are a couple other good ones from that list: bless, laud, acclaim, extol

A: Perhaps salute.
From the Free Dictionary
    1. To greet or address with an expression of welcome, goodwill, or respect.
    ...
    3a. To honor formally and ceremoniously

Salute gives the connotation of acknowledging and giving respect to a superior in much the same way "hail" does.


text:
Q: Menu full width of the page I have a menu I want to be the entire width of the site even when I zoom out but can't manage to make it work, this is my code.
HTML:

home

contact

about

CSS I Have tried:
#menu {
    width: max;
    background-color: #f4f4f4;
    height: 75px;
}

And
#menu {
    width: 1920px;
    background-color: #f4f4f4;
    height: 75px;
}

A: Make the width 100% -- change it in your CSS to width: 100%;
HTML :

home

contact

about

CSS:
#menu {

  width: 100%;
  background-color: #f4f4f4;
  height: 75px;

}


text:
Q: IF ... (AND) statement run time error "13" I need help with my if statements. In the code show below: The first if ... then section works just as intended, however the second section creates a run time error "13". Can someone please explain me how to fix this issue? / what i'm doing wrong?
Sub ASN_BaaN3()
Dim i As Integer
i = 0

ThisWorkbook.Sheets("BaaN").Activate

Do While ThisWorkbook.Sheets("BaaN").Cells(2 + i, 1) <> ""

    'CHECK NON SERIALIZED
    If Range("J" & 2 + i).Value = "N" Then
        Range("P" & 2 + i).Value = "Ok, Non Serialized"
        Range("P" & 2 + i).EntireRow.Interior.Color = RGB(198, 239, 206)
    End If

    If Range("J" & 2 + i).Value = "Y" And _
    Range("M" & 2 + i).Value = "ACK" And _
    Range("o" & 2 + i).Value = "TRUE" Then
        Range("P" & 2 + i).Value = "Ok, Non Serialized"
        Range("P" & 2 + i).EntireRow.Interior.Color = RGB(198, 239, 206)
    End If

    i = i + 1
Loop

End Sub

when typing the code like this i get the same error:
    If Range("J" & 2 + i).Value = "Y" Then
    If Range("M" & 2 + i).Value = "ACK" Then
    If Range("O" & 2 + i).Value = "TRUE" Then
        Range("P" & 2 + i).Value = "Ok, Non Serialized"
        Range("P" & 2 + i).EntireRow.Interior.Color = RGB(198, 239, 206)
    End If
    End If
    End If

Also when typing the code like this
    If Range("J" & 2 + i).Value = "Y" Then
    If Range("M" & 2 + i).Value = "Y" Then

Please help!


text:
Q: Sql server: Keeping track of counts in a View? Using Sql Server 2008, would it be appropriate to use a View to keep track of table counts. E.g.
CREATE VIEW [dbo].UserCounts
    SELECT     O.UserId, Count(O.OrderId) AS OrderCount
    FROM       User U INNER JOIN Orders O ON U.UserId = O.UserId
    GROUP BY O.UserId

Is this a viable solution having 100.000 users and approx. 500.000 orders?
Thanks in advance,
Anders

A: You can create an indexed view, but you must use COUNT_BIG instead:
CREATE VIEW dbo.UserCounts
WITH SCHEMABINDING
AS
    SELECT     O.UserId,
      COUNT_BIG(O.OrderId) AS OrderCount
    FROM       dbo.User U
    INNER JOIN dbo.Orders O ON U.UserId = O.UserId
    GROUP BY O.UserId;
go

CREATE UNIQUE CLUSTERED INDEX cdxUserCounts on dbo.UserCounts(UserId);
go

This way the engine will maintain the counts up to date, as opposed to count them every time you query the view. The drawback is contention, you cannot create/delete orders for the same user from different transactions.

A: This view will be executing the inline query every time you access this view. So I think just creating the index on view will not help.The main thing is to have proper indexes on the underlying 2 tables Users and Orders.


text:
Q: Convert Value on Realm Property When Retrieved and Saved in SwiftUI I have a Flight Realm class with a duration property that is an Int. It stores the duration of a flight as the number of minutes.
class Flight: Object, ObjectKeyIdentifiable{
  @objc dynamic var duration = 0
}

I pass a Flight object as an ObservedRealmObject to a child view where it's edited. The user can enter the time as HHMM (130 = 1 hr 30 min) or #.# (1.5 hrs). I have some extensions that convert either of those times from a String to the number of minutes stored as an Int and back again.
But the problem I'm having is binding my TextField. I can't bind to the duration property directly because I need to convert it from the time format to the number of minutes.
struct MyView: View {
  @ObservedRealmObject var flight: Flight
  @AppStorage("timeDisplayHHMM") var timeDisplayHHMM = false

  var body: some View{
    TextField(timeDisplayHHMM ? "HHMM": "#.#", text: $flight.duration)
  }
}

I've tried a couple different approaches that don't quite work right.
Attempt 1
I created a @State variable which I set in .onAppear and then I save the value inside .onChange like this:
@State var duration = ""

TextField(...)
  .onChange(of: duration, perform: { value in
    //Save duration using my view model
    model.saveDuration(flight: $flight, duration: duration)
  })
  .onAppear(){
    //Get value
    duration = flight.duration.timeDisplay //"timeDisplay" is my conversion Int extension.
  }

This works great, but it relies on onAppear to keep its value updated. So if the duration changes in my Realm, the UI won't update unless the user causes the view to appear again.
Attempt 2
I've tried creating a custom binding and I set the binding's value from the Realm property, and then save it in the setter. This behaves erratically as the user types because the value is saved and updated before they can finish typing.
For example, if they type 1. then it quickly saves it as 1 hour and then the value updates to 1.0 before they can finish typing 1.5.
private var durationBinding: Binding<String> {
  Binding<String>(get: {
    //Set binding value
    flight.duration.timeDisplay
  }, set: {
    //Save
    model.saveDuration(flight: $flight, duration: $0)
  })
}

How can I get the benefits of binding to a String Realm property while still having the value convert to/from an Int?


text:
Q: Need marquee text but in which we can stop on mouseover Can you please send it to me in jquery?

A: Try the marquee jQuery plugin.
$('#some-id').marquee().mouseover(function () {
      $(this).trigger('stop');
   }).mouseout(function () {
      $(this).trigger('start');
   });

A: Why can't your use html marquee itself? Its very simple solution with plain javascript.
<marquee direction="left" width="750" height="25" scrollamount="3" scrolldelay="10"
    onmouseover="this._scrollAmount='0'" onmouseout="this._scrollAmount='3'">
Website Hits crossed 1.1 Million, Since 1st March 2006.
</marquee>

Will this help?


text:
Q: Interface implementation is not getting reference My implementation class of interface is not getting referenced at runtime.  Please let me know how to make it work at runtime.  There are no compilation errors
My App's interface is ::
public interface BiometricIntegrationAPI
{
void captureBiometrics(CaptureHandler callback);
}

My App's interface implementation is in.sampleapp.BiometricIntegrationImpl.Java
public final class BiometricIntegrationImpl implements BiometricIntegrationAPI {

    @Override
    public void captureBiometrics(final CaptureHandler callback){
        // TODO...
    }
}

I tried to instantiate the object using:
biometricIntegrationAPI = (BiometricIntegrationAPI) Class.forName("in.sampleapp.BiometricIntegrationImpl").newInstance();

When I run my app, it is unable instantiate & unable to find reference to object  BiometricIntegrationImpl though there is BiometricIntegrationImpl.java file which has the class defined & methods related

A: Without the compiler/runtime output we're guessing here, but you posted
biometricIntegrationAPI = (BiometricIntegrationAPI) Class.forName("in.sampleapp.BiometricIntegrationImpl").newInstance();

Hopefully, there is
BiometricIntegrationAPI biometricIntegrationAPI = null;

somewhere above the Class.forName() call.   But very likely your runtime CLASSPATH cannot find the class, or cannot find the jar with in.sampleapp.BiometricIntegrationImpl


text:
Q: JavaScript Promises mongoose and bluebird missing catch and fail I've started using promises, I use Node.js Mango (with mongoose) and bluebird..
The issue I'm having is for some reason when I chain the mongoose call with functions returning promises (I'm assuming this is the correct way to return and chain) then I get:
typeError: Object #<Promise> has no method 'fail'

if I change the fail to catch then I get the same issue:
typeError: Object #<Promise> has no method 'catch'

what I do is use the function(null, function) pattern which is exactly fail and catch.
However the catch / fail is more readable. Any clue why I'm getting this and how I should resolve this issue?
Here is an example of the code block.
User.findOne({ 'email' :  user_email }).exec()
 }).then (promisedTransformUserSchemaToFrontendObjectWithProjectMapping)
   .then (function (feUser) {
       return new Promise(function (resolve, reject) {
          res.json(feUser);
          return resolve(feUser);
      });
   }).fail/catch  (function (err) {
      console.log(err);
      sendError(res,"failed to get user",err);
   });

And here is the stacktrace:
TypeError: Object #<Promise> has no method 'catch'
    at module.exports.app.put.User.update.email (app\controllers\router.js:165:16)
    at callbacks (node_modules\express\lib\router\index.js:164:37)
    at isLoggedIn (app\controllers\router.js:741:10)
    at callbacks (node_modules\express\lib\router\index.js:164:37)
    at param (node_modules\express\lib\router\index.js:138:11)
    at param (node_modules\express\lib\router\index.js:135:11)
    at pass (node_modules\express\lib\router\index.js:145:5)
    at Router._dispatch (node_modules\express\lib\router\index.js:173:5)
    at Object.router (node_modules\express\lib\router\index.js:33:10)
    at next (node_modules\express\node_modules\connect\lib\proto.js:193:15)

A: I do not know moongose, but in general, functions like fail or catch are convenience shortcuts and are not a part of the promises spec. As such the library does not need to have them to be promises-compliant. Apparently in your case they are not there.
You can achieve same functionality with then(successHandler, rejectionHandler).
In order to handle the promise rejection, you can rewrite your code as follows:
User.findOne({ 'email' :  user_email }).exec()
 }).then (promisedTransformUserSchemaToFrontendObjectWithProjectMapping)
   .then (function (feUser) {
       return new Promise(function (resolve, reject) {
          res.json(feUser);
          return resolve(feUser);
      });
   }).then (undefined, function (err) {
      console.log(err);
      sendError(res,"failed to get user",err);
   });

A: Another way to do it is shown in the bluebird docs:
https://github.com/petkaantonov/bluebird/blob/master/API.md#promiseresolvedynamic-value---promise
You can wrap the mongoose promise in bluebird's Promise.resolve(), and you will get back a bluebird promise.
 Promise.resolve(User.findOne({ 'email' :  user_email }).exec())
 .then (promisedTransformUserSchemaToFrontendObjectWithProjectMapping)
   .then (function (feUser) {
          res.json(feUser);
          return feUser;
   }).fail/catch  (function (err) {
      console.log(err);
      sendError(res,"failed to get user",err);
   });

A: mongoose 4.1+ maintainer suggestion:
es2015 (es6):
require('mongoose').Promise = Promise;

bluebird:
require('mongoose').Promise = require('bluebird');

Q:
require('mongoose').Promise = require('q').Promise;

A: It seems that the problem was mixing the two types of promises (bluebird and mongoose)..
Once I used the promsifyAll on the db object, the catch started to work..

// promisify all model using mongoomise..
require('../../mongoomise').promisifyAll(mongoose, require('bluebird'))


text:
Q: What happens if no Device Shadows concept in AWS IoT I am trying to work on AWS IoT.. From my understanding aws shadow copy the state information of the device/thing.. but i don't understand why.. what happen if its not stored any device state information ??  I will be happy if anyone explains with simple example

A: Device shadow is basically a copy of state of your device in the cloud. What it allows you to do is to make state changes on the device even when the device is disconnected from the network. Those changes are made on its shadow and once the device reconnects with cloud, states of the device and the shadow are synchronized.
Suppose that you have a smart lightbulb which is currently on. You configured your system in such a way that the lightbulb should be turned off at 6am but there is network outage at 5:55am which lasts for 10 minutes. If you are not using device shadow, then the state change will try to reach your lightbulb but since it is disconnected at that particular time, the message is lost and your lightbulb will not be turned off.
If you are using device shadow, this state change is performed on it so the shadow lightbulb will be turned off at 6am even if the real one is not connected to the cloud. When the lightbulb is reconnected at 6:05am, device shadow sends synchronization message to it and it will be turned off.
If you could ensure that your devices are always connected to the cloud, which you can't because networks are inherently unreliable, then using device shadow would be pointless. Bottom line is that it allows you to perform offline state management with automatic synchronization.


text:
Q: How do you obtain the astrometric RA and Dec for earthsatellite objects Below is an example provided in the Pyephem documentation:
    iss = ephem.readtle("ISS (ZARYA)","1 25544U 98067A   03097.78853147  .00021906  00000-0  28403-3 0  8652","2 25544  51.6361  13.7980 0004256  35.6671  59.2566 15.58778559250029")
    gatech = ephem.Observer()
    gatech.lon, gatech.lat = '-84.39733', '33.775867'
    gatech.date = '2003/3/23'
    iss.compute(gatech)
    print iss.rise_time, iss.transit_time, iss.set_time
    2003/3/23 00:00:44 2003/3/23 00:03:22 2003/3/23 00:06:00

I have obtained the exact same result when I run the example, so I expect that I am doing at least this part correct.  What I want to find out is the astrometric position of the satellite in J2000 coordinates, so I can compare it against a star chart.  I tried the following code and the answer is dubious since a_ra and ra are identical.  I believe both a_ra and ra are given in the epoch-of-date instead of the a_ra being the astrometric solution in J2000.
    print iss.a_ra, iss.ra, iss.g_ra
    8:50:10.99 8:50:10.99 6:54:40.64

Is there a way to apply the precession/nutation to the topocentric ra and dec in pyephem?

A: Excellent question! Having reviewed the C code that underlies PyEphem, it looks like both the ra and a_ra values are already precessed to the epoch of your observer object (which in your case is the default of J2000). For your reference, this is the libastro code in question from earthsat.c:
if (epoch != EOD && mjd != epoch)
    precess (mjd, epoch, &ra, &dec);
op->s_ra = ra;
op->s_dec = dec;

It looks to me like this .ra and .dec value are already precessed. Letting this code stand was probably an omission on my part; it is likely that what I really ought to have done, but failed to see at the time, was to move those assignment statements to a position before the if statement, so that they would be un-precessed and therefore distinct from the astrometric RA and dec that get set a few lines later by code that I myself added.
So: for the moment, you are actually — if I am understanding PyEphem correctly — getting exactly the RA and dec you want, and can proceed with your project. Meanwhile, I will pursue that ticket and try to get .ra and .dec to start giving different numbers than .a_ra and .a_dec!


text:
Q: NIntegrate crashes kernel I am trying to evaluate numerically an integral of a function which depends on some parameters which I need to vary within a given range. Here are the definitions I use:
m2[x_, m02_, l2_, p_] = m02/(1 + (x/l2)^(1 + p));
f[x_, a_, b_, m02_, l2_, p_] = b x Exp[-a x] + m2[x, m02, l2, p];
suppr[x_, as_, bs_] = x* bs*Exp[-as*x];
newf[x_, as_, bs_] = (1 + suppr[x, as, bs]) f[x, Rationalize[0.180],
Rationalize[-0.719], Rationalize[0.371^2], Rationalize[0.634],
Rationalize[0.1]];
newD[x_, as_, bs_] = 1/(x + newf[x, as, bs]);
newuD[x_, as_, bs_] = newD[x, as, bs] newf[x, as, bs];

So the final function I need to integrate is s Log[1 - newuD[s, as, bs]] in the interval {s,0,Infinity} (this function is well behaved in this interval); for this purpose I have defined:
newq[as_, bs_, wpr_] := NIntegrate[s Log[1 - newuD[s, Rationalize[as],
Rationalize[bs]]], {s, 0, Infinity}, MaxRecursion -> 50,
WorkingPrecision -> wpr]

Here is the problem. For as=bs=0 I can select any working precision I want:
In[1]:= newq[0, 0, 6]
Out[1]= 24.1143
In[2]:= newq[0, 0, 7]
Out[2]= 23.75709
In[3]:= newq[0, 0, 10]
Out[3]= 23.75711286

However, if I choose non-zero values for the parameters I can get a result selecting working precision 6:
In[4]:= newq[0.1, 0.129, 6]
Out[4]= 34.8776

But selecting a higher precision (which I need) invariably crashes the kernel and does not return any result. I am running on version 11.0.1 for Mac OS X x86 (64-bit).
Any idea/workaround?

A: Problems arise due to overflow with E^s in numerator and denominator.
First calculating the terms with that E^s... and than taking Log helps as workaround.
NIntegrate[logint = newuD[s, 0, 0];
   s Log[1 - logint], {s, 0, \[Infinity]}, WorkingPrecision -> 40,
         MaxRecursion -> 100]

(*   23.75712157250552910577356711075917849924   *)

NIntegrate[logint = newuD[s, 1/10, 129/1000];
   s Log[1 - logint], {s, 0, \[Infinity]}, WorkingPrecision -> 40,
      MaxRecursion -> 100]

(*   34.52101133437542508965238453435432822158   *)


text:
Q: Jackson automatically converting json date to 8 hours ahead of its time In my json date is represented like this :-
"from":"2015-11-11T09:21:00.00Z"

But when it gets converted to java.sql.Timestamp it looks like this :-
 2015-11-11 17:21:00.0

My timezone is Singapore . It is 8 hours ahead of UTC timezone and coincidentally the date also gets converted to 8 hours ahead of its time.

A: They are showing the same times, just formatted differently for the different locations.  The time you are taking in is UTC/GMT.  What you are viewing in your IDE is showing the local time stamp formating, but they are the same values and points in time.
If it really matters how it is displayed to you in the debugger you can use a Calendar object instead of a TimeStamp and set the locale value to be UTC and it will format them the same way, but again they are the same values.

I don't want the Timestamp in java to be different from json

It is not different, the display format is different do to the location setting but they are the same values just represented differently.
P.S.   Be aware that if your server is set to a different time zone than your work station it will show a different format as well, but it again will be the same time just represented differently.


text:
Q: Exponential PDF, infinite bounds The Question
Let $f(x, y) = e^{-x-y}$, $0 < x < \infty$, $0 < y < \infty$, $0$ elsewhere, be the probability density function of $X$ and $Y$. Then if $Z = X + Y$, compute $\Pr(Z \le 0)$, $\Pr(Z \le 6)$, and, more generally, $\Pr(Z \le z)$, for $0 < z < \infty$. What is the probability density function of $Z$?
My Attempt
I started by setting up the double integral
$$\int_0^\infty \int_0^ \infty e^{-x-y} \, dx dy + \int_0^\infty \int_0^ \infty e^{-x-y} \, dy dx$$
But this doesn't look correct (and may not even be integrable). I suspect the integrals done for $X$ and $Y$ are basically the same but in some way have $X$ and $Y$ swapped in each, but I could be wrong. (As a side note, I do not believe this problem involves a transformation, as bivariate transformations are not discussed until the next chapter of the book.
If it helps, the book provides $ze^{-z}, \quad 0 < z < \infty$ as the solution, presumably for the pdf.

A: This should not be the sum of two integrals. If we are looking for $P(Z \leq z) = P(X+Y \leq z)$ then we have the condition that $x+y \leq z$ or equivalently $0 \leq x \leq z - y$.
Then our bounds of integration become
$$
\int_0^z \int_0^{z-y} e^{-x-y} dx dy.
$$
This should be straightforward to integrate if you are comfortable with double integrals.

A: For $z >0$,$P\{Z \leq z\}=\int_0^{z} \int _0^{z-x} e^{-x-y} \, dy\, dx=\int_0^{z}e^{-x}(1-e^{x-z})\, dx=1-e^{-z}+ze^{-z}$. Differentiate to get the density.


text:
Q: CSS animation: pausing I have a simple CSS3 animation which I would like to pause on hover.
Here is a simplified version:
h1 {
    animation-name: test 3000ms infinite alternate;
}
@keyframes test {
    from {
        transform: translate(0,0);
    }
    to {
        transform: translate(100px,0);
    }
}
h1:hover {
    animation: paused;
}

It works, but pausing means jumping back to the 0% state. Is there a way to either (a) pause in the current state of (b) resetting more gracefully, such as running through one final loop?
Thanks

A: Use animation-play-state as below:
h1 {
    animation-name: test;
    animation-duration:3000ms;
    animation-iteration-count: infinite;
    animation-direction: alternate;
    animation-play-state:running;/*running normally*/
}

h1:hover {
    animation-play-state:paused; /*paused when hover*/
}

DEMO

Note -  The animation-play-state property is not supported in Internet Explorer 9 and earlier versions.


text:
Q: Wagtail customize PageChooserPanel page explorer view I'm looking for a way to customize the Explorer that pops-up when using the PageChooserPanel, ideally I would like to add two more columns there.
I've found this http://docs.wagtail.io/en/v2.2/reference/hooks.html#choosers but that only covers generating a custom queryset not adding columns, is that even possible?
Alternatively I can live with only changing the default title shown on the pagechooserpanel explorer but so far adding a __str__ method to the class hasn't worked
Here a graphic representation to my question

A: You can customise the displayed title by overriding your page model's get_admin_display_title method:
https://docs.wagtail.io/en/stable/reference/pages/model_reference.html#wagtail.core.models.Page.get_admin_display_title


text:
Q: Cannot Autowire Spring Batch Itemreader,writer I am trying to create a batch configuration class but i couldnt inject this fields idk why class annotations :
@Configuration
@EnableBatchProcessing
@Component
public class SpringBatchConfig {

and here is code

     @Bean
    public Job job(JobBuilderFactory jobBuilderFactory,
                   StepBuilderFactory stepBuilderFactory,
                   ItemReader<Object> personItemReader,
                   ItemProcessor<Object, Person> itemProcessor,
                   ItemWriter<Object> personItemWriter
                   ){

        Step step = stepBuilderFactory.get("ETL-File-Load")
                .chunk(100)
                .reader(personItemReader)
                .writer(personItemWriter)
                .build();
        Job job = jobBuilderFactory.get("ETL-Load")
                .incrementer(new RunIdIncrementer())
                .start(step)
                .build();

    return job;

and this is the full error :
Parameter 2 of method job in com.emir.batchjobtest.config.SpringBatchConfig required a bean of type 'org.springframework.batch.item.ItemReader' that could not be found.

Action:

Consider defining a bean of type 'org.springframework.batch.item.ItemReader' in your configuration.

Process finished with exit code 0


text:
Q: Best way to do multiprocessing? What might be the best way to use multiprocessing in which the results of each process is required in the main process?
Suppose, I have a list of students id. For each student, I need to apply the operation like reading the student's data and calculating the overall results of the student. Each process then stores the end results to the multiprocessing manager dictionary. The dictionary will be then processed in the main process to and saved to the database.
import multiprocessing as mp

def main():
    manager = mp.Manager()
    student_dict = manager.dict()
    processes = []
    for student_id in student_ids:
       process = multiprocessing.process(target=process_student,
                                      args=student_dict)
       processes.append(process)
       process.start()

    for key, value in student_dict.items():
         #save to db

for process in processes:
    process.join()

def process_student():
    read_student()
    calculate_student_results()

def read_student():
    #operation

def calculate_student_results():
    #operation
    student_dict[key] = value

I am worried if this is the right way to do because in many tutorials they say not to use the shared state and use the queue. But when I used the queue the process hanged. might be because of the huge number of results in the queue.
Can I do this way or should I use any another way for multiprocessing? Also is there any chance of deadlock in the process.


text:
Q: When using P-splines to fit data, does the dataset need to be divided into validation set and testing set? I am doing the curve fitting by p-splines(with the basis b-splines) in a 1D dataset. I am struggling that in almost every regression model, it is essential to divide the dataset into a validation set and a testing set, to see if the data fits well or over-fitting. But in p-splines(#mgcv# in R), it is using GCV or AIC to control the location and numbers of knots to prevent the over-fit and generate the best lambda(or knots). In this situation, I am not quite sure if it needs to divide the dataset. If it needs, what's the difference between dividing dataset and not dividing dataset? Cause I read the paper and it said the penalty would help to prevent the over-fit.
And how to test if the fit is good or not? Due to the GCV only tells that I've chosen the best result in this model.
I tried using #mgcv# packages in R to do the fitting. And the codes are as follows:
dataset <- read.csv("bsplinesforR.csv", header = TRUE)

x <- dataset[,2]
y <- dataset[,4]
vdist <- hdist <- 0.2
layout( matrix(1:4, 2, 2, byrow=TRUE), widths=c(10,10), heights=c(10, 10))
par(mar= c(vdist, 4, 3, hdist))

library(gamlss)
gamlss.ps<- gamlss( y~pb(x), control=gamlss.control(trace=FALSE))
detach("package:gamlss")
library(mgcv)
mgcv.ps <- gam(y~s(x,bs="ps"), method = "GCV.Cp")
t.gl <- predict(gamlss.ps)
t.g <- predict(mgcv.ps)
lines(x, t.gl,col=2, lwd=2)
lines(x, t.g,col=3, lwd=2)
legend(5, 600, c("Real", "gamlss", "mgcv"), col=c(1, 2, 3), lty=c(2, 1, 1), bty="n")
layout(matrix(1, 1, 1))
legend("topright", "p-splines: default values", col=1 ,lty=0, bty="n")

Family: gaussian
Link function: identity

Formula:
y ~ s(x, bs = "ps")

Parametric coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)  327.182      4.945   66.17   <2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Approximate significance of smooth terms:
       edf Ref.df     F p-value
s(x) 5.294  6.123 214.5  <2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

R-sq.(adj) =  0.961   Deviance explained = 96.4%
GCV = 1518.4  Scale est. = 1344.7    n = 55

A: GCV is the default way of selecting smoothness parameters in mgcv. It is one of several methods for doing this. GCV is the default because this was the best option available when Simon Wood was developing his ideas for estimating GAMs via penalized splines. Research results since then have shown that GCV can undersmooth data as the profile of the GCV score can become very flat around the optimal score; slight variations in the data drawn from a known model could yield very different selected values for smoothness parameters due to the flatness of the GCV score profile.
REML or ML smoothness selection, wherein the GAM is estimated as a mixed effects model with smoothness parameters related to the random effects variance parameters, have both been shown to work better than GCV, being far less sensitive to undersmoothing. You should ideally be fitting GAMs in mgcv using method = "REML" or method = "ML".
In most applications of GAMs fitted using mgcv, you wouldn't split-sample your data. Or at least you'd have to be very careful how you do it, because you have to create bases from the covariate(s) and you'd want to be careful not to extrapolate. There are also some other issues; CV a GAM takes a lot of time, and the process isn't invariant to orthogonal transformations of the covariates.
There are ways to get smoother models if you worry about overfitting. One is to apply the one standard error rule, wherein we choose smoothness parameters that are within one standard error of the selected value. See ?one.se.rule for how to do this.
Another option is double cross-validation; use GCV and set gamma = 1.5. In this procedure, what is happening is that smoothness parameters are chosen to minimise the difference between the predicted values for the response where those observations are included in the model and when they are excluded; i.e. choose smoothness parameters in such a way as to minimise the change in the model when you include observations in the model.


text:
Q: If greater than or equal in MIPS Prompt for and input two integers "a" and "b" using syscalls
Display one of the following statements depending on if a>b, or a=b or a

*

*You entered a greater than b

*You entered an equal to b

*You entered a less than b
I have to get this prompt and I tried so hard to get it done. This is where I'm stucked, I'd really appreciate your help.
    .data
p1: .asciiz "Please enter the first number ? "
p2: .asciiz " Please enter the second number? "
ans1: .asciiz " \nYou entered a greater than b "
ans2: .asciiz " \nYou entered a equal to b "
ans3: .asciiz " \nYou entered a less than b "

        .text
        .globl main

main:
    li $v0, 4     #system call code for print_str
    la $a0, p1  #address of string to print
    syscall     #print the first prompt

    li $v0, 5   #system call code for read_int
    syscall     #read first integer
    move $t1, $v0   #store it till later

    li $v0, 4   #system call code for print_str
    la $a0, p2  #address of string to print
    syscall     #prints the second prompt

    li $v0, 5   #system call code for read_int
    syscall     #read first integer
    move $t2, $v0   #store it till later

    slt $t1,$s1,$s0      # checks if $s0 > $s1
    beq $t1,1,label1

I really don't know how to use branch statements, and it's really confusing. I would like to know how to fix it.

A: Why do you read the numbers into $t1 and $t2 then compare $s1 and $s0? Where is it confusing?
Simply use slt and beq/bne, that'll cover all comparison cases you need.
Suppose a is in $s0, b is in $s1

*

*a < b:
slt $t0, $s0, $s1
bne $t0, $zero, a_lt_b # $t0 == 1 != 0 if a < b

*a = b:
beq $s0, $s1, a_eq_b   # nothing more to explain

*a > b:
slt $t0, $s1, $s0
bne $t0, $zero, b_lt_a # $t0 == 1 != 0 if b < a

*a >= b:
slt $t0, $s0, $s1
beq $t0, $zero, a_ge_b # $t0 == 0 if a >= b or !(a < b)

*a <= b:
slt $t0, $s1, $s0
beq $t0, $zero, b_ge_a # $t0 == 0 if b >= a or !(b < a)


text:
Q: Simplest way to register an MBean (JMX) in JBoss Fuse Fabric? I've written a custom MBean for my service running in JBoss Fuse Fabric (v7.2.0.redhat-024)

*

*Interface: com.mycompany.myservice.MyServiceManagerMBean

*Implementation class: com.mycompany.myservice.MyServiceManager
What is the simplest way for my MBean to be registered or "discovered" by JBoss Fuse?
I tried adding the following to my blueprint.xml, but it doesnt seem to work:
<bean id="org.apache.cxf.management.InstrumentationManager" class="org.apache.cxf.management.jmx.InstrumentationManagerImpl">
    <property name="enabled" value="true" />
    <property name="bus" ref="cxf" />
    <property name="usePlatformMBeanServer" value="true" />
</bean>

I run JBoss Fuse Fabric with the profile that deploys my services, I fire up JConsole and I connect to the first Local Process named org.apache.karaf.man.Main (there are 2 of them).
Yet I cant find my MBean - I'm expecting to see com.mycompany.myservice on the MBean tab, but it isn't there.
In contrast, I can see all of my datasource jmx beans under this tree node:
com.mycompany.anotherservice.datasources.
However the datasource MBeans were configured by setting jmxEnabled=true, so I am none the wiser about how to configure and expose my own MBean.
Could someone please tell me what I need to do here?
Thanks in advance.

A: And here is a way to do this in the JBoss Fuse blueprint.xml configuration
<bean id="mbeanRegistrer" class="org.apache.karaf.management.MBeanRegistrer" init-method="init">
    <property name="bundleContext" ref="blueprintBundleContext"/>
    <property name="mbeans">
        <map>
            <entry value="com.mycompany.myservice:type=admin,name=myadminBean" key-ref="myadminBean"/>
        </map>
    </property>
</bean>

Thanks to my colleague Y.H. for help :)

A: I received the following code snippet which should solve this problem.
First, you inject the cxf bus into a bean in blueprint.xml via <property name="bus" ref="cxf"/> and use it to register the bean with the InstrumentationManager:
    MyMBean mbean = new MyMBeanImpl();
    InstrumentationManager imanager = bus.getExtension(InstrumentationManager.class);
    final ObjectName objectName = new ObjectName("org.apache.cxf:type=foo,name=bar");
    imanager.register(mbean, objectName);

I am still having problems with this, bus.getExtension(InstrumentationManager.class) returns null, but I am told this is the proper solution...


text:
Q: Maven Compilation Error using Spring Boot with Cassandra I am setting up a Spring Boot application with Cassandra repository. Maven has gone rogue though, because the application stopped compiling. Spring Data Cassandra is not getting handled properly. Everything in "org.springframework.cassandra.core.mapping" does not exist locally. And it looks like I have other packages "...cassandra.core" that are OK.
Cassandra bean mapping classes like @Table, @Column, etc. fail with "cannot find symbol" in Maven compilation. I tried cleaning, and even tried deleting my ./.m2/repository, but it cannot compile. I expect some version mismatch must be happening, or it could be time to start using Gradle.
I have run "jar tvf spring-data-cassandra-1.5.9.RELEASE.jar | grep 'mapping'" and the mapping.* classes are all present. Yet, "mvn clean compile" results in multiple homogeneous errors of:

[ERROR]
  /media/kevvurs/ExtraDrive1/winshare/workspace/FPSJobsRedesign/FPSDistributionFilter/src/main/java/com/shc/scinventory/dfilter/data/DcUnitInfoBean.java:[4,55]
  package org.springframework.data.cassandra.core.mapping does not exist

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.sample.app</groupId>
<artifactId>Filter</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>Filter</name>
<description>Command-line tool</description>
<properties>
    <maven.antrun.plugin.version>1.7</maven.antrun.plugin.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <jdk.version>1.8</jdk.version>
</properties>
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.9.RELEASE</version>
</parent>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-cassandra</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>com.beust</groupId>
        <artifactId>jcommander</artifactId>
        <version>1.72</version>
    </dependency>
    <dependency>
        <groupId>org.testng</groupId>
        <artifactId>testng</artifactId>
        <version>6.8.13</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.assertj</groupId>
        <artifactId>assertj-core</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.17</version>
            <dependencies>
                <dependency>
                    <groupId>org.apache.maven.surefire</groupId>
                    <artifactId>surefire-testng</artifactId>
                    <version>2.17</version>
                </dependency>
            </dependencies>
            <configuration>
                <groups>dev</groups>
            </configuration>
            <executions>
                <execution>
                    <phase>test</phase>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

A: Solved
I was integrating a class that uses a different, non-Boot, configuration of Spring. I had tried importing @Table and other Spring Data annotations from: org.springframework.data.cassandra.core.mapping.Table when it is provided in org.springframework.data.cassandra.mapping.Table for when using spring-boot-starter-data-cassandra.
Conclusion
I sometimes depend too much on Intellij and tools for refactoring and auto-completing things. The problem would have been obvious if I had paid more attention.


text:
Q: How to add time to the current time? I have an initial time 12:00:00 and I need to add 144 mins to it.
The expected output is 15.24.00 (i.e, adding 2.24 hours to the initial time).
How should I update the current code given below ?
String startTime = "13:00:00";
SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss");
Date date1 = null;
Date date2 = null;
try {
    date1 = format.parse(startTime);
} catch (ParseException e) {
    e.printStackTrace();
}
Long addition = (long) (TimeUnit.MILLISECONDS.toMinutes(date1.getTime()));
System.out.println("Difference : "+addition);

A: You should use a modern date-time API as follows :
import java.time.Duration;
import java.time.LocalTime;

public class Main {
    public static void main(String[] args) {
        LocalTime time = LocalTime.parse("13:00:00").plus(Duration.ofMinutes(144));
        System.out.println(time);
    }
}

Output:
15:24

Check here for more information.

A: Step 1:
Convert input String to java.util.Date via implementing the following logic:
public static Date getDate(String source, String format) throws ParseException {
    DateFormat dateFormat = new SimpleDateFormat(format);
    return dateFormat.parse(source);
}

Step 2:
Adding minutes to the date:
    public static Date add(Date date, int minute) {
       Calendar calendar = Calendar.getInstance();
       calendar.setTime(date);
       calendar.add(Calendar.MINUTE, minute);
       return calendar.getTime();
    }

Step 3:
Now, If you want to convert java.util.Date back to String use following logic:
    public static String getDate(Date date, String format) {
       DateFormat dateFormat = new SimpleDateFormat(format);
       return dateFormat.format(date);
    }

A: You can do it in the below way:
String str = "13:00:00";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("kk:mm:ss");
LocalTime dateTime = LocalTime.parse(str, formatter).plusMinutes(144);
System.out.println(dateTime);


text:
Q: EF 6.1 Code First - the number of columns specified must match the number of primary key columns I am running into the following error while trying to migrate a database in Entity Framework.
The specified association foreign key columns 'question_set_id' are invalid. The number of columns specified must match the number of primary key columns.
I dropped the original primary key QuestionSetId and created a composite key relationship. The columns in the composite key relationship also map to foreign keys. I'm not sure what the issue is.
Here is the associated entity.
public class QuestionSet
{
    [Key, Column(Order = 1)]
    public long TitleId { get; set; }

    [ForeignKey("TitleId")]
    public virtual Title Title { get; set; }

    [Key, Column(Order = 0)]
    public long ReviewCycleId { get; set; }

    [ForeignKey("ReviewCycleId")]
    public virtual ReviewCycle ReviewCycle { get; set; }

    public virtual List<Question> Questions { get; set; }
}

The DbContext has:
    modelBuilder.Entity<QuestionSet>()
            .HasMany(c => c.Questions)
            .WithMany(c => c.QuestionSets)
                .Map(x => x.ToTable("QUESTION_SET_QUESTION")
                    .MapLeftKey("question_set_id")
                    .MapRightKey("question_id"))
        ;

A: The QuestionSet has two keys, but the MapLeftKey of QuestionSet only spefified one key.
MapLeftKey("question_set_id")

Replace it with something like this:
MapLeftKey(new []{ "question_set_review_cycle_id", "question_set_title_id" })

The first key is ReviewCycleId (Column's Order 0), the second key is TitleId (Column's Order 1).
It should fix the problem, unless the Question also has two keys.


text:
Q: Retrieve posts by page in wp rest api I want to develop an app for my WordPress.org website. I am using wp rest api to receive post in json. My question is how do I retrieve posts page by page. For example if there are 50 posts I want to receive 1-10 then 11-20 and so on.

A: Well, you can add ?page={$page_number} to the URL that you're requesting.
See, for example, http://demo.wp-api.org/wp-json/wp/v2/posts/?page=2.
It appears to split the posts into pages of 10.
Reference

*

*WP-API documentation (I found this in the docs for v1 of the API, but per the sample URL above, it works on v2 as well)


text:
Q: Dozer - From List of entities to list of entities' id I have a domain object called User:
public class User {
    private long id;
    private String username;
    private String email;
    private List<Profile> profiles;

    // getters & setters
}

And I have the related DTO (UserDTO) which is
public class UserDTO {
    private long id;
    private String username;
    private String email;
    private List<Long> profilesId;

    // getters & setters
 }

I'd like to use Dozer to convert from domain object to DTO. The Profile class has a property
Long id;

What I want is that Dozer takes the profile's id for each profile in the list and save it in the DTO's list. Can I do something like that? Do I have to use custom converters?
Here's my actual mapping file
<mapping>
    <class-a>common.model.User</class-a>
    <class-b>common.model.dto.UserDTO</class-b>
    <field>
        legalEntity.id
        legalEntityId
    </field>
    <field type="one-way">
        profiles.id
        profilesId
    </field>
</mapping>

A: Solved
just add to the source class this method
public List<Long> getProfilesId() {
    List<Long> profilesId = new ArrayList<Long>();
    for(Profile p : this.profiles) {
        profilesId.add(p.getId());
    }
    return profilesId;
}

and to the mapping file
<field type="one-way">
    profiles
    profilesId
</field>

which says Dozer which method use to make the conversion.


text:
Q: How can I increase speed of vehicles in Veins? I am using OMNeT++ 5.4.1, Veins 7.4.1, and SUMO 0.30.0.
As the maximum speed of vehicles in Veins is 13.99, I really want to increase it up to 33. How can I do it? is it possible in Veins or should I do it in SUMO?

A: You may need to modify the network. Probably the vehicles are only allowed to drive 50 km/h (about 13.99 m/s considering the deviations allowed by the models) on the streets you are looking at. Use SUMO's netedit to edit the maximum edge speeds.


text:
Q: DVWA sql injection I have a question about commenting out the sql query.
The sql query has that form $query  = "SELECT first_name, last_name FROM users WHERE user_id = '$id';";
So i try that 1' or 1=1;  # and i get all the users and passwords as i expected but when i use -- for a comment instead of # i get a syntax error. Why is that happening ? Can you explain how is the sql formed in each case ? Also i notice 1' or 1=1  # works too. The # symbol doesnt comment out the ; ?

A: As you can read in the mysql manual:

In MySQL, the --  (double-dash) comment style requires the second dash to be followed by at least one whitespace or control character (such as a space, tab, newline, and so on)

When adding only -- to your input... there is no whitespace or control character following. Your synthesized query would look like that:
SELECT first_name, last_name FROM users WHERE user_id = '1' or 1=1--';

As you can see, the double dash is followed immediately by a ; which leads to a syntax error as it is not considered a comment.
Try putting in -- (with a trailing whitespace) at the end
For the ;: It is not necessary in a query issued to the server. This is only to separate different statements but with a single statement not required at all.
The mysql command line client does not send that character to the server but treats it as an "execution instruction".


text:
Q: Alter vs Modify vs Change (in Legal Documents) Consider the quote from "What is a Grantor Trust" article.

This trust is revocable, which simply means it can be altered, modified, and otherwise changed or even terminated during the life of the grantor, provided that the grantor has full mental capacity.

As far as I could figure out from other forums words "alter" and "modified" mean "to change slightly", and "change" is more generic word and may also mean "replace" or "exchange for something else". The text in bold sounds to me like "it can be slightly changed, slightly changed, and otherwise changed". Are there some differences in meaning between "alter" and "modify" in this context or in general? Are they generally interchangeable?

A: The following information is culled from the website uslegal.com
Alter is defined as "to cause to become different in some particular characteristic . . . without changing into something else." United States v. Kilbride, 2009 U.S. App. LEXIS 23722 (9th Cir. Ariz. Oct. 28, 2009)
Modification means "any alteration in the terms and conditions of a contract, including supplemental agreements, amendments, and extensions."

A: It's your typical legalese. You'll note that lawyers love to use such legal doublets (cease and desist, furnish and supply, e.g.) or triplets (cancel, annul and set aside, e.g.) which for the rest of us are simple synonyms and thus pleonasms.


text:
Q: Freeing memory with a struct pointing to another struct I have seen this topic a few times on here but couldn't quite find the information to help me out. I am trying to get better with freeing memory for my programming class. I have the below code to allocate some memory, but don't quite understand how to free it. I take the number of members, allocate that many members, then allocate the number of wines each member has rated, and store information for each wine they have rated in another struct linked through my member one.
How do I free memory for this specific style of program?
I commented out the printf statements for showing the information input into the program. Any help appreciated.
#include <stdio.h>
#include <stdlib.h>

typedef struct wine {
    char type[20];
    char brand[20];
    int rating;
} wine;

typedef struct member {
    char name[20];
    int numRated;
    wine* list;
} member;

int main()
{
    int n;

    scanf("%d", &n);

    member *members = malloc(n * sizeof(member));

    for(int i=0; i<n; i++){
        scanf("%s", (members+i)->name);
        scanf("%d", &(members+i)->numRated);
        (members+i)->list = malloc((members+i)->numRated * sizeof(wine));

        for(int j=0; j<(members+i)->numRated; j++){
            scanf("%s", (members+i)->list[j].type);
            scanf("%s", (members+i)->list[j].brand);
            scanf("%d", &(members+i)->list[j].rating);

        }
    }

    // for(int i=0; i<n; i++){
    //     printf("%s: %d\n", (members+i)->name, (members+i)->numRated);
    //     for(int j=0; j<(members+i)->numRated; j++){
    //         printf("Type:%s  Brand: %s  Rating: %d\n", (members+i)->list[j].type, (members+i)->list[j].brand, (members+i)->list[j].rating);
    //     }
    //     printf("\n");
    // }

    return 0;
}

Edit: Put in an explicit question.

A: Solution:
At the bottom of your code, you would first free the wine ratings for each member and then free the member list itself:
for (int i = 0; i < n; i++) {
    free(members[i].list); // Or free((members + i)->list;
}
free(members);

In general, you should have a matching call to free for each call to malloc.
A little more explanation:
The first call to malloc allocates a single block of memory to hold n members' information. Even though this block of memory can store n members' information, it is still just a single block of memory and will be freed with a single call to free.
In your loop, you allocate a block of memory for each member (n times) that will store their wine ratings' information. Even if a member has many wine ratings, there is still just one block of memory for that member's wine ratings, so you'll need as many calls to free as there are members with wine ratings.
Also, notice how the calls to free happen in reverse order of the calls to malloc. This makes sense intuitively, you would want to free members[i].list before you free members.


text:
Q: vImageConvert to extract one channel How can i "extract" only one channel from an image using vImage?
My approach right now is:
vImage_Buffer redBuffer;
redBuffer.data = (void*)redImageData.bytes;
redBuffer.width = size.width;
redBuffer.height = size.height;
redBuffer.rowBytes = [redImageData length]/size.height;
vImage_Buffer redBuffer2;
redBuffer2.width = size.width;
redBuffer2.height = size.height;
redBuffer2.rowBytes = size.width;
vImageConvert_RGB888toPlanar8(&redBuffer, &redBuffer2, nil, nil, kvImageNoFlags);

redBuffer is a working image, no errors with it, but vImageConvert gives me an EXC_BAD_ACCESS, i've tried many options and some lead to an EXC_BAD_ACCESS and some to a broken output image. What am i doing wrong?
So thanks to Rob Keniger i've managed to extract the channels, but if i try to put them back together with other channels, the images get stretched horizontally and have RGB stripes in it. Why aren't they put back together correctly? Here an example with extracting the channels and then putting them back together:
    vImage_Buffer blueBuffer;
    blueBuffer.data = (void*)blueImageData.bytes;
    blueBuffer.width = size.width;
    blueBuffer.height = size.height;
    blueBuffer.rowBytes = [blueImageData length]/size.height;

    vImage_Buffer rBuffer;
    rBuffer.width = size.width;
    rBuffer.height = size.height;
    rBuffer.rowBytes = size.width;
    void *rPixelBuffer = malloc(size.width * size.height);
    if(rPixelBuffer == NULL)
    {
        NSLog(@"No pixelbuffer");
    }
    rBuffer.data = rPixelBuffer;

    vImage_Buffer gBuffer;
    gBuffer.width = size.width;
    gBuffer.height = size.height;
    gBuffer.rowBytes = size.width;
    void *gPixelBuffer = malloc(size.width * size.height);
    if(gPixelBuffer == NULL)
    {
        NSLog(@"No pixelbuffer");
    }
    gBuffer.data = gPixelBuffer;

    vImage_Buffer bBuffer;
    bBuffer.width = size.width;
    bBuffer.height = size.height;
    bBuffer.rowBytes = size.width;
    void *bPixelBuffer = malloc(size.width * size.height);
    if(bPixelBuffer == NULL)
    {
        NSLog(@"No pixelbuffer");
    }
    bBuffer.data = bPixelBuffer;

    vImageConvert_RGB888toPlanar8(&blueBuffer, &rBuffer, &gBuffer, &bBuffer, kvImageNoFlags);

    size_t destinationImageBytesLength = size.width*size.height*3;
    const void* destinationImageBytes = valloc(destinationImageBytesLength);
    NSData* destinationImageData = [[NSData alloc] initWithBytes:destinationImageBytes length:destinationImageBytesLength];
    vImage_Buffer destinationBuffer;
    destinationBuffer.data = (void*)destinationImageData.bytes;
    destinationBuffer.width = size.width;
    destinationBuffer.height = size.height;
    destinationBuffer.rowBytes = [destinationImageData length]/size.height;

    vImage_Error result = vImageConvert_Planar8toRGB888(&rBuffer, &gBuffer, &bBuffer, &destinationBuffer, 0);
    NSImage* image = nil;
    if(result == kvImageNoError)
    {
        //TODO: If you need color matching, use an appropriate colorspace here
        CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
        CGDataProviderRef dataProvider = CGDataProviderCreateWithCFData((__bridge CFDataRef)(destinationImageData));
        CGImageRef finalImageRef = CGImageCreate(size.width, size.height, 8, 24, destinationBuffer.rowBytes, colorSpace, kCGBitmapByteOrder32Big|kCGImageAlphaNone, dataProvider, NULL, NO, kCGRenderingIntentDefault);
        CGColorSpaceRelease(colorSpace);
        CGDataProviderRelease(dataProvider);
        image = [[NSImage alloc] initWithCGImage:finalImageRef size:NSMakeSize(size.width, size.height)];
        CGImageRelease(finalImageRef);
    }
    free((void*)destinationImageBytes);
    return image;

A: A solution (or, at least the beginnings of one):
err = vImageExtractChannel_ARGB8888(&_src, &_blu, 2, kvImageNoError);
...
uint8_t copyMask = 1;
vImageOverwriteChannels_ARGB8888(&_blu, &_src, &_dst, copyMask, kvImageNoFlags);

This worked for me, except in the OpenCV version of my in-development iOS camera app; the preview window displays a white stripe on one side, which it does everytime OpenCV doesn't like the way I do something. I don't think that will be your issue, and seeing as it is only three lines of code to your multiplicity of lines, it's worth trying.

A: You're not initialising the redBuffer2 output buffer, so you don't have anywhere to store the output of the function.
//allocate a buffer for the output image and check it exists
void *pixelBuffer = malloc(size.width * size.height);
if(pixelBuffer == NULL)
{
    NSLog(@"No pixelbuffer");
    //handle this somehow
}

//assign the allocated buffer to the vImage buffer struct
redBuffer2.data = pixelBuffer;

A: vImageConvert_RGB888toPlanar8 does not accept NULL pointers for the vImage_Buffer structs.  The function is tagged with VIMAGE_NON_NULL(1,2,3,4) which should be causing your compiler to complain about this usage.
On OS X.10 or iOS 8 vImageExtractChannel_ARGB8888 was added, but there is no RGB888 equivalent. If you need that, you should file a feature request. http://bugreporter.apple.com   In the mean time, you can make three planar8 output buffers and throw two away.


text:
Q: Add fix number/criteria to countif function I have the following Excel spreadsheet:
      A                      B                    C                    D
1                     Purchase Price        Sales Price      Purchase Price > Sales Price
2     Product A            50                    40        ={COUNTIF(B2:B6;">"&C2:C6)}
3     Product B            60                    65
4     Product C            80                    60
5     Product D            10                    20
6     Product E            50                    30

With the formular in cell D2 I detect the number of products where the Purchase Price is higher than the Sales Price. This formula works perfectly. Now, I want to change the formula in cell D2 so it counts the products where the Purchase Price > Sales Price - 10 which in case of Product B would mean that the Sales Price is 65 - 10 = 55 and therefore needs to be counted from the formula in cell D2.
Do you know how I can add this non-tolerance range of 10 to my formula in cell D2?
Thanks for any help.

A: How about:
=SUMPRODUCT(--(B2:B6>C2:C6-10))


text:
Q: Add button control(s) to SplitContainer Splitter Is there any way to display controls (like buttons) on the adjustable splitter that displays between the two panels in a .NET SplitContainer?
Example:

I don't think SplitContainer natively supports this, but overriding the control to get this functionality that seems omni-present in numerous applications seems a bit much to me - I feel like I'm over-thinking this or missing something obvious.

A: Here's an example that uses a TableLayoutPanel to simulate a SplitContainer.
using System;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;

class Form1 : Form
{
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }

    TableLayoutPanel rootPanel;
    float originalWidth;
    int splitPointX;

    public Form1()
    {
        Controls.Add(rootPanel = new TableLayoutPanel
        {
            ColumnCount = 3,
            ColumnStyles =
            {
                // Notice the use of Absolute here as this will control the 'splitting'
                new ColumnStyle(SizeType.Absolute, 120F),
                // Size of button panel
                new ColumnStyle(SizeType.AutoSize),
                // Remaining size
                new ColumnStyle(SizeType.Percent, 100F),
            },
            Dock = DockStyle.Fill,
            RowCount = 1,
            RowStyles = { new RowStyle(SizeType.Percent, 100F) },
        });

        Panel buttonPanel;
        rootPanel.Controls.Add(buttonPanel = new Panel
        {
            Anchor = AnchorStyles.Top | AnchorStyles.Bottom,
            BackColor = SystemColors.ControlDark,
            Margin = new Padding(0),
            MinimumSize = new Size(80, 0),
            Size = new Size(80, 0),
            Controls =
            {
                // UseVisualStyleBackColor = true only because we altered the container's BackColor
                new Button { Text = ">>", Location = new Point(19, 112), Size = new Size(40, 23), UseVisualStyleBackColor = true },
                new Button { Text = ">", Location = new Point(19, 83), Size = new Size(40, 23), UseVisualStyleBackColor = true },
                new Button { Text = "<", Location = new Point(19, 54), Size = new Size(40, 23), UseVisualStyleBackColor = true },
                new Button { Text = "<<", Location = new Point(19, 25), Size = new Size(40, 23), UseVisualStyleBackColor = true },
            },
        }, 1, 0);

        buttonPanel.MouseDown += (s, e) =>
            {
                if (e.Button == MouseButtons.Left)
                {
                    // Capture mouse so that all mouse move messages go to this control
                    (s as Control).Capture = true;

                    // Record original column width
                    originalWidth = rootPanel.ColumnStyles[0].Width;

                    // Record first clicked point
                    // Convert to screen coordinates because this window will be a moving target
                    Point windowPoint = (s as Control).PointToScreen(e.Location);
                    splitPointX = windowPoint.X;
                }
            };
        buttonPanel.MouseMove += (s, e) =>
            {
                if ((s as Control).Capture)
                {
                    Point windowPoint = (s as Control).PointToScreen(e.Location);

                    // Calculate distance of mouse from splitPoint
                    int offset = windowPoint.X - splitPointX;

                    // Apply to originalWidth
                    float newWidth = originalWidth + offset;

                    // Clamp it.
                    // The control in the left pane's MinimumSize.Width would be more appropriate than zero
                    newWidth = Math.Max(0, newWidth);

                    // Update column width
                    if (Math.Abs(newWidth - rootPanel.ColumnStyles[0].Width) >= 1)
                        rootPanel.ColumnStyles[0].Width = newWidth;
                }
            };
        buttonPanel.MouseUp += (s, e) =>
            {
                if (e.Button == MouseButtons.Left)
                {
                    // Release mouse capture
                    if ((s as Control).Capture)
                        (s as Control).Capture = false;
                }
            };
    }
}