问:
code is returning data of one date only whereas i want data of every date
```<code>function practise()
{
    $this->load->database();
     $qry = mysql_query("select * from demmo");
  if (mysql_num_rows($qry) > 0)
{
     while ($row = mysql_fetch_array($qry))
  {
      $created = $row['created'];
//from here
      $qry = mysql_query("select * from demmo where created = '$created'");

            while ($res = mysql_fetch_array($qry))
            {
                $user_id = $res['id'];
                $name = $res['name'];
                $created2 = $res['created'];
            $users[] = array('user_id' => $user_id, 'name' => $name);
            }
                $dotts[] = array('created' => $created2);
//till here
}
    return array ($dotts,$users);
}
}
</code>```

in demmo table i am trying to fetch data and showing that data according to date .the problem is that the code is only selecting one date from the table from created rows and showing that data only .fortunately data shown is not only last but the data with actual date.

答:
You need to create an array and use array_push function , then only it will have more than one value.

example:

create an empty array as

```<code>$allUser = array();
</code>```

then after this line

```<code>$users[] = array('user_id' => $user_id, 'name' => $name);
</code>```

use array_push as

```<code>array_push($allUser, $users);
}
return array($dots, $allUser);
</code>```

Body:
function practise()
{
    $this->load->database();
     $qry = mysql_query("select * from demmo");
  if (mysql_num_rows($qry) > 0)
{
     while ($row = mysql_fetch_array($qry))
  {
      $created = $row['created'];
//from here
      $qry = mysql_query("select * from demmo where created = '$created'");

            while ($res = mysql_fetch_array($qry))
            {
                $user_id = $res['id'];
                $name = $res['name'];
                $created2 = $res['created'];
            $users[] = array('user_id' => $user_id, 'name' => $name);
            }
                $dotts[] = array('created' => $created2);
//till here
}
    return array ($dotts,$users);
}
}

in demmo table i am trying to fetch data and showing that data according to date .the problem is that the code is only selecting one date from the table from created rows and showing that data only .fortunately data shown is not only last but the data with actual date.

Body:
You need to create an array and use array_push function , then only it will have more than one value.

example:

create an empty array as

$allUser = array();

then after this line

$users[] = array('user_id' => $user_id, 'name' => $name);

use array_push as

array_push($allUser, $users);
}
return array($dots, $allUser);


来源: stackexchange

问:
Can't call this inside arrow function
I have problem when i'm trying to access by this keyword. I need to access run function inside updateTime

```<code>export class PlayerService {

 createPlayer(): void {
            return new window['YT'].Player(this.youtube.playerId, {
                height: this.youtube.playerHeight,
                width: this.youtube.playerWidth,

                events: {
                    'onStateChange': (event) => {

                        function updateTime() {

                   //////I need to access | run function | from here

                        };

                        this.timeupdater = setInterval(updateTime, 100);

                    }
                }
            });
        }

           run (){

    //some codes

                }
}
</code>```

I'm working on ionic 2

答:
You need to go arrow function all the way

```<code>function updateTime() {
</code>```

should be

```<code>var updateTime = () => {
</code>```

or

```<code>setInterval(updateTime, 100);
</code>```

should be

```<code>setInterval(() => updateTime(), 100);
</code>```

ContentLicense: CC BY-SA 3.0

Title: Can't call this inside arrow function

Body:
I have problem when i'm trying to access by this keyword. I need to access run function inside updateTime

export class PlayerService {

 createPlayer(): void {
            return new window['YT'].Player(this.youtube.playerId, {
                height: this.youtube.playerHeight,
                width: this.youtube.playerWidth,

                events: {
                    'onStateChange': (event) => {

                        function updateTime() {

                   //////I need to access | run function | from here

                        };

                        this.timeupdater = setInterval(updateTime, 100);

                    }
                }
            });
        }

           run (){

    //some codes

                }
}

I'm working on ionic 2

Body:
You need to go arrow function all the way

function updateTime() {

should be

var updateTime = () => {

or

setInterval(updateTime, 100);

should be

setInterval(() => updateTime(), 100);


问:
Can`t make gRPC work with Electron.js
I`m making an Electron app that should connect by grpc to remote host and call some functions from there.

But I keep getting the following error:
Uncaught Error: A dynamic link library (DLL) initialization routine failed.
\?\D:\Projects\demo-app\node_modules\grpc\src\node\extension_binary\grpc_node.node

I tried to:

establish grpc connection from main and from renderer processes of Electron

install dependencies as npm install --unsafe-perm

but nothing works.

Error

答:
If you're using a native module, you'll need to rebuild them against your current electron node version.

There is a package called electron-rebuild that will do this for you. Basic instructions:

```<code>npm install --save-dev electron-rebuild
</code>```

Then, whenever you install a new npm package, rerun electron-rebuild:

```<code>./node_modules/.bin/electron-rebuild
</code>```

Or if you're on Windows:

```<code>.\node_modules\.bin\electron-rebuild.cmd
</code>```

Title: Can`t make gRPC work with Electron.js

Body:
If you're using a native module, you'll need to rebuild them against your current electron node version.

There is a package called electron-rebuild that will do this for you. Basic instructions:

npm install --save-dev electron-rebuild

Then, whenever you install a new npm package, rerun electron-rebuild:

./node_modules/.bin/electron-rebuild

Or if you're on Windows:

.\node_modules\.bin\electron-rebuild.cmd


问:
Can a piece of code, if reusable and applicable to different contexts be classified a pattern?
What constitutes a pattern ? If i have a template/code that is reusable and can be applied to other similar situations, can it be called a pattern ?

The following is what i have created. It is a binary approach to handling conditional constructs. I have a field in a table that is composite i.e. it comprises of 3 or more other sub-fields each of which have a true or false value.

Now, i have the sub-fields representing true/false values as 0 and 1. These fields are presented as drop downs to the user in the web based application. These fields are combined to form a byte value comprising 8 bits with the first 3 bits have values of 0 or 1 which the user chooses as false or true. If the user chooses all fields as true the main field would have a value 7 and if he chooses all fields as false, the main field would have a value 0 and like wise.

The main field represents one of the columns in an existing table. The advantage of this code is that, as new sub-fields are required, there is no need to add new columns in the table. The user interface would have an additional drop down for each new sub-field.

This code is reusable and can be applied to different contexts. Could this be classified as a pattern ?

答:
A Pattern isn't the actual code it is the method. A guess this could be some kind of pattern... I would say that patterns tend to be peices of logic/methods that are pared back to their basic form and have uses to many people in many situations.

Not sure whether your method is one of those or not?!

OwnerDisplayName: Subramanian

LastEditorDisplayName: Binary Worrier

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Lambert

LastEditorDisplayName: Lambert


问:
How to map a 2D numpy array onto a 1D array with another 2D array as a map?
So I have two 2D numpy arrays, data containing the actual sample data:

```<code>[[12 15  5  0]
 [ 3 11  3  7]
 [ 9  3  5  2]
 [ 4  7  6  8]]
</code>```

and the other, location, containing a map, another 2D array of unique, non-overlapping int values corresponding to the spaces in a new 1D array of the same size as the two:

```<code>[[ 5  6  9 10]
 [ 4  7  8 11]
 [ 3  2 13 12]
 [ 0  1 14 15]]
</code>```

The only way I've been able to run the transfer so far is with a simple for loop:

```<code>arr = np.zeros(4*4, dtype = int)

for i in range(4):
    for j in range(4):
        mapval = location[i, j]
        arr[mapval] = data[i, j]
</code>```

Which does correctly output [ 4  7  3  9  3 12 15 11  3  5  0  7  2  5  6  8]

This is fine with the simple 4*4 array, but the actual dataset clocks in at 512*512, and this method takes rather very long to complete. So my question is, are there any functions, or methods exploiting ufuncs/numpy's fast processing capabilities to get this done more efficiently?

答:
You need the index that sorts the location array to reorder the data array, which can be calculated using argsort:

```<code>data.ravel()[location.ravel().argsort()]
# array([ 4,  7,  3,  9,  3, 12, 15, 11,  3,  5,  0,  7,  2,  5,  6,  8])
</code>```

```<code>import numpy as np
data = np.array([[12, 15,  5,  0],
 [ 3, 11,  3,  7],
 [ 9,  3,  5,  2],
 [ 4,  7,  6,  8]])

location = np.array([[ 5,  6,  9, 10],
 [ 4,  7,  8, 11],
 [ 3,  2, 13, 12],
 [ 0,  1, 14, 15]])
</code>```

Body:
So I have two 2D numpy arrays, data containing the actual sample data:

[[12 15  5  0]
 [ 3 11  3  7]
 [ 9  3  5  2]
 [ 4  7  6  8]]

and the other, location, containing a map, another 2D array of unique, non-overlapping int values corresponding to the spaces in a new 1D array of the same size as the two:

[[ 5  6  9 10]
 [ 4  7  8 11]
 [ 3  2 13 12]
 [ 0  1 14 15]]

The only way I've been able to run the transfer so far is with a simple for loop:

arr = np.zeros(4*4, dtype = int)

for i in range(4):
    for j in range(4):
        mapval = location[i, j]
        arr[mapval] = data[i, j]

Which does correctly output [ 4  7  3  9  3 12 15 11  3  5  0  7  2  5  6  8]

This is fine with the simple 4*4 array, but the actual dataset clocks in at 512*512, and this method takes rather very long to complete. So my question is, are there any functions, or methods exploiting ufuncs/numpy's fast processing capabilities to get this done more efficiently?

Body:
You need the index that sorts the location array to reorder the data array, which can be calculated using argsort:

data.ravel()[location.ravel().argsort()]
# array([ 4,  7,  3,  9,  3, 12, 15, 11,  3,  5,  0,  7,  2,  5,  6,  8])

import numpy as np
data = np.array([[12, 15,  5,  0],
 [ 3, 11,  3,  7],
 [ 9,  3,  5,  2],
 [ 4,  7,  6,  8]])

location = np.array([[ 5,  6,  9, 10],
 [ 4,  7,  8, 11],
 [ 3,  2, 13, 12],
 [ 0,  1, 14, 15]])


问:
How can I print the text immediately in combobox with bind event?
```<code>from Tkinter import *
import ttk
main=Tk()

def print1(event):
    string = ""
    string = combobox1.get()
    print combobox1.get()

val = StringVar()
combobox1 = ttk.Combobox(main, textvariable=val, height=4)
combobox1.bind("<Key>", print1)
combobox1.focus_set()
combobox1.pack()

mainloop()
</code>```

How can I fix the problem that is, when I press the first button, it didn't show immediately.

For example, when I pressed a, it didn't show anything, and then I pressed b. It will show a, but not ab.
How can I fix this bug?
thanks.

答:
@Ron Norris seems to figured-out and solved your issue. Regardless, here's another way to do things that doesn't involve binding events, it uses the trace() method common to all Tkinter variable classes (BooleanVar, DoubleVar, IntVar, and StringVar) which is described here. The arguments it receives when called are explained in the answer to this question.

```<code>from Tkinter import *
import ttk

main=Tk()

def print1(*args):
    string = combobox1.get()
    print string

val = StringVar()
val.trace("w", print1)  # set callback to be invoked whenever variable is written

combobox1 = ttk.Combobox(main, textvariable=val, height=4)
combobox1.focus_set()
combobox1.pack()

mainloop()
</code>```

Body:
from Tkinter import *
import ttk
main=Tk()

def print1(event):
    string = ""
    string = combobox1.get()
    print combobox1.get()

val = StringVar()
combobox1 = ttk.Combobox(main, textvariable=val, height=4)
combobox1.bind("<Key>", print1)
combobox1.focus_set()
combobox1.pack()

mainloop()

How can I fix the problem that is, when I press the first button, it didn't show immediately.

For example, when I pressed a, it didn't show anything, and then I pressed b. It will show a, but not ab.
How can I fix this bug?
thanks.

Body:
@Ron Norris seems to figured-out and solved your issue. Regardless, here's another way to do things that doesn't involve binding events, it uses the trace() method common to all Tkinter variable classes (BooleanVar, DoubleVar, IntVar, and StringVar) which is described here. The arguments it receives when called are explained in the answer to this question.

from Tkinter import *
import ttk

main=Tk()

def print1(*args):
    string = combobox1.get()
    print string

val = StringVar()
val.trace("w", print1)  # set callback to be invoked whenever variable is written

combobox1 = ttk.Combobox(main, textvariable=val, height=4)
combobox1.focus_set()
combobox1.pack()

mainloop()


问:
Android:Sound doesn't play after 24th click
So I am a programming beginner and while making a simple soundboard app with 8 buttons, i got a strange problem where it stops playing sound after the 24th button press.Here's the java code:

```<code>public class MainActivity extends AppCompatActivity {

    MediaPlayer mediaPlayer;
    int i = 0;
    public void playSound(View view){

            switch(view.getId())
            {
                case R.id.button1:
                    mediaPlayer = MediaPlayer.create(this, R.raw.doyouspeakenglish);
                    break;
                case R.id.button2:
                    mediaPlayer = MediaPlayer.create(this, R.raw.goodevening);
                    break;
                case R.id.button3:
                    mediaPlayer = MediaPlayer.create(this, R.raw.hello);
                    break;
                case R.id.button4:
                    mediaPlayer = MediaPlayer.create(this, R.raw.howareyou);
                    break;
                case R.id.button5:
                    mediaPlayer = MediaPlayer.create(this, R.raw.ilivein);
                    break;
                case R.id.button6:
                    mediaPlayer = MediaPlayer.create(this, R.raw.mynameis);
                    break;
                case R.id.button7:
                    mediaPlayer = MediaPlayer.create(this, R.raw.please);
                    break;
                case R.id.button8:
                    mediaPlayer = MediaPlayer.create(this, R.raw.welcome);
                    break;
                default:
                    throw new RuntimeException("Unknown button ID");
            }
            i++;
        Log.i("klik", Integer.toString(i));
            mediaPlayer.start();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}
</code>```

And here's the error message,I'm not allowed to post the image for being a new user so here's a link

答:
You are not releasing the media player resource , so you need to close and release them as well

Releasing the MediaPlayer

```<code>public void playSound(View view){
        if (null != mediaPlayer) {
            mediaPlayer.stop();
            mediaPlayer.release();
        }

        switch(view.getId())
        {
            case R.id.button1:
                mediaPlayer = MediaPlayer.create(this, R.raw.doyouspeakenglish);
                break;
            case R.id.button2:
                mediaPlayer = MediaPlayer.create(this, R.raw.goodevening);
                break;
            case R.id.button3:
                mediaPlayer = MediaPlayer.create(this, R.raw.hello);
                break;
            case R.id.button4:
                mediaPlayer = MediaPlayer.create(this, R.raw.howareyou);
                break;
            case R.id.button5:
                mediaPlayer = MediaPlayer.create(this, R.raw.ilivein);
                break;
            case R.id.button6:
                mediaPlayer = MediaPlayer.create(this, R.raw.mynameis);
                break;
            case R.id.button7:
                mediaPlayer = MediaPlayer.create(this, R.raw.please);
                break;
            case R.id.button8:
                mediaPlayer = MediaPlayer.create(this, R.raw.welcome);
                break;
            default:
                throw new RuntimeException("Unknown button ID");
        }
        i++;
    Log.i("klik", Integer.toString(i));
        mediaPlayer.start();
}
</code>```

Body:
So I am a programming beginner and while making a simple soundboard app with 8 buttons, i got a strange problem where it stops playing sound after the 24th button press.Here's the java code:

public class MainActivity extends AppCompatActivity {

    MediaPlayer mediaPlayer;
    int i = 0;
    public void playSound(View view){

            switch(view.getId())
            {
                case R.id.button1:
                    mediaPlayer = MediaPlayer.create(this, R.raw.doyouspeakenglish);
                    break;
                case R.id.button2:
                    mediaPlayer = MediaPlayer.create(this, R.raw.goodevening);
                    break;
                case R.id.button3:
                    mediaPlayer = MediaPlayer.create(this, R.raw.hello);
                    break;
                case R.id.button4:
                    mediaPlayer = MediaPlayer.create(this, R.raw.howareyou);
                    break;
                case R.id.button5:
                    mediaPlayer = MediaPlayer.create(this, R.raw.ilivein);
                    break;
                case R.id.button6:
                    mediaPlayer = MediaPlayer.create(this, R.raw.mynameis);
                    break;
                case R.id.button7:
                    mediaPlayer = MediaPlayer.create(this, R.raw.please);
                    break;
                case R.id.button8:
                    mediaPlayer = MediaPlayer.create(this, R.raw.welcome);
                    break;
                default:
                    throw new RuntimeException("Unknown button ID");
            }
            i++;
        Log.i("klik", Integer.toString(i));
            mediaPlayer.start();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

And here's the error message,I'm not allowed to post the image for being a new user so here's a link

Body:
You are not releasing the media player resource , so you need to close and release them as well

Releasing the MediaPlayer

public void playSound(View view){
        if (null != mediaPlayer) {
            mediaPlayer.stop();
            mediaPlayer.release();
        }

        switch(view.getId())
        {
            case R.id.button1:
                mediaPlayer = MediaPlayer.create(this, R.raw.doyouspeakenglish);
                break;
            case R.id.button2:
                mediaPlayer = MediaPlayer.create(this, R.raw.goodevening);
                break;
            case R.id.button3:
                mediaPlayer = MediaPlayer.create(this, R.raw.hello);
                break;
            case R.id.button4:
                mediaPlayer = MediaPlayer.create(this, R.raw.howareyou);
                break;
            case R.id.button5:
                mediaPlayer = MediaPlayer.create(this, R.raw.ilivein);
                break;
            case R.id.button6:
                mediaPlayer = MediaPlayer.create(this, R.raw.mynameis);
                break;
            case R.id.button7:
                mediaPlayer = MediaPlayer.create(this, R.raw.please);
                break;
            case R.id.button8:
                mediaPlayer = MediaPlayer.create(this, R.raw.welcome);
                break;
            default:
                throw new RuntimeException("Unknown button ID");
        }
        i++;
    Log.i("klik", Integer.toString(i));
        mediaPlayer.start();
}


问:
Labeling points in matplotlib scatterplot
Edit: This question is not a duplicate, I don't want to plot numbers instead of points, I wanted to plot numbers beside my points.

I'm making a plot using matplotlib. There are three points to plot [[3,9],[4,8],[5,4]]

I can easily make a scatterplot with them

```<code>import matplotlib.pyplot as plt

allPoints = [[3,9],[4,8],[5,4]]

f, diagram = plt.subplots(1)

for i in range(3):
    xPoint =  allPoints[i][0]
    yPoint =  allPoints[i][1]
    diagram.plot(xPoint, yPoint, 'bo')
</code>```

That produces this plot:

I want to label each point with numbers 1,2,3.

Based on this SO answer I tried to use annotate to label each point.

```<code>import matplotlib.pyplot as plt

allPoints = [[1,3,9],[2,4,8],[3,5,4]]

f, diagram = plt.subplots(1)

for i in range(3):
    pointRefNumber = allPoints[i][0]
    xPoint =  allPoints[i][1]
    yPoint =  allPoints[i][2]
    diagram.annotate(pointRefNumber, (xPoint, yPoint))
</code>```

This produces a blank plot. I'm closely following the other answer but it isn't producing any plot. Where have I made a mistake?

答:
I solved my own question. I needed to plot the points and then annotate them, the annotation does not have plotting built-in.

```<code>import matplotlib.pyplot as plt

allPoints = [[1,3,9],[2,4,8],[3,5,4]]

f, diagram = plt.subplots(1)

for i in range(3):
    pointRefNumber = allPoints[i][0]
    xPoint =  allPoints[i][1]
    yPoint =  allPoints[i][2]
    diagram.plot(xPoint, yPoint, 'bo')
    diagram.annotate(nodeRefNumber, (xPoint, yPoint), fontsize=12)
</code>```

Edited to add the fontsize option just like in Gregoux's answer

Body:
Edit: This question is not a duplicate, I don't want to plot numbers instead of points, I wanted to plot numbers beside my points.

I'm making a plot using matplotlib. There are three points to plot [[3,9],[4,8],[5,4]]

I can easily make a scatterplot with them

import matplotlib.pyplot as plt

allPoints = [[3,9],[4,8],[5,4]]

f, diagram = plt.subplots(1)

for i in range(3):
    xPoint =  allPoints[i][0]
    yPoint =  allPoints[i][1]
    diagram.plot(xPoint, yPoint, 'bo')

That produces this plot:

I want to label each point with numbers 1,2,3.

Based on this SO answer I tried to use annotate to label each point.

import matplotlib.pyplot as plt

allPoints = [[1,3,9],[2,4,8],[3,5,4]]

f, diagram = plt.subplots(1)

for i in range(3):
    pointRefNumber = allPoints[i][0]
    xPoint =  allPoints[i][1]
    yPoint =  allPoints[i][2]
    diagram.annotate(pointRefNumber, (xPoint, yPoint))

This produces a blank plot. I'm closely following the other answer but it isn't producing any plot. Where have I made a mistake?

Body:
I solved my own question. I needed to plot the points and then annotate them, the annotation does not have plotting built-in.

import matplotlib.pyplot as plt

allPoints = [[1,3,9],[2,4,8],[3,5,4]]

f, diagram = plt.subplots(1)

for i in range(3):
    pointRefNumber = allPoints[i][0]
    xPoint =  allPoints[i][1]
    yPoint =  allPoints[i][2]
    diagram.plot(xPoint, yPoint, 'bo')
    diagram.annotate(nodeRefNumber, (xPoint, yPoint), fontsize=12)

Edited to add the fontsize option just like in Gregoux's answer


问:
Is extending the DelegateProcessor of the @Delegate active annotation possible?
I am currently working on an active annotation that is an adjusted version of the Xtend active annotation @Delegate. I already have an ugly version that is just an adapted copy of the class DelegateProcessor and its inner class Util. But this means I copied the whole class just do adapt a few lines of code in two methods.

I tried to extend the DelegateProcessor and Util to override the few methods I need to change. Even in a minimal setup (see code) this is not working. I recognize that the Javadoc tags suggest me not to do this, but I cannot believe that there is no other way than copying the whole 300 lines of code.

This is my minimal setup:

```<code>import com.google.common.annotations.Beta
import com.google.common.annotations.GwtCompatible
import java.lang.annotation.Documented
import java.lang.annotation.ElementType
import java.lang.annotation.Target
import java.util.List
import org.eclipse.xtend.lib.annotations.Delegate
import org.eclipse.xtend.lib.annotations.DelegateProcessor
import org.eclipse.xtend.lib.macro.Active
import org.eclipse.xtend.lib.macro.TransformationContext
import org.eclipse.xtend.lib.macro.TransformationParticipant
import org.eclipse.xtend.lib.macro.declaration.MutableMemberDeclaration

/**
 * Copy of the Xtend {@link Delegate} annotation.
 */
@Beta
@GwtCompatible
@Target(ElementType.FIELD, ElementType.METHOD)
@Active(DelegateDeclaredProcessor)
@Documented
annotation DelegateDeclared {
    /**
     * Optional list of interfaces that this delegate is restricted to.
     * Defaults to the common interfaces of the context type and the annotated
     * element.
     */
    Class<?>[] value = #[]
}

@Beta
class DelegateDeclaredProcessor extends DelegateProcessor implements TransformationParticipant<MutableMemberDeclaration> {

    override doTransform(List<? extends MutableMemberDeclaration> elements, extension TransformationContext context) {
        val extension util = new Util(context) // Overridden to use my own Util class, which i want to adapt later on.
        elements.forEach [
            if (validDelegate) {
                methodsToImplement.forEach[method|implementMethod(method)]
            }
        ]
    }

    @Beta
    static class Util extends DelegateProcessor.Util { // this is where I want to later override some methods.
        new(TransformationContext context) {
            super(context)
        }
    }
}
</code>```

This code produces the following error when using the annotation:

```<code>    Error during annotation processing:
java.lang.NullPointerException
    at org.eclipse.xtend.lib.annotations.DelegateProcessor$Util.listedInterfaces(DelegateProcessor.java:258)
    at org.eclipse.xtend.lib.annotations.DelegateProcessor$Util.areListedInterfacesValid(DelegateProcessor.java:184)
    at org.eclipse.xtend.lib.annotations.DelegateProcessor$Util._isValidDelegate(DelegateProcessor.java:67)
    at org.eclipse.xtend.lib.annotations.DelegateProcessor$Util.isValidDelegate(DelegateProcessor.java:592)
    at jce.util.DelegateDeclaredProcessor.lambda$0(DelegateDeclaredProcessor.java:28)
    at jce.util.DelegateDeclaredProcessor$$Lambda$15311/667735929.accept(Unknown Source)
    at java.lang.Iterable.forEach(Iterable.java:75)
    at jce.util.DelegateDeclaredProcessor.doTransform(DelegateDeclaredProcessor.java:36)
</code>```

What is the problem here? Am I doing anything wrong or is it just not possible to do that? Is there another way to create adapted versions of existing active annotations such as @Delegate?

答:
looks like you miss some overrides</p>

```<code>@Beta
static class Util extends DelegateProcessor.Util { // this is where I want to later override some methods.

    extension TransformationContext context

    new(TransformationContext context) {
        super(context)
        this.context = context
    }

    override getDelegates(TypeDeclaration it) {
        declaredMembers.filter[findAnnotation(findTypeGlobally(DelegateDeclared)) !== null]
    }

    override listedInterfaces(MemberDeclaration it) {
        findAnnotation(findTypeGlobally(DelegateDeclared)).getClassArrayValue("value").toSet
    }

}
</code>```

Body:
I am currently working on an active annotation that is an adjusted version of the Xtend active annotation @Delegate. I already have an ugly version that is just an adapted copy of the class DelegateProcessor and its inner class Util. But this means I copied the whole class just do adapt a few lines of code in two methods.

I tried to extend the DelegateProcessor and Util to override the few methods I need to change. Even in a minimal setup (see code) this is not working. I recognize that the Javadoc tags suggest me not to do this, but I cannot believe that there is no other way than copying the whole 300 lines of code.

This is my minimal setup:

import com.google.common.annotations.Beta
import com.google.common.annotations.GwtCompatible
import java.lang.annotation.Documented
import java.lang.annotation.ElementType
import java.lang.annotation.Target
import java.util.List
import org.eclipse.xtend.lib.annotations.Delegate
import org.eclipse.xtend.lib.annotations.DelegateProcessor
import org.eclipse.xtend.lib.macro.Active
import org.eclipse.xtend.lib.macro.TransformationContext
import org.eclipse.xtend.lib.macro.TransformationParticipant
import org.eclipse.xtend.lib.macro.declaration.MutableMemberDeclaration

/**
 * Copy of the Xtend {@link Delegate} annotation.
 */
@Beta
@GwtCompatible
@Target(ElementType.FIELD, ElementType.METHOD)
@Active(DelegateDeclaredProcessor)
@Documented
annotation DelegateDeclared {
    /**
     * Optional list of interfaces that this delegate is restricted to.
     * Defaults to the common interfaces of the context type and the annotated
     * element.
     */
    Class<?>[] value = #[]
}

@Beta
class DelegateDeclaredProcessor extends DelegateProcessor implements TransformationParticipant<MutableMemberDeclaration> {

    override doTransform(List<? extends MutableMemberDeclaration> elements, extension TransformationContext context) {
        val extension util = new Util(context) // Overridden to use my own Util class, which i want to adapt later on.
        elements.forEach [
            if (validDelegate) {
                methodsToImplement.forEach[method|implementMethod(method)]
            }
        ]
    }

    @Beta
    static class Util extends DelegateProcessor.Util { // this is where I want to later override some methods.
        new(TransformationContext context) {
            super(context)
        }
    }
}

This code produces the following error when using the annotation:

    Error during annotation processing:
java.lang.NullPointerException
    at org.eclipse.xtend.lib.annotations.DelegateProcessor$Util.listedInterfaces(DelegateProcessor.java:258)
    at org.eclipse.xtend.lib.annotations.DelegateProcessor$Util.areListedInterfacesValid(DelegateProcessor.java:184)
    at org.eclipse.xtend.lib.annotations.DelegateProcessor$Util._isValidDelegate(DelegateProcessor.java:67)
    at org.eclipse.xtend.lib.annotations.DelegateProcessor$Util.isValidDelegate(DelegateProcessor.java:592)
    at jce.util.DelegateDeclaredProcessor.lambda$0(DelegateDeclaredProcessor.java:28)
    at jce.util.DelegateDeclaredProcessor$$Lambda$15311/667735929.accept(Unknown Source)
    at java.lang.Iterable.forEach(Iterable.java:75)
    at jce.util.DelegateDeclaredProcessor.doTransform(DelegateDeclaredProcessor.java:36)

What is the problem here? Am I doing anything wrong or is it just not possible to do that? Is there another way to create adapted versions of existing active annotations such as @Delegate?

Body:
looks like you miss some overrides

@Beta
static class Util extends DelegateProcessor.Util { // this is where I want to later override some methods.

    extension TransformationContext context

    new(TransformationContext context) {
        super(context)
        this.context = context
    }

    override getDelegates(TypeDeclaration it) {
        declaredMembers.filter[findAnnotation(findTypeGlobally(DelegateDeclared)) !== null]
    }

    override listedInterfaces(MemberDeclaration it) {
        findAnnotation(findTypeGlobally(DelegateDeclared)).getClassArrayValue("value").toSet
    }

}


问:
SQL find dates that will expire in 6 months from now
I have a mysql table that contains, among others, the columns personName, board (a bool that states if person is part of board or not) and board_date (a date column that contains the date that the person was elected to the board, if she was).

In my club, the people are elected for 5 year terms. I need to create a query that will return the people whose term will expire in the next 6 months. But I have no clue on how to do that math with those dates.

Can someone please give me a hand? I inherited this system from a previous administrator, and the client wants this. I'm not good with SQL

答:
you can use date_add  adding 6 months to now() </p>

```<code>select *
from my_table
where date_add(board_date, INTERVAL 5 YEAR)
         between now() and  DATE_ADD(now(), INTERVAL 6 MONTH)
</code>```

Body:
you can use date_add  adding 6 months to now()

select *
from my_table
where date_add(board_date, INTERVAL 5 YEAR)
         between now() and  DATE_ADD(now(), INTERVAL 6 MONTH)


问:
How to combine columns form two different pipe delimited filea using unix. I need to pick columns from both file and merge into one output file
I am trying to write a logic in unix scripting where I am merging columns form 2 pipe delimited file. For example, I have file a.txt with columns A|B|C and file b.txt which has columns D|E|F. I want the output file c.txt with columns A|D|B|C|E|F.

Thanks!!
Sourabh

答:
Use paste to match up the two files, and then awk to output the
columns in the order desired.</p>

```<code>$ cat a
A|B|C
1|2|3
$ cat b
D|E|F
4|5|6
$ paste -d'|' a b | awk -F'|' 'BEGIN { OFS="|" }{print $1, $4, $2, $3, $5, $6}'
A|D|B|C|E|F
1|4|2|3|5|6
</code>```

Body:
Use paste to match up the two files, and then awk to output the
columns in the order desired.

$ cat a
A|B|C
1|2|3
$ cat b
D|E|F
4|5|6
$ paste -d'|' a b | awk -F'|' 'BEGIN { OFS="|" }{print $1, $4, $2, $3, $5, $6}'
A|D|B|C|E|F
1|4|2|3|5|6


问:
How to ignore a dot (.) in regex?
I have this:

```<code>(adrian)(@mazur.com)|(^(adrian)\+(.*)@mazur.com$)
</code>```

It matches these only partially:

```<code>adrian@mazur.com
adrian+whatever@mazur.com
adrian+what.ev.er@mazur.com
a.d.r.i.a.n@mazur.com
a.d.r.i.a.n+whatever@mazur.com
a..drian@mazur.com
</code>```

They also can't match those:

```<code>patryk@mazur.com
patryk+whatever@mazur.com
patryk+what.ev.er@mazur.com
p.a.t.r.y.k@mazur.com
p.a.t.r.y.k+whatever@mazur.com
p..adtryk@mazur.com
p.dra..us...@mazur.com
</code>```

or other like danuta, micheal, ryan, sean etc.

How do I make it ignore the dot (.) between my name?
I use this tool to test the regex: http://74.50.60.193/ it's http://www.rubular.com/ but it doesn't resolve for me so I put IP too.

答:
You could try something like this although it isn't the best solution (you will also need global flag to capture all matches):</p>

```<code>(a\.*?d\.*?r\.*?i\.*?a\.*?n)\+?(.*)(@mazur\.com)
</code>```

Title: How to ignore a dot (.) in regex?

Body:
I have this:

(adrian)(@mazur.com)|(^(adrian)\+(.*)@mazur.com$)

It matches these only partially:

adrian@mazur.com
adrian+whatever@mazur.com
adrian+what.ev.er@mazur.com
a.d.r.i.a.n@mazur.com
a.d.r.i.a.n+whatever@mazur.com
a..drian@mazur.com

They also can't match those:

patryk@mazur.com
patryk+whatever@mazur.com
patryk+what.ev.er@mazur.com
p.a.t.r.y.k@mazur.com
p.a.t.r.y.k+whatever@mazur.com
p..adtryk@mazur.com
p.dra..us...@mazur.com

or other like danuta, micheal, ryan, sean etc.

How do I make it ignore the dot (.) between my name?
I use this tool to test the regex: http://74.50.60.193/ it's http://www.rubular.com/ but it doesn't resolve for me so I put IP too.

Body:
You could try something like this although it isn't the best solution (you will also need global flag to capture all matches):

(a\.*?d\.*?r\.*?i\.*?a\.*?n)\+?(.*)(@mazur\.com)


问:
How to access 2d array in assembly x86
How to use 2d array in assembly? i declarated int array[100][2] in C , and i want to access for example array[4][0] in assembly

答:
In C,

```<code>array[i][j]
</code>```

is the same as:

```<code>*(*(array + i) + j)
</code>```

When you add pointers in C, it automatically takes into account the size of the type that is pointed to. That isn't the case in assembly, so you have to do that yourself.

The basic formula is just:

```<code>(offsetof(array) + (sizeof(int) * i)) + (sizeof(int) * j)
</code>```

Since an int is almost certainly 4 bytes, the assembly equivalent of:

```<code>int temp = array[4][0];
</code>```

would be:

```<code>mov  eax, DWORD PTR [array+16]
</code>```

because (4*4)+(0*4) == 16.

Title: How to access 2d array in assembly x86

Body:
In C,

array[i][j]

is the same as:

*(*(array + i) + j)

When you add pointers in C, it automatically takes into account the size of the type that is pointed to. That isn't the case in assembly, so you have to do that yourself.

The basic formula is just:

(offsetof(array) + (sizeof(int) * i)) + (sizeof(int) * j)

Since an int is almost certainly 4 bytes, the assembly equivalent of:

int temp = array[4][0];

would be:

mov  eax, DWORD PTR [array+16]

because (4*4)+(0*4) == 16.


问:
return jsonresult behaves unexpextedly with jquery post
Okay please help, I've been frustrated with this issue.

I need to either set an error value or perform a redirect when a user hits the submit button. (its a standard login form). I need to do it with ajax.

I think its almost working, however when the user clicks submit the page just displays:
{"redirect":"/Home/Index"}

or
{"error":"The user name or password provided is incorrect."}

its not redirecting/displaying the error how I'm intending it to.

some background - the form is a login form, and its placed inside a modal popup dialog.(jqueryui)

Heres my jquery:

```<code>$("#submit").click(function () {
            $.post({
                url: "Account/LogOn",
                dataType: "json",
                success: function (data) {
                    if (data.redirect) {
                        // data.redirect contains the string URL to redirect to
                        window.location.href = data.redirect;
                    }
                    else {
                        // data.form contains the HTML for the replacement form
                        $("#error").replaceWith(data.error);
                    }
                }
            });
            return false;
        });
</code>```

and heres my Action method:

```<code>[HttpPost]
    public JsonResult LogOn(LogOnModel model, string returnUrl)
    {
        if (ModelState.IsValid)
        {
            if (MembershipService.ValidateUser(model.UserName, model.Password))
            {
                FormsService.SignIn(model.UserName, model.RememberMe);
                if (Url.IsLocalUrl(returnUrl))
                {
                    return Json(new { redirect = returnUrl });
                }
                else
                {
                    return Json(new { redirect = "/Home/Index" });
                }
            }

        }
        return Json(new { error = "The user name or password provided is incorrect." });
    }
</code>```

heres is my form:

```<code>@using (Html.BeginForm("LogOn", "Account"))
{

    <div>
        <fieldset>
            <legend>Account Information</legend>

            <div class="editor-label">
                @Html.LabelFor(m => m.UserName)
            </div>
            <div class="editor-field">
                @Html.TextBoxFor(m => m.UserName)
                @Html.ValidationMessageFor(m => m.UserName)
            </div>

            <div class="editor-label">
                @Html.LabelFor(m => m.Password)
            </div>
            <div class="editor-field">
                @Html.PasswordFor(m => m.Password)
                @Html.ValidationMessageFor(m => m.Password)
            </div>

            <div class="editor-label">
                @Html.CheckBoxFor(m => m.RememberMe)
                @Html.LabelFor(m => m.RememberMe)
            </div>

            <p>
                <input id="submit" type="submit" value="Log On" />
            </p>
        </fieldset>
    </div>
}
</code>```

答:
Ouch, the whole $.post()-call is wrong.

Use this:

```<code>$("#submit").click(function (e) {e.preventDefault();
            $.post( "Account/LogOn",
                    $(this.form).serialize(),
                    function (data)
                    {
                      if (data.redirect)
                      {
                        // data.redirect contains the string URL to redirect to
                        window.location.href = data.redirect;
                      }
                      else
                      {
                        // data.form contains the HTML for the replacement form
                        $("#error").replaceWith(data.error);
                      }
                    },
                    'json'
            );
            return false;
        });
</code>```

You've used the notation of the arguments like expected in $.ajax() , but in $.post() it's different.

Body:
Okay please help, I've been frustrated with this issue.

I need to either set an error value or perform a redirect when a user hits the submit button. (its a standard login form). I need to do it with ajax.

I think its almost working, however when the user clicks submit the page just displays:
{"redirect":"/Home/Index"}

or
{"error":"The user name or password provided is incorrect."}

its not redirecting/displaying the error how I'm intending it to.

some background - the form is a login form, and its placed inside a modal popup dialog.(jqueryui)

Heres my jquery:

$("#submit").click(function () {
            $.post({
                url: "Account/LogOn",
                dataType: "json",
                success: function (data) {
                    if (data.redirect) {
                        // data.redirect contains the string URL to redirect to
                        window.location.href = data.redirect;
                    }
                    else {
                        // data.form contains the HTML for the replacement form
                        $("#error").replaceWith(data.error);
                    }
                }
            });
            return false;
        });

and heres my Action method:

[HttpPost]
    public JsonResult LogOn(LogOnModel model, string returnUrl)
    {
        if (ModelState.IsValid)
        {
            if (MembershipService.ValidateUser(model.UserName, model.Password))
            {
                FormsService.SignIn(model.UserName, model.RememberMe);
                if (Url.IsLocalUrl(returnUrl))
                {
                    return Json(new { redirect = returnUrl });
                }
                else
                {
                    return Json(new { redirect = "/Home/Index" });
                }
            }

        }
        return Json(new { error = "The user name or password provided is incorrect." });
    }

heres is my form:

@using (Html.BeginForm("LogOn", "Account"))
{

        <fieldset>
            <legend>Account Information</legend>

                @Html.LabelFor(m => m.UserName)

                @Html.TextBoxFor(m => m.UserName)
                @Html.ValidationMessageFor(m => m.UserName)

                @Html.LabelFor(m => m.Password)

                @Html.PasswordFor(m => m.Password)
                @Html.ValidationMessageFor(m => m.Password)

                @Html.CheckBoxFor(m => m.RememberMe)
                @Html.LabelFor(m => m.RememberMe)

                <input id="submit" type="submit" value="Log On" />

        </fieldset>

}

Body:
Ouch, the whole $.post()-call is wrong.

Use this:

$("#submit").click(function (e) {e.preventDefault();
            $.post( "Account/LogOn",
                    $(this.form).serialize(),
                    function (data)
                    {
                      if (data.redirect)
                      {
                        // data.redirect contains the string URL to redirect to
                        window.location.href = data.redirect;
                      }
                      else
                      {
                        // data.form contains the HTML for the replacement form
                        $("#error").replaceWith(data.error);
                      }
                    },
                    'json'
            );
            return false;
        });

You've used the notation of the arguments like expected in $.ajax() , but in $.post() it's different.


问:
Allowing users to change order of list of items
I am trying to allow users to create a list of items with their categories in the order they want. For some reason categories are appearing in the order users are choosing. But, items are showing in a random order! even though I am using the same code for them!

models.py

```<code>class Category(models.Model):
    user = models.ForeignKey(User)
    title = models.CharField(max_length=250)
    order = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(10)])

class Item(models.Model):
    user = models.ForeignKey(User)
    category = models.ForeignKey(Category)
    title = models.CharField(max_length=250)
    order = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(10)])
</code>```

views.py

```<code>def items_list(request):
    category = Category.objects.filter(user=request.user).order_by("order")
    item = Item.objects.filter(user=request.user).order_by("order")
    return render(request, 'fav.html', {"items": item, "categories": category})
</code>```

Any help would be much appreciated.

答:
try:

```<code> def items_list(request):
    category = Category.objects.filter(user=request.user).order_by("order")
    items = [Item.objects.filter(category=c).order_by('order') for c in category]
    return render(request, 'fav.html', {"items": items})
</code>```

After this,u should edit ur template.loop items twice, the first time items will be split by category, the second time items in one category will be split by id and ordered by order.

Body:
I am trying to allow users to create a list of items with their categories in the order they want. For some reason categories are appearing in the order users are choosing. But, items are showing in a random order! even though I am using the same code for them!

models.py

class Category(models.Model):
    user = models.ForeignKey(User)
    title = models.CharField(max_length=250)
    order = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(10)])

class Item(models.Model):
    user = models.ForeignKey(User)
    category = models.ForeignKey(Category)
    title = models.CharField(max_length=250)
    order = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(10)])

views.py

def items_list(request):
    category = Category.objects.filter(user=request.user).order_by("order")
    item = Item.objects.filter(user=request.user).order_by("order")
    return render(request, 'fav.html', {"items": item, "categories": category})

Any help would be much appreciated.

Body:
try:

 def items_list(request):
    category = Category.objects.filter(user=request.user).order_by("order")
    items = [Item.objects.filter(category=c).order_by('order') for c in category]
    return render(request, 'fav.html', {"items": items})

After this,u should edit ur template.loop items twice, the first time items will be split by category, the second time items in one category will be split by id and ordered by order.


问:
API Service Architecture vs Browser - Using Workers and Queues
I'm reading this article on Heroku about the proper architecture of handling requests and using polling on the browser side if the requests will take longer than a few milliseconds. It is clear and makes sense.

My issue is, I'm in the planning stage of a commercial API service, which is the app, where there's going to be no browser involved. I can't exactly send back a hold on reply, and ask the client to poll when the response is ready.

How do I handle this scenario of sending long-working jobs to workers in an API app setup?

答:
This is an interesting question, and there are many ways of doing it.

One way would be to have your clients register an endpoint, and then when your background worker is done, you can hit their endpoint.


问:
Protect JavaScript code
I am trying to find a way to protect/hide/encrypt my JavaScript code. With a little research I get that you can not do that. I found only that you can minify your code and do some other tricks. However in Facebook if you try to inspect an element or try to debug, you get a message in the console and you cannot see any code.
How can I do that?
Is it safe?
I am working with fire base and I use JavaScript for getting data and authentication. It is important to ensure that my code is protected. </p>

答:
I just wanted to share with everyone who has the same problem, Firebase gives you the option to set the rules for the application.
https://firebase.google.com/docs/database/security/quickstart</p>

Title: Protect JavaScript code


问:
cURL throwing globbing error when JSON data in variable contains a space
Using bash v4.3.48(1) on Ubuntu 16.04.2 LTS and bash v3.2.57 on macOS Sierra 10.12.5 I have this code which POSTs JSON data stored in a variable:

```<code>#1
JSON_DATA="Test"; \
curl -X POST "https://www.techotaku.com/json.php" \
    -H "Content-Type: application/json" \
    -d '{"data":"'$JSON_DATA'"}'
</code>```

This returns:

```<code>Array
(
    [data] => Test
)
</code>```

However, if $JSON_DATA contains a space...

```<code>#2
JSON_DATA="A Test"; \
curl -X POST "https://www.techotaku.com/json.php" \
    -H "Content-Type: application/json" \
    -d '{"data":"'$JSON_DATA'"}'
</code>```

...it throws an error:

```<code>curl: (3) [globbing] unmatched close brace/bracket in column 6
</code>```

I thought this might be due to incorrect use of quotes, but if I echo the JSON data...

```<code>echo '{"data":"'$JSON_DATA'"}'
</code>```

...it appears well-formed:

```<code>{"data":"A Test"}
</code>```

Also, if I include the JSON data as a string and not a variable, it works.

```<code>#3
curl -X POST "https://www.techotaku.com/json.php" \
    -H "Content-Type: application/json" \
    -d '{"data":"A Test"}'
</code>```

The only way I can get it to work if the variable contains a space is to enclose the JSON data in double-quotes and escape the literal double-quotes in the string:

```<code>#4
JSON_DATA="A Test"; \
curl -X POST "https://www.techotaku.com/json.php" \
    -H "Content-Type: application/json" \
    -d "{\"data\":\"$JSON_DATA\"}"
</code>```

I would have thought that all 4 examples would have worked. So, can anyone throw any light on why only examples 1,3 and 4 work and example 2 doesn't?

Many thanks, Steve.

答:
You should quote your variables to prevent word splitting by shell. Your second example:

```<code>'{"data":"'$JSON_DATA'"}'
</code>```

doesn't work because it's being expanded by bash to two words:

```<code>{"data":"A Test"}
</code>```

so -d option receives 2 arguments ({"data":"A and Test"}). If JSON_DATA contained globbing metacharacters, those would cause filename expansion.

To fix it, quote it:

```<code>'{"data":"'"$JSON_DATA"'"}'
</code>```

Note the use of alternating single and double quotes. This will be expanded to a single word:

```<code>{"data":"A Test"}
</code>```

Here's a more detailed answer I wrote some time ago which also mentions another convenient option, the use of a here-document.

Body:
Using bash v4.3.48(1) on Ubuntu 16.04.2 LTS and bash v3.2.57 on macOS Sierra 10.12.5 I have this code which POSTs JSON data stored in a variable:

#1
JSON_DATA="Test"; \
curl -X POST "https://www.techotaku.com/json.php" \
    -H "Content-Type: application/json" \
    -d '{"data":"'$JSON_DATA'"}'

This returns:

Array
(
    [data] => Test
)

However, if $JSON_DATA contains a space...

#2
JSON_DATA="A Test"; \
curl -X POST "https://www.techotaku.com/json.php" \
    -H "Content-Type: application/json" \
    -d '{"data":"'$JSON_DATA'"}'

...it throws an error:

curl: (3) [globbing] unmatched close brace/bracket in column 6

I thought this might be due to incorrect use of quotes, but if I echo the JSON data...

echo '{"data":"'$JSON_DATA'"}'

...it appears well-formed:

{"data":"A Test"}

Also, if I include the JSON data as a string and not a variable, it works.

#3
curl -X POST "https://www.techotaku.com/json.php" \
    -H "Content-Type: application/json" \
    -d '{"data":"A Test"}'

The only way I can get it to work if the variable contains a space is to enclose the JSON data in double-quotes and escape the literal double-quotes in the string:

#4
JSON_DATA="A Test"; \
curl -X POST "https://www.techotaku.com/json.php" \
    -H "Content-Type: application/json" \
    -d "{\"data\":\"$JSON_DATA\"}"

I would have thought that all 4 examples would have worked. So, can anyone throw any light on why only examples 1,3 and 4 work and example 2 doesn't?

Many thanks, Steve.

Body:
You should quote your variables to prevent word splitting by shell. Your second example:

'{"data":"'$JSON_DATA'"}'

doesn't work because it's being expanded by bash to two words:

{"data":"A Test"}

so -d option receives 2 arguments ({"data":"A and Test"}). If JSON_DATA contained globbing metacharacters, those would cause filename expansion.

To fix it, quote it:

'{"data":"'"$JSON_DATA"'"}'

Note the use of alternating single and double quotes. This will be expanded to a single word:

{"data":"A Test"}

Here's a more detailed answer I wrote some time ago which also mentions another convenient option, the use of a here-document.


问:
I want to get the field name of class in android
I want to get the field name of class in android. for this I am using this code

```<code>public static String checkForNull(Object obj) {
    Class cls = obj.getClass();
    Field fields[] = cls.getDeclaredFields();
    for (Field field : fields) {
        Object object = null;
        try {
            object = field.get(obj);
        } catch (IllegalAccessException e) {
            return "The field " + field.getName() + " of " + cls.getSimpleName() + " is not accessible!";
        }
        if (object == null) {
            return "The field " + field.getName() + " of " + cls.getSimpleName() + " is null!";
        } else if (object instanceof String) {
            String string = (String) object;
            if (string.equals("")) {
                return "The field " + field.getName() + " of " + cls.getSimpleName() + " is empty!";
            }
        }
    }
    return null;
}
</code>```

but this code return generic name of class field like a,b,c...etc. This code work fine in netbeans.

答:
Looks like obfuscated names, most probably you have default settings for ProGuard and Android SDK performs some code obfuscation, see https://developer.android.com/studio/build/shrink-code.html

If you would like to see original field names, you should disable obfuscation either completely or for this particular class / package.

Body:
I want to get the field name of class in android. for this I am using this code

public static String checkForNull(Object obj) {
    Class cls = obj.getClass();
    Field fields[] = cls.getDeclaredFields();
    for (Field field : fields) {
        Object object = null;
        try {
            object = field.get(obj);
        } catch (IllegalAccessException e) {
            return "The field " + field.getName() + " of " + cls.getSimpleName() + " is not accessible!";
        }
        if (object == null) {
            return "The field " + field.getName() + " of " + cls.getSimpleName() + " is null!";
        } else if (object instanceof String) {
            String string = (String) object;
            if (string.equals("")) {
                return "The field " + field.getName() + " of " + cls.getSimpleName() + " is empty!";
            }
        }
    }
    return null;
}

but this code return generic name of class field like a,b,c...etc. This code work fine in netbeans.


问:
rich:modalPanel closes without Validation
I am trying to validate a data in inside a rich:modalPanel; The behavior i see is quite strange.

I have a dropdown and a Add button to that dropdown, for the first time when i try to add data to the dropdown by clicking the Add button the validations are successful, how oever when once the user adds the data for the first time and tries to enter a new data second time by opening newAddUserDialog; and now when the validation fails, the modal panel simply hides. Even if I remove the code for hiding the modal panel (onComplete event inside a4j:commadButton), the window simply closes on click of the buttion.

```<code>        <rich:modalPanel id="newAddUserDialog" autosized="true">

    <a4j:outputPanel id="addName_panel"
        styleClass="largePanel">

        <a4j:form>

            <rich:messages layout="list" showDetail="false"
                errorClass="validationError" />

            <h:panelGrid columns="2" cellpadding="10" cellspacing="10" width="100%">

                <h:outputLabel value="Name:" styleClass="label" />
                <h:inputText id="nameId"
                    value="#{formBean.name}" maxlength="32"
                    required="true" styleClass="width100">
                    <f:validateLength minimum="3" maximum="32" />
                </h:inputText>
            </h:panelGrid>

            <h:panelGrid cellpadding="10" cellspacing="10" width="100%">
                <h:panelGroup>
                    <a4j:commandButton id="addBtn" value="Add"
                        styleClass="stdButton" action="doAddUserName"
                        reRender="addName_panel, targetsMaster">

                        <rich:componentControl for="newAddUserDialog"
                            event="oncomplete"
                            operation="#{(!modelValidationMessages.hasMessages and empty facesContext.maximumSeverity) ? 'hide' : 'focus'}" />
                    </a4j:commandButton>

                    <a4j:commandButton id="addUser_cancel" value="Cancel"
                        styleClass="stdButton">
                        <rich:componentControl for="newAddUserDialog" event="onclick"
                            operation="hide" />
                    </a4j:commandButton>
                </h:panelGroup>
            </h:panelGrid>

        </a4j:form>

    </a4j:outputPanel>

</rich:modalPanel>
</code>```

What could be the reason for such behaviour?

答: Yeah this is the problem addressed by the Richfaces team.  Please check this out</p>

Body:
I am trying to validate a data in inside a rich:modalPanel; The behavior i see is quite strange.

I have a dropdown and a Add button to that dropdown, for the first time when i try to add data to the dropdown by clicking the Add button the validations are successful, how oever when once the user adds the data for the first time and tries to enter a new data second time by opening newAddUserDialog; and now when the validation fails, the modal panel simply hides. Even if I remove the code for hiding the modal panel (onComplete event inside a4j:commadButton), the window simply closes on click of the buttion.

        <rich:modalPanel id="newAddUserDialog" autosized="true">

    <a4j:outputPanel id="addName_panel"
        styleClass="largePanel">

        <a4j:form>

            <rich:messages layout="list" showDetail="false"
                errorClass="validationError" />

            <h:panelGrid columns="2" cellpadding="10" cellspacing="10" width="100%">

                <h:outputLabel value="Name:" styleClass="label" />
                <h:inputText id="nameId"
                    value="#{formBean.name}" maxlength="32"
                    required="true" styleClass="width100">
                    <f:validateLength minimum="3" maximum="32" />
                </h:inputText>
            </h:panelGrid>

            <h:panelGrid cellpadding="10" cellspacing="10" width="100%">
                <h:panelGroup>
                    <a4j:commandButton id="addBtn" value="Add"
                        styleClass="stdButton" action="doAddUserName"
                        reRender="addName_panel, targetsMaster">

                        <rich:componentControl for="newAddUserDialog"
                            event="oncomplete"
                            operation="#{(!modelValidationMessages.hasMessages and empty facesContext.maximumSeverity) ? 'hide' : 'focus'}" />
                    </a4j:commandButton>

                    <a4j:commandButton id="addUser_cancel" value="Cancel"
                        styleClass="stdButton">
                        <rich:componentControl for="newAddUserDialog" event="onclick"
                            operation="hide" />
                    </a4j:commandButton>
                </h:panelGroup>
            </h:panelGrid>

        </a4j:form>

    </a4j:outputPanel>

</rich:modalPanel>

What could be the reason for such behaviour?


问:
Inner Join referencing columns not valid
I am trying to do an inner join based on two columns and am having a problem  referencing the columns correctly.  I have used the following query which to the best of my knowledge is best pratice within postgresql.  The two tables I am attempting to do an inner join on are mk_kw & adwords_final, both columns that are to be joined on are named "Key"

Here is the query

```<code>SELECT
 *
FROM
 adwords_final
INNER JOIN mk_kw ON "mk_kw.Key" = "adwords_final.Key";
</code>```

Here is the result

```<code>ERROR:  column "mk_kw.Key" does not exist
LINE 5: INNER JOIN mk_kw ON "mk_kw.Key" = "adwords_final.Key";
                        ^
ERROR: column "mk_kw.Key" does not exist
SQL state: 42703
Character: 51
</code>```

These columns certainly do exist within this context.  Is there a better way to  reference these columns?

Many Thanks.

答:
The query should become:

```<code> SELECT
 *
FROM
adwords_final
INNER JOIN mk_kw ON mk_kw.Key = adwords_final.Key;
</code>```

Here is a sample of how to write inner joins:

```<code>SELECT Orders.OrderID, Customers.CustomerName
FROM Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;
</code>```

Orders and Customers are table names. CustomerID, CustomerName,OrderID are column names. All of them are case sensitive.

Body:
I am trying to do an inner join based on two columns and am having a problem  referencing the columns correctly.  I have used the following query which to the best of my knowledge is best pratice within postgresql.  The two tables I am attempting to do an inner join on are mk_kw & adwords_final, both columns that are to be joined on are named "Key"

Here is the query

SELECT
 *
FROM
 adwords_final
INNER JOIN mk_kw ON "mk_kw.Key" = "adwords_final.Key";

Here is the result

ERROR:  column "mk_kw.Key" does not exist
LINE 5: INNER JOIN mk_kw ON "mk_kw.Key" = "adwords_final.Key";
                        ^
ERROR: column "mk_kw.Key" does not exist
SQL state: 42703
Character: 51

These columns certainly do exist within this context.  Is there a better way to  reference these columns?

Many Thanks.

Body:
The query should become:

 SELECT
 *
FROM
adwords_final
INNER JOIN mk_kw ON mk_kw.Key = adwords_final.Key;

Here is a sample of how to write inner joins:

SELECT Orders.OrderID, Customers.CustomerName
FROM Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;

Orders and Customers are table names. CustomerID, CustomerName,OrderID are column names. All of them are case sensitive.


问:
Updating the list view when the adapter data changes
When the data associated with array adapter is changed, invalidating the listview is sufficient to show the updated values? Following piece of code is not working, did i misunderstood something here.?

```<code>public class ZeroItemListActivity extends Activity {
    private ArrayList<String> listItems=new ArrayList<String>();
    private ListView mMyListView;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mMyListView=(ListView) findViewById(R.id.MyListView);
        mMyListView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,listItems));
    }
    public void addItem(View v){
        listItems.add("list Item");
        mMyListView.invalidate();
    }
}
</code>```

Layout used :

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:text="@string/hello" />
    <ListView android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:id="@+id/MyListView"></ListView>
    <Button android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:id="@+id/AddItemsButton"
        android:text="Add Items" android:onClick="addItem"></Button>
</LinearLayout>
</code>```

答:
I found a solution that is more efficient than currently accepted answer, because current answer forces all list elements to be refreshed. My solution will refresh only one element (that was touched) by calling adapters getView and recycling current view which adds even more efficiency.</p>

```<code>mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
      // Edit object data that is represented in Viewat at list's "position"
      view = mAdapter.getView(position, view, parent);
    }
});
</code>```

Body:
When the data associated with array adapter is changed, invalidating the listview is sufficient to show the updated values? Following piece of code is not working, did i misunderstood something here.?

public class ZeroItemListActivity extends Activity {
    private ArrayList<String> listItems=new ArrayList<String>();
    private ListView mMyListView;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mMyListView=(ListView) findViewById(R.id.MyListView);
        mMyListView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,listItems));
    }
    public void addItem(View v){
        listItems.add("list Item");
        mMyListView.invalidate();
    }
}

Layout used :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:text="@string/hello" />
    <ListView android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:id="@+id/MyListView"></ListView>
    <Button android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:id="@+id/AddItemsButton"
        android:text="Add Items" android:onClick="addItem"></Button>
</LinearLayout>

Body:
I found a solution that is more efficient than currently accepted answer, because current answer forces all list elements to be refreshed. My solution will refresh only one element (that was touched) by calling adapters getView and recycling current view which adds even more efficiency.

mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
      // Edit object data that is represented in Viewat at list's "position"
      view = mAdapter.getView(position, view, parent);
    }
});

ContentLicense: CC BY-SA 4.0


问:
Use Same Variable In Multiple View Controllers
I have two colour variables:

```<code>var blue = UIColor(red:0.08, green:0.49, blue:0.49, alpha:1.0)
var red = UIColor(red:0.61, green:0.12, blue:0.20, alpha:1.0)
</code>```

I have declared these variables in my EntryViewController, however, I also need to use them in my other ViewControllers. I was wondering if it were possible to use the same variables in multiple ViewControllers? I already know about passing data with segues, but I was wondering if there were a way to maybe declare the colours in their own class and subclass my ViewControllers with this class. Thank you.

答:
You could make these global variables, but that's frowned upon because it pollutes the global name space. Instead, you can make these static members of a new type. A class or struct would work, but typically, an enum is used for this, just to ensure that no instances of the type can be made.

```<code>enum Colors {
    static let blue = UIColor(red: 0.08, green: 0.49, blue: 0.49)
    static let red = UIColor(red: 0.61, green: 0.12, blue: 0.20)
}
</code>```

Body:
I have two colour variables:

var blue = UIColor(red:0.08, green:0.49, blue:0.49, alpha:1.0)
var red = UIColor(red:0.61, green:0.12, blue:0.20, alpha:1.0)

I have declared these variables in my EntryViewController, however, I also need to use them in my other ViewControllers. I was wondering if it were possible to use the same variables in multiple ViewControllers? I already know about passing data with segues, but I was wondering if there were a way to maybe declare the colours in their own class and subclass my ViewControllers with this class. Thank you.

Body:
You could make these global variables, but that's frowned upon because it pollutes the global name space. Instead, you can make these static members of a new type. A class or struct would work, but typically, an enum is used for this, just to ensure that no instances of the type can be made.

enum Colors {
    static let blue = UIColor(red: 0.08, green: 0.49, blue: 0.49)
    static let red = UIColor(red: 0.61, green: 0.12, blue: 0.20)
}


问:
Converting non-numeric matrix into numeric
I have an imported table with longitudes and latitudes and want to create a spatial grid from them.
The coordinates are in this format:

```<code>[1] 6.955 6.937 6.956 6.923
</code>```

So looks numeric for me. But trying to create the grid this Error occurs:

Error in .local(obj, ...) :

        cannot derive coordinates from non-numeric matrix

When I try to change the format using as.numeric I get this result:

```<code>[1] 10  9  6  8
</code>```

How can I convert the coordinates in numeric format without changing the value?

```<code>longitude = structure(c(9L, 7L, 10L, 3L, 8L, 4L, 6L, 2L, 11L, 1L, 5L, 9L,
7L, 10L, 3L, 8L, 4L, 6L, 2L, 11L, 1L, 5L), .Label = c("6.920",
"6.922", "6.923", "6.924", "6.926", "6.936", "6.937", "6.939",
"6.955", "6.956", "6.958"), class = "factor")

latitude = structure(c(10L, 9L, 6L, 8L, 1L, 5L, 3L, 2L, 7L, 8L, 4L, 10L,
9L, 6L, 8L, 1L, 5L, 3L, 2L, 7L, 8L, 4L), .Label = c("50.911",
"50.918", "50.920", "50.929", "50.930", "50.931", "50.934", "50.950",
"50.965", "50.969"), class = "factor")
</code>```

The original table luftdaten.set contains latitudes, longitudes and particulate matter values. I tried to created a grid:

```<code>coordinates(luftdaten.set) <- ~ latitude + longitude
</code>```

I also tried to create a dataframe with only the coordinates and tried to derive a grid from it:

```<code>luftdaten.grid <- data.frame(latitude, longitude)
luftdaten.grid <- data.frame(latitude, longitude)
</code>```

Both throws the described error.

coordinates is in the SpatialTools 'sp' package.

答:
That way it works:</p>

```<code>longitude <- as.numeric(as.character(longitude))
latitude <- as.numeric(as.character(latitude))
luftdaten.grid <- data.frame(latitude, longitude)
attach(luftdaten.grid)
coordinates(luftdaten.grid) <- ~ latitude + longitude
</code>```

Body:
I have an imported table with longitudes and latitudes and want to create a spatial grid from them.
The coordinates are in this format:

[1] 6.955 6.937 6.956 6.923

So looks numeric for me. But trying to create the grid this Error occurs:

Error in .local(obj, ...) :

        cannot derive coordinates from non-numeric matrix

When I try to change the format using as.numeric I get this result:

[1] 10  9  6  8

How can I convert the coordinates in numeric format without changing the value?

longitude = structure(c(9L, 7L, 10L, 3L, 8L, 4L, 6L, 2L, 11L, 1L, 5L, 9L,
7L, 10L, 3L, 8L, 4L, 6L, 2L, 11L, 1L, 5L), .Label = c("6.920",
"6.922", "6.923", "6.924", "6.926", "6.936", "6.937", "6.939",
"6.955", "6.956", "6.958"), class = "factor")

latitude = structure(c(10L, 9L, 6L, 8L, 1L, 5L, 3L, 2L, 7L, 8L, 4L, 10L,
9L, 6L, 8L, 1L, 5L, 3L, 2L, 7L, 8L, 4L), .Label = c("50.911",
"50.918", "50.920", "50.929", "50.930", "50.931", "50.934", "50.950",
"50.965", "50.969"), class = "factor")

The original table luftdaten.set contains latitudes, longitudes and particulate matter values. I tried to created a grid:

coordinates(luftdaten.set) <- ~ latitude + longitude

I also tried to create a dataframe with only the coordinates and tried to derive a grid from it:

luftdaten.grid <- data.frame(latitude, longitude)
luftdaten.grid <- data.frame(latitude, longitude)

Both throws the described error.

coordinates is in the SpatialTools 'sp' package.

Body:
That way it works:

longitude <- as.numeric(as.character(longitude))
latitude <- as.numeric(as.character(latitude))
luftdaten.grid <- data.frame(latitude, longitude)
attach(luftdaten.grid)
coordinates(luftdaten.grid) <- ~ latitude + longitude


问:
com.sun:tools:jar:1.4.2 missing when running "perform eclipse" in roo
When I run "perform eclipse" in Roo I get:

```<code>roo> perform eclipse
[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] Building bugzter
[INFO]    task-segment: [eclipse:clean, eclipse:eclipse]
[INFO] ------------------------------------------------------------------------
[INFO] [eclipse:clean {execution: default-cli}]
[INFO] Deleting file: .project
[INFO] Deleting file: .classpath
[INFO] Deleting file: .wtpmodules
[INFO] Deleting file: .component
[INFO] Deleting file: org.eclipse.wst.common.component
[INFO] Deleting file: org.eclipse.wst.common.project.facet.core.xml
[INFO] Deleting file: org.eclipse.jdt.core.prefs
[INFO] Deleting file: org.eclipse.ajdt.ui.prefs
[INFO] Preparing eclipse:eclipse
[INFO] ------------------------------------------------------------------------
[ERROR] BUILD ERROR
[INFO] ------------------------------------------------------------------------
[INFO] Failed to resolve artifact.

Missing:
----------
1) com.sun:tools:jar:1.4.2

  Try downloading the file manually from the project website.

  Then, install it using the command:
      mvn install:install-file -DgroupId=com.sun -DartifactId=tools -Dversion=1.4.2 -Dpackaging=jar -Dfile=/path/to/file

  Alternatively, if you host your own repository you can deploy the file there:
      mvn deploy:deploy-file -DgroupId=com.sun -DartifactId=tools -Dversion=1.4.2 -Dpackaging=jar -Dfile=/path/to/file -Durl=[url] -DrepositoryId=[id]

  Path to dependency:
      1) org.codehaus.mojo:aspectj-maven-plugin:maven-plugin:1.0
      2) com.sun:tools:jar:1.4.2

----------
1 required artifact is missing.

for artifact:
  org.codehaus.mojo:aspectj-maven-plugin:maven-plugin:1.0

from the specified remote repositories:
  com.springsource.repository.bundles.release (http://repository.springsource.com/maven/bundles/release),
  com.springsource.repository.bundles.external (http://repository.springsource.com/maven/bundles/external),
  central (http://repo1.maven.org/maven2),
  codehaus.org (http://repository.codehaus.org),
  com.springsource.repository.bundles.milestone (http://repository.springsource.com/maven/bundles/milestone),
  com.springsource.repository.bundles.snapshot (http://repository.springsource.com/maven/bundles/snapshot),
  snapshots (http://snapshots.repository.codehaus.org)

[INFO] ------------------------------------------------------------------------
[INFO] For more information, run Maven with the -e switch
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3 seconds
[INFO] Finished at: Wed Jul 28 20:57:52 CEST 2010
[INFO] Final Memory: 30M/298M
[INFO] ------------------------------------------------------------------------
</code>```

Tried downloaded the tools-1.4.2.jar and run mvn install:install-file -DgroupId=com.sun -DartifactId=tools -Dversion=1.4.2 -Dpackaging=jar -Dfile=/path/to/file but it doesn't solve the problem.

Running ubuntu 10.04 and maven 2.2

Any suggestions?

答: Repoint your system environment parameter JAVA_HOME to JDK (1.5+) directory instead of JRE.</p>

Body:
When I run "perform eclipse" in Roo I get:

roo> perform eclipse
[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] Building bugzter
[INFO]    task-segment: [eclipse:clean, eclipse:eclipse]
[INFO] ------------------------------------------------------------------------
[INFO] [eclipse:clean {execution: default-cli}]
[INFO] Deleting file: .project
[INFO] Deleting file: .classpath
[INFO] Deleting file: .wtpmodules
[INFO] Deleting file: .component
[INFO] Deleting file: org.eclipse.wst.common.component
[INFO] Deleting file: org.eclipse.wst.common.project.facet.core.xml
[INFO] Deleting file: org.eclipse.jdt.core.prefs
[INFO] Deleting file: org.eclipse.ajdt.ui.prefs
[INFO] Preparing eclipse:eclipse
[INFO] ------------------------------------------------------------------------
[ERROR] BUILD ERROR
[INFO] ------------------------------------------------------------------------
[INFO] Failed to resolve artifact.

Missing:
----------
1) com.sun:tools:jar:1.4.2

  Try downloading the file manually from the project website.

  Then, install it using the command:
      mvn install:install-file -DgroupId=com.sun -DartifactId=tools -Dversion=1.4.2 -Dpackaging=jar -Dfile=/path/to/file

  Alternatively, if you host your own repository you can deploy the file there:
      mvn deploy:deploy-file -DgroupId=com.sun -DartifactId=tools -Dversion=1.4.2 -Dpackaging=jar -Dfile=/path/to/file -Durl=[url] -DrepositoryId=[id]

  Path to dependency:
      1) org.codehaus.mojo:aspectj-maven-plugin:maven-plugin:1.0
      2) com.sun:tools:jar:1.4.2

----------
1 required artifact is missing.

for artifact:
  org.codehaus.mojo:aspectj-maven-plugin:maven-plugin:1.0

from the specified remote repositories:
  com.springsource.repository.bundles.release (http://repository.springsource.com/maven/bundles/release),
  com.springsource.repository.bundles.external (http://repository.springsource.com/maven/bundles/external),
  central (http://repo1.maven.org/maven2),
  codehaus.org (http://repository.codehaus.org),
  com.springsource.repository.bundles.milestone (http://repository.springsource.com/maven/bundles/milestone),
  com.springsource.repository.bundles.snapshot (http://repository.springsource.com/maven/bundles/snapshot),
  snapshots (http://snapshots.repository.codehaus.org)

[INFO] ------------------------------------------------------------------------
[INFO] For more information, run Maven with the -e switch
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3 seconds
[INFO] Finished at: Wed Jul 28 20:57:52 CEST 2010
[INFO] Final Memory: 30M/298M
[INFO] ------------------------------------------------------------------------

Tried downloaded the tools-1.4.2.jar and run mvn install:install-file -DgroupId=com.sun -DartifactId=tools -Dversion=1.4.2 -Dpackaging=jar -Dfile=/path/to/file but it doesn't solve the problem.

Running ubuntu 10.04 and maven 2.2

Any suggestions?


答:
```<code>[^ \n]{1,}(@mazur.com)
</code>```

This says to accept anything except a space or a new line, from 1 to many times, and then your website name. I changed it from 0 to 1 because I figured nobody would have an email without something leading in front of it.

But, if it cant match anything except adrian...you could do this. Not such an elegant approach, but this will solve your problem.

```<code>a(\.+)?d(\.+)?r(\.+)?i(\.+)?a(\.+)?n(.+)?(@mazur\.com)
</code>```

Title: How to ignore a dot (.) in regex?

Body:
I have this:

(adrian)(@mazur.com)|(^(adrian)\+(.*)@mazur.com$)

It matches these only partially:

adrian@mazur.com
adrian+whatever@mazur.com
adrian+what.ev.er@mazur.com
a.d.r.i.a.n@mazur.com
a.d.r.i.a.n+whatever@mazur.com
a..drian@mazur.com

They also can't match those:

patryk@mazur.com
patryk+whatever@mazur.com
patryk+what.ev.er@mazur.com
p.a.t.r.y.k@mazur.com
p.a.t.r.y.k+whatever@mazur.com
p..adtryk@mazur.com
p.dra..us...@mazur.com

or other like danuta, micheal, ryan, sean etc.

How do I make it ignore the dot (.) between my name?
I use this tool to test the regex: http://74.50.60.193/ it's http://www.rubular.com/ but it doesn't resolve for me so I put IP too.

Body:
[^ \n]{1,}(@mazur.com)

This says to accept anything except a space or a new line, from 1 to many times, and then your website name. I changed it from 0 to 1 because I figured nobody would have an email without something leading in front of it.

But, if it cant match anything except adrian...you could do this. Not such an elegant approach, but this will solve your problem.

a(\.+)?d(\.+)?r(\.+)?i(\.+)?a(\.+)?n(.+)?(@mazur\.com)


问:
Derived class initialization with parameter of another derived class
I am new in Abstract classes so please excuse any ignorant mistakes

The exercise is given from my school, so the main.cpp file is to be used, almost as it is

I am trying to create a simple calculator in Eclipse using C++11

There exists a simple Abstract class with two virtual methods.

The two derived classes are simply the "Result" and the "Const" classes.
This is the header file of the Abstract class called

Expression.h

```<code>class Expression
{
public:
    Expression();
    virtual ~Expression();
   //methods
};
</code>```

Following is the source file of Expression

Expression.cpp

```<code>#include "expression.h"
#include <iostream>

Expression::Expression(){}
Expression::~Expression(){}
</code>```

Then I have created two classes called Const and Result

Const.h

```<code>#include <iostream>
#include "expression.h"

class  Const : public Expression
{
public:
    Const(int value);
    //inherited methods
private:
    int value;
};
</code>```

and the source file

Const.cpp

```<code>#include "expression.h"
#include "Const.h"

Const::Const(int x)
{
    value=x;
};

//inherited methods
</code>```

Result.h

```<code>#include <iostream>
#include "expression.h"
#include "Const.h"

class  Result : public Expression
{
public:
    Result(Const& c);
    //inherited methods
private:
    double value;
};
</code>```

Result.cpp

```<code>#include "expression.h"
#include "Result.h"
Result::Result(Const& c)
{
    value=c.point;
};
//inherited methods
</code>```

So what i need is to understand

main.cpp

```<code>#include <iostream>
#include "expression.h"
#include "const.h"
#include "result.h"
void testResult()
{
    Result  res (new Const(4));
    //Here an inherited method will be used to print the contents of object res
}
int main()
{
    testResult();
    return 0;
}
</code>```

The problem i can't solve is the line

```<code>Result res (new Const(4));
</code>```

The error i get is

Conversion from 'Const* to non-scalar type 'Result' requested

The thing is that what is described in this line should be used as it is, and i can't seem to find exactly what it is.

EDIT

The question as asked firstly was apparently misleading due to my fault, tried to fix the question so as to describe exactly my problem

答:
If you had two derived classes DerivedClass1 and DerivedClass2 both derived from some BaseClass then to instantiate a pointer to a DerivedClass1 and use it in polymorphic way use:

```<code>BaseClass* p = new DerivedClass1;
</code>```

To create a base class pointer to a DerivedClass2 use:

```<code>BaseClass* p = new DerivedClass2;
</code>```

And not the:

```<code>DerivedClass1* p = new DerivedClass2;
</code>```

In your example both Result and Const classes are derived from Expression class hence the confusion. To pass in an argument of SomeClass& type, create a temporary object of SomeClass and pass it in:

```<code>SomeClass o;
someFunction(o);
</code>```

Body:
I am new in Abstract classes so please excuse any ignorant mistakes

The exercise is given from my school, so the main.cpp file is to be used, almost as it is

I am trying to create a simple calculator in Eclipse using C++11

There exists a simple Abstract class with two virtual methods.

The two derived classes are simply the "Result" and the "Const" classes.
This is the header file of the Abstract class called

Expression.h

class Expression
{
public:
    Expression();
    virtual ~Expression();
   //methods
};

Following is the source file of Expression

Expression.cpp

#include "expression.h"
#include <iostream>

Expression::Expression(){}
Expression::~Expression(){}

Then I have created two classes called Const and Result

Const.h

#include <iostream>
#include "expression.h"

class  Const : public Expression
{
public:
    Const(int value);
    //inherited methods
private:
    int value;
};

and the source file

Const.cpp

#include "expression.h"
#include "Const.h"

Const::Const(int x)
{
    value=x;
};

//inherited methods

Result.h

#include <iostream>
#include "expression.h"
#include "Const.h"

class  Result : public Expression
{
public:
    Result(Const& c);
    //inherited methods
private:
    double value;
};

Result.cpp

#include "expression.h"
#include "Result.h"
Result::Result(Const& c)
{
    value=c.point;
};
//inherited methods

So what i need is to understand

main.cpp

#include <iostream>
#include "expression.h"
#include "const.h"
#include "result.h"
void testResult()
{
    Result  res (new Const(4));
    //Here an inherited method will be used to print the contents of object res
}
int main()
{
    testResult();
    return 0;
}

The problem i can't solve is the line

Result res (new Const(4));

The error i get is

Conversion from 'Const* to non-scalar type 'Result' requested

The thing is that what is described in this line should be used as it is, and i can't seem to find exactly what it is.

EDIT

The question as asked firstly was apparently misleading due to my fault, tried to fix the question so as to describe exactly my problem

Body:
If you had two derived classes DerivedClass1 and DerivedClass2 both derived from some BaseClass then to instantiate a pointer to a DerivedClass1 and use it in polymorphic way use:

BaseClass* p = new DerivedClass1;

To create a base class pointer to a DerivedClass2 use:

BaseClass* p = new DerivedClass2;

And not the:

DerivedClass1* p = new DerivedClass2;

In your example both Result and Const classes are derived from Expression class hence the confusion. To pass in an argument of SomeClass& type, create a temporary object of SomeClass and pass it in:

SomeClass o;
someFunction(o);