问:
Invalid UTF-8 middle byte 0x72
I am using JsonSerializer and JsonDeserializer in spring-kafka to set the value serializer while producing a message.
The message has one field(orgName)with a special character in it (german umlaut).How do I handle this special character? I know JsonDeserializer uses jackson and jackson supports utf-8.
The JsonDeserializer throws this error because of it:</p>

```<code>Caused by: com.fasterxml.jackson.databind.JsonMappingException: Invalid UTF-8 middle byte 0x72
 at [Source: [B@403d4534; line: 1, column: 128]
 at [Source: [B@403d4534; line: 1, column: 116] (through reference chain: com.abc-company.kafka.JobRequest["orgName"])
    at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:388) ~[jackson-databind-2.8.5.jar:2.8.5]
    at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:348) ~[jackson-databind-2.8.5.jar:2.8.5]
    at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.wrapAndThrow(BeanDeserializerBase.java:1599) ~[jackson-databind-2.8.5.jar:2.8.5]
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:359) ~[jackson-databind-2.8.5.jar:2.8.5]
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:148) ~[jackson-databind-2.8.5.jar:2.8.5]
    at com.fasterxml.jackson.databind.ObjectReader._bindAndClose(ObjectReader.java:1626) ~[jackson-databind-2.8.5.jar:2.8.5]
    at com.fasterxml.jackson.databind.ObjectReader.readValue(ObjectReader.java:1237) ~[jackson-databind-2.8.5.jar:2.8.5]
    at org.springframework.kafka.support.serializer.JsonDeserializer.deserialize(JsonDeserializer.java:86) ~[spring-kafka-1.1.2.RELEASE.jar:na]
</code>```

答:
Your Deserializer uses UTF-8, but your Serializer uses another encoding, for example, ISO 8859-1. To solve this problem, you must set the encoding of the Serializer to UTF-8.

For an explanation why this error occurs, see this answer to a similar question.

Title: Invalid UTF-8 middle byte 0x72

Body:
I am using JsonSerializer and JsonDeserializer in spring-kafka to set the value serializer while producing a message.
The message has one field(orgName)with a special character in it (german umlaut).How do I handle this special character? I know JsonDeserializer uses jackson and jackson supports utf-8.
The JsonDeserializer throws this error because of it:

Caused by: com.fasterxml.jackson.databind.JsonMappingException: Invalid UTF-8 middle byte 0x72
 at [Source: [B@403d4534; line: 1, column: 128]
 at [Source: [B@403d4534; line: 1, column: 116] (through reference chain: com.abc-company.kafka.JobRequest["orgName"])
    at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:388) ~[jackson-databind-2.8.5.jar:2.8.5]
    at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:348) ~[jackson-databind-2.8.5.jar:2.8.5]
    at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.wrapAndThrow(BeanDeserializerBase.java:1599) ~[jackson-databind-2.8.5.jar:2.8.5]
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:359) ~[jackson-databind-2.8.5.jar:2.8.5]
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:148) ~[jackson-databind-2.8.5.jar:2.8.5]
    at com.fasterxml.jackson.databind.ObjectReader._bindAndClose(ObjectReader.java:1626) ~[jackson-databind-2.8.5.jar:2.8.5]
    at com.fasterxml.jackson.databind.ObjectReader.readValue(ObjectReader.java:1237) ~[jackson-databind-2.8.5.jar:2.8.5]
    at org.springframework.kafka.support.serializer.JsonDeserializer.deserialize(JsonDeserializer.java:86) ~[spring-kafka-1.1.2.RELEASE.jar:na]


来源: stackexchange

问:
Compare hashMap arrays values with Javascript
How to compare between two Hashmaps that contains arrays in their values with javascript?

Example : Let suppose this is my 2 hashmaps

1st =>

```<code>1234 : [1.03 , 2.17 , 3]
1235 : [1 , 4 , 5]
1236 : [2 , 3 , 3]
1237 : [0.33 , 1.51 , 5]
</code>```

2nd =>

```<code>1234 : [1.03 , 2.17 , 3]
1235 : [1.17 , 2 , 3.9]
1236 : [2 , 3 , 3]
1237 : [2 , 1 , 5]
</code>```

Result =>

```<code>1235 : [1 , 4 , 5]
1237 : [0.33 , 1.51 , 5]
</code>```

(the goal is to compare the first with the second and display what keys and values of the first hashmap that aren't coherent).

答:
I did this at the beginning when my values was String and not arrays :

```<code>compareHashMap: function(iAdaptation, iActual){
                var difference = {};
                Object.keys(iActual).forEach(function(k){
                    if(iAdaptation[k] !== iActual[k]){
                        difference[k] = iActual[k];
                    }
                });
                return difference;
            },
</code>```

P.S : iAdaptation and iActual are hashmaps

ContentLicense: CC BY-SA 3.0

Body:
How to compare between two Hashmaps that contains arrays in their values with javascript?

Example : Let suppose this is my 2 hashmaps

1st =>

1234 : [1.03 , 2.17 , 3]
1235 : [1 , 4 , 5]
1236 : [2 , 3 , 3]
1237 : [0.33 , 1.51 , 5]

2nd =>

1234 : [1.03 , 2.17 , 3]
1235 : [1.17 , 2 , 3.9]
1236 : [2 , 3 , 3]
1237 : [2 , 1 , 5]

Result =>

1235 : [1 , 4 , 5]
1237 : [0.33 , 1.51 , 5]

(the goal is to compare the first with the second and display what keys and values of the first hashmap that aren't coherent).

Body:
I did this at the beginning when my values was String and not arrays :

compareHashMap: function(iAdaptation, iActual){
                var difference = {};
                Object.keys(iActual).forEach(function(k){
                    if(iAdaptation[k] !== iActual[k]){
                        difference[k] = iActual[k];
                    }
                });
                return difference;
            },

P.S : iAdaptation and iActual are hashmaps


问:
Intellij break point stops execution two times even though code is executed only once
I have the below class:

```<code>package com.example;

public class Main {
    public static void main(String[] args) {
      System.out.println(Integer.toString(Math.abs(1)));
      System.out.println(Integer.toString(
            Math.abs(-2)));

    }
}
</code>```

I put two break points for the first two lines after the main method declaration.
For the second brake point the execution stops two times(I have to press F8 two times to resume the program) and I do not understand why.

I noticed that this happens only when the Math.abs method call is placed on the next line(So the first break point works properly).

Can someone please explain if there is any particular reason intellij stops execution two times even though, if I run this program and check the output, I can tell for sure that the code is only executed once?

I tried and did not manage to reproduce this issue in Eclipse.

答: Please check https://youtrack.jetbrains.com/issue/IDEA-144462, it is being discussed with Oracle, but still no solution found :(</p>

Body:
I have the below class:

package com.example;

public class Main {
    public static void main(String[] args) {
      System.out.println(Integer.toString(Math.abs(1)));
      System.out.println(Integer.toString(
            Math.abs(-2)));

    }
}

I put two break points for the first two lines after the main method declaration.
For the second brake point the execution stops two times(I have to press F8 two times to resume the program) and I do not understand why.

I noticed that this happens only when the Math.abs method call is placed on the next line(So the first break point works properly).

Can someone please explain if there is any particular reason intellij stops execution two times even though, if I run this program and check the output, I can tell for sure that the code is only executed once?

I tried and did not manage to reproduce this issue in Eclipse.


问:
Multiple spaces in command CMD
Ok so i am trying to flash a hex file onto my arduino pro micro following this sorta guide:

https://www.reddit.com/r/MechanicalKeyboards/comments/69woay/hand_built_keypad_gateron_blues_first_hand_wire/

And I am really struggling with step 2. The problem that i am having is that my thing (Not sure what to call it) looks like this:

```<code>""C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude" "-CC:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf" -v -patmega32u4 -cavr109 -PCOM5 -b57600 -D -Uflash:wC:"\Users\My Name\Desktop\Layout\layout.hex:i""
</code>```

I am getting a this error:

```<code>'""C:\Program' is not recognized as an internal or external command,
</code>```

operable program or batch file.

Which i tried fixing with the speech marks following these recommendations:

How do I specify C:\Program Files without a space in it for programs that can't handle spaces in file paths?

How to use spaces in CMD?

So that's the issue i am probably making one minor mistake or many major ones, but you help would be greatly appreciated.

答:
Let's analyze your string

```<code>""C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude" "-CC:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf" -v -patmega32u4 -cavr109 -PCOM5 -b57600 -D -Uflash:wC:"\Users\My Name\Desktop\Layout\layout.hex:i""
</code>```

The problem occurs right away with your double quote "". This is interpreted as an empty string between these two quotes. Thus making your C:\Program Files end up outside quotes.

Try this instead

```<code>"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude" "-CC:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf" -v -patmega32u4 -cavr109 -PCOM5 -b57600 -D -Uflash:wC:"\Users\My Name\Desktop\Layout\layout.hex:i"
</code>```

Title: Multiple spaces in command CMD

Body:
Ok so i am trying to flash a hex file onto my arduino pro micro following this sorta guide:

https://www.reddit.com/r/MechanicalKeyboards/comments/69woay/hand_built_keypad_gateron_blues_first_hand_wire/

And I am really struggling with step 2. The problem that i am having is that my thing (Not sure what to call it) looks like this:

""C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude" "-CC:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf" -v -patmega32u4 -cavr109 -PCOM5 -b57600 -D -Uflash:wC:"\Users\My Name\Desktop\Layout\layout.hex:i""

I am getting a this error:

'""C:\Program' is not recognized as an internal or external command,

operable program or batch file.

Which i tried fixing with the speech marks following these recommendations:

How do I specify C:\Program Files without a space in it for programs that can't handle spaces in file paths?

How to use spaces in CMD?

So that's the issue i am probably making one minor mistake or many major ones, but you help would be greatly appreciated.

Body:
Let's analyze your string

""C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude" "-CC:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf" -v -patmega32u4 -cavr109 -PCOM5 -b57600 -D -Uflash:wC:"\Users\My Name\Desktop\Layout\layout.hex:i""

The problem occurs right away with your double quote "". This is interpreted as an empty string between these two quotes. Thus making your C:\Program Files end up outside quotes.

Try this instead

"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude" "-CC:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf" -v -patmega32u4 -cavr109 -PCOM5 -b57600 -D -Uflash:wC:"\Users\My Name\Desktop\Layout\layout.hex:i"


问:
String arrays in float arrays without format change
Is there a way to include strings in an array of floats without the format of the array changing such that all floats are changed to strings but the string element is still kept as a string?

eg.

```<code>import numpy as np

a = np.array([ 'hi' , 1. , 2. , 3. ])
</code>```

Ideally I would like the format to remain the same as how it looks when input as 'a' above.

This gives:

```<code>array(['hi', '1.0', '2.0', '3.0'], dtype='|S3')
</code>```

And then how would one save such an array as a text file?

Many thanks,

J

答:
I'm guessing your problem is this: you want to dump out the array np.array([ 'hi' , 1. , 2. , 3. ]) using np.savetxt() but are getting this error:

```<code>TypeError: Mismatch between array dtype ('|S3') and format specifier ('%.18e')
</code>```

If this is the case, you just need to set the fmt kwarg in np.savetxt. Instead of the default %.18e, which is for formatting floating point data, you can use %s, which formats things as a string, even if the original value in the array was numerical.

So this will work:

```<code>import numpy as np
a = np.array([ 'hi' , 1. , 2. , 3. ])
np.savetxt("test.out",a,fmt="%s")
</code>```

Note that you can just do this with the original list - numpy will convert it to an array for you. So for example you can do:

```<code>np.savetxt("test.out",[ 'hi' , 1. , 2. , 3. ],fmt="%s")
</code>```

and it should work fine too.

For the first part of the question, this is not really what numpy arrays are intended for. If you are trying to put different data types into the same array, then you probably want a different data structure. A vanilla python list would do it, but depending on your situation, a dict is probably what you're looking for.

Edit: Based on the comment threads & the specific question, it looks like this is an attempt to make a header on a data file. This can be done directly through

```<code>np.savetxt("a.txt",a,header="title goes here")
</code>```

This can be read directly with np.loadtxt() because by default the header is prepended with #, and by default np.loadtxt() ignores lines that start with #.

Body:
Is there a way to include strings in an array of floats without the format of the array changing such that all floats are changed to strings but the string element is still kept as a string?

eg.

import numpy as np

a = np.array([ 'hi' , 1. , 2. , 3. ])

Ideally I would like the format to remain the same as how it looks when input as 'a' above.

This gives:

array(['hi', '1.0', '2.0', '3.0'], dtype='|S3')

And then how would one save such an array as a text file?

Many thanks,

J

Body:
I'm guessing your problem is this: you want to dump out the array np.array([ 'hi' , 1. , 2. , 3. ]) using np.savetxt() but are getting this error:

TypeError: Mismatch between array dtype ('|S3') and format specifier ('%.18e')

If this is the case, you just need to set the fmt kwarg in np.savetxt. Instead of the default %.18e, which is for formatting floating point data, you can use %s, which formats things as a string, even if the original value in the array was numerical.

So this will work:

import numpy as np
a = np.array([ 'hi' , 1. , 2. , 3. ])
np.savetxt("test.out",a,fmt="%s")

Note that you can just do this with the original list - numpy will convert it to an array for you. So for example you can do:

np.savetxt("test.out",[ 'hi' , 1. , 2. , 3. ],fmt="%s")

and it should work fine too.

For the first part of the question, this is not really what numpy arrays are intended for. If you are trying to put different data types into the same array, then you probably want a different data structure. A vanilla python list would do it, but depending on your situation, a dict is probably what you're looking for.

Edit: Based on the comment threads & the specific question, it looks like this is an attempt to make a header on a data file. This can be done directly through

np.savetxt("a.txt",a,header="title goes here")

This can be read directly with np.loadtxt() because by default the header is prepended with #, and by default np.loadtxt() ignores lines that start with #.


问:
In Delphi: How to skip sections of code while debugging?
I often accidently step into code that I'm not interested in while debugging in Delphi.

Let's start by saying that I know that you can step over with F8, and that you can run to a certain line with f4.

Example:

```<code>function TMyClass.DoStuff():Integer;
begin
  // do some stuff
  bla();
end;

procedure TMyClass.Foo()
begin
  if DoStuff()=0 then // press F7 when entering this line
    beep;
end;
</code>```

Example: I want to step into method DoStuff() by pressing F7, but instead of going there, I first end up in FastMM4.FastGetMem(), which is a massive blob of assembly code that obviously I'm not interested in at the moment.

There are several ways to go about this, and I don't like any of them:

Add a breakpoint on "bla" (almost useless if you only want to step into DoStuff on special occasions, like iteration 23498938);

Instead of pressing F7, manually move the cursor to "bla", and press F4 (Works for this simple example. In practice, it doesn't);

In case of FastMM: temporarily disable fastmm;

Is there any way to hint the IDE that I'm never interested into stepping into a certain block of code, or do I always have to set extra breakpoints or use F4 to try to avoid this?

I'm hoping for some magic compiler directive like {$NODEBUG BEGIN/END} or something like that.

In most cases being able to exclude entire units would be fine-grained enough for me, but being able to avoid certain methods or even lines of code would be even better.

Update: Maybe codegear should introduce something like skip-points (as opposed to break-points) :-)

答:
No. I don't believe there is a way to tell the debugger to never stop in a certain section of code. There is no magic directive.

The best you can do when you get into a routine you don't want to be in is to use Shift+F8 which will Run until the Return. Then do a F7 or F8 to exit the procedure.

Hmmm. Now I see Mason's answer. Learned something. Thanks, Mason. +1

OwnerDisplayName: Wouter van Nifterick

ContentLicense: CC BY-SA 2.5

Body:
I often accidently step into code that I'm not interested in while debugging in Delphi.

Let's start by saying that I know that you can step over with F8, and that you can run to a certain line with f4.

Example:

function TMyClass.DoStuff():Integer;
begin
  // do some stuff
  bla();
end;

procedure TMyClass.Foo()
begin
  if DoStuff()=0 then // press F7 when entering this line
    beep;
end;

Example: I want to step into method DoStuff() by pressing F7, but instead of going there, I first end up in FastMM4.FastGetMem(), which is a massive blob of assembly code that obviously I'm not interested in at the moment.

There are several ways to go about this, and I don't like any of them:

Add a breakpoint on "bla" (almost useless if you only want to step into DoStuff on special occasions, like iteration 23498938);

Instead of pressing F7, manually move the cursor to "bla", and press F4 (Works for this simple example. In practice, it doesn't);

In case of FastMM: temporarily disable fastmm;

Is there any way to hint the IDE that I'm never interested into stepping into a certain block of code, or do I always have to set extra breakpoints or use F4 to try to avoid this?

I'm hoping for some magic compiler directive like {$NODEBUG BEGIN/END} or something like that.

In most cases being able to exclude entire units would be fine-grained enough for me, but being able to avoid certain methods or even lines of code would be even better.

Update: Maybe codegear should introduce something like skip-points (as opposed to break-points) :-)

LastEditorDisplayName: Wouter van Nifterick

OwnerDisplayName: lkessler


问:
MSMQ Message Viewer?
I have messages in a MSMQ queue and I would like to view the full message.

I know I can write code to peek the queue, but was wondering if there is a viewer that already exists that will let me read the entire message?

答:
There are a few options - all I found are commercial (not terribly expensive, but not free, either):

Mqueue Viewer (free)

Mulholland Q Set

QueueExplorer

Title: MSMQ Message Viewer?


问:
How to tell a qml binding about additional dependencies?
I have a C++ implemented Quick Item and it offeres multiple properties and Q_INVOKABLE methods with return values. Most of these methods depend on these properties.

Can I define a notify signal for methods? Or when binding to it, can I add additional dependencies so the method is evaluated again?

In this example I want all text items to be updated whenever theItem.something changes.

```<code>SimpleCppItem {
    id: theItem
    something: theSpinBox.value
}

RowLayout {
    SpinBox { id: theSpinBox; }

    Repeater {
        model: 10
        Text { text: theItem.computeWithSomething(index) }
    }
}
</code>```

The implementation of the SimpleCppItem looks like this:

```<code>class SimpleCppItem : public QQuickItem
{
    Q_OBJECT
    Q_PROPERTY(int something READ something WRITE setSomething NOTIFY somethingChanged)

public:
    explicit SimpleCppItem(QQuickItem *parent = Q_NULLPTR) :
        QQuickItem(parent),
        m_something(0)
    { }

    Q_INVOKABLE int computeWithSomething(int param)
    { return m_something + param; } //The result depends on something and param

    int something() const { return m_something; }
    void setSomething(int something)
    {
        if(m_something != something)
            Q_EMIT somethingChanged(m_something = something);
    }

Q_SIGNALS:
    void somethingChanged(int something);

private:
    int m_something;
};
</code>```

答:
That is not possible with functions. But there are some workarouds:

"Small Hack" (You get warning M30: Warning, Do not use comma expressions Thanks to GrecKo, no warning anymore!

```<code>Repeater {
        model: 10
        Text {
            text: {theItem.something; return theItem.computeWithSomething(index);}
        }
    }
</code>```

Or you connect every item in the repeater with the "somethingChanged" signal:

```<code>Repeater {
    model: 10
    Text {
        id: textBox
        text: theItem.computeWithSomething(index)
        Component.onCompleted: {
            theItem.somethingChanged.connect(updateText)
        }
        function updateText() {
            text = theItem.computeWithSomething(index)
        }
    }
}
</code>```

===== ORIGNAL QUESTION =====

You can catch the signal in the QML file like this:

```<code>SimpleCppItem {
    id: theItem
    something: theSpinBox.value

    onSomethingChanged() {
       consoloe.log("Catched: ",something)
       //something ist the name of the parameter
    }
}
</code>```

Body:
I have a C++ implemented Quick Item and it offeres multiple properties and Q_INVOKABLE methods with return values. Most of these methods depend on these properties.

Can I define a notify signal for methods? Or when binding to it, can I add additional dependencies so the method is evaluated again?

In this example I want all text items to be updated whenever theItem.something changes.

SimpleCppItem {
    id: theItem
    something: theSpinBox.value
}

RowLayout {
    SpinBox { id: theSpinBox; }

    Repeater {
        model: 10
        Text { text: theItem.computeWithSomething(index) }
    }
}

The implementation of the SimpleCppItem looks like this:

class SimpleCppItem : public QQuickItem
{
    Q_OBJECT
    Q_PROPERTY(int something READ something WRITE setSomething NOTIFY somethingChanged)

public:
    explicit SimpleCppItem(QQuickItem *parent = Q_NULLPTR) :
        QQuickItem(parent),
        m_something(0)
    { }

    Q_INVOKABLE int computeWithSomething(int param)
    { return m_something + param; } //The result depends on something and param

    int something() const { return m_something; }
    void setSomething(int something)
    {
        if(m_something != something)
            Q_EMIT somethingChanged(m_something = something);
    }

Q_SIGNALS:
    void somethingChanged(int something);

private:
    int m_something;
};

Body:
That is not possible with functions. But there are some workarouds:

"Small Hack" (You get warning M30: Warning, Do not use comma expressions Thanks to GrecKo, no warning anymore!

Repeater {
        model: 10
        Text {
            text: {theItem.something; return theItem.computeWithSomething(index);}
        }
    }

Or you connect every item in the repeater with the "somethingChanged" signal:

Repeater {
    model: 10
    Text {
        id: textBox
        text: theItem.computeWithSomething(index)
        Component.onCompleted: {
            theItem.somethingChanged.connect(updateText)
        }
        function updateText() {
            text = theItem.computeWithSomething(index)
        }
    }
}

===== ORIGNAL QUESTION =====

You can catch the signal in the QML file like this:

SimpleCppItem {
    id: theItem
    something: theSpinBox.value

    onSomethingChanged() {
       consoloe.log("Catched: ",something)
       //something ist the name of the parameter
    }
}


问:
Regular expression to match 1.* only
I've tried various regular expression but can't get this one quite right.

I need to match 1.* so that means it has to be a 1 followed by a dot and any 1 or 2 digit number following the dot.

So examples of valid matches:

```<code>1.8
1.9
1.11
1.99
</code>```

Invalid:

```<code>2.1
9.19
1.111
</code>```

答:
This one is pretty simple:

```<code>^1\.\d{1,2}$
</code>```

Explanation:

```<code>^     Start of Line
1     match 1
\.    match Dot, Dot needs to be escaped, otherwise it will match any Character
\d    match a Digit
{1,2} Length of the Digit is 1 to 2 Characters
$     End of Line
</code>```

Title: Regular expression to match 1.* only

Body:
I've tried various regular expression but can't get this one quite right.

I need to match 1.* so that means it has to be a 1 followed by a dot and any 1 or 2 digit number following the dot.

So examples of valid matches:

1.8
1.9
1.11
1.99

Invalid:

2.1
9.19
1.111

Body:
This one is pretty simple:

^1\.\d{1,2}$

Explanation:

^     Start of Line
1     match 1
\.    match Dot, Dot needs to be escaped, otherwise it will match any Character
\d    match a Digit
{1,2} Length of the Digit is 1 to 2 Characters
$     End of Line


问:
How to make results of a join statement a new table
I have the following mysql query. How can i make the result of the query be a new table;</p>

```<code>SELECT t1.referree AS LEVEL1, t2.referree AS LEVEL2, t3.referree AS LEVEL3, t4.referree AS LEVEL4, t5.referree AS LEVEL5, t6.referree AS LEVEL6, t7.referree AS LEVEL7, t8.referree AS LEVEL8, t9.referree AS LEVEL9, t10.referree LEVEL10, t11.referree AS LEVEL11
                                        FROM referrals AS t1
                                        LEFT JOIN referrals AS t2 ON t2.referrer = t1.referree
                                        LEFT JOIN referrals AS t3 ON t3.referrer = t2.referree
                                        LEFT JOIN referrals AS t4 ON t4.referrer = t3.referree
                                        LEFT JOIN referrals AS t5 ON t5.referrer = t4.referree
                                        LEFT JOIN referrals AS t6 ON t6.referrer = t5.referree
                                        LEFT JOIN referrals AS t7 ON t7.referrer = t6.referree
                                        LEFT JOIN referrals AS t8 ON t8.referrer = t7.referree
                                        LEFT JOIN referrals AS t9 ON t9.referrer = t8.referree
                                        LEFT JOIN referrals AS t10 ON t10.referrer = t9.referree
                                        LEFT JOIN referrals AS t11 ON t11.referrer = t10.referree
                                        WHERE t1.referrer ='2'));
</code>```

答:
assuming all the columns are varchar(10) datatype, try this syntax :</p>

```<code>CREATE TABLE new_table (Level1 varchar(10),Level2 varchar(10),Level3 varchar(10),Level4 varchar(10),Level5 varchar(10),Level6 varchar(10),Level7 varchar(10),Level8 varchar(10),Level9 varchar(10),Level10 varchar(10),Level11 varchar(10))
SELECT
t1.referree AS LEVEL1,
t2.referree AS LEVEL2,
 t3.referree AS LEVEL3,
t4.referree AS LEVEL4,
t5.referree AS LEVEL5,
t6.referree AS LEVEL6,
t7.referree AS LEVEL7,
t8.referree AS LEVEL8,
t9.referree AS LEVEL9,
t10.referree LEVEL10,
t11.referree AS LEVEL11
FROM
referrals AS t1 LEFT JOIN referrals AS t2
ON t2.referrer = t1.referree
LEFT JOIN referrals AS t3
ON t3.referrer = t2.referree
LEFT JOIN referrals AS t4
ON t4.referrer = t3.referree
LEFT JOIN referrals AS t5
ON t5.referrer = t4.referree
LEFT JOIN referrals AS t6
ON t6.referrer = t5.referree
LEFT JOIN referrals AS t7
ON t7.referrer = t6.referree
LEFT JOIN referrals AS t8
ON t8.referrer = t7.referree
LEFT JOIN referrals AS t9
ON t9.referrer = t8.referree
LEFT JOIN referrals AS t10
ON t10.referrer = t9.referree
LEFT JOIN referrals AS t11
ON t11.referrer = t10.referree
WHERE
t1.referrer ='2'));
</code>```

Body:
I have the following mysql query. How can i make the result of the query be a new table;

SELECT t1.referree AS LEVEL1, t2.referree AS LEVEL2, t3.referree AS LEVEL3, t4.referree AS LEVEL4, t5.referree AS LEVEL5, t6.referree AS LEVEL6, t7.referree AS LEVEL7, t8.referree AS LEVEL8, t9.referree AS LEVEL9, t10.referree LEVEL10, t11.referree AS LEVEL11
                                        FROM referrals AS t1
                                        LEFT JOIN referrals AS t2 ON t2.referrer = t1.referree
                                        LEFT JOIN referrals AS t3 ON t3.referrer = t2.referree
                                        LEFT JOIN referrals AS t4 ON t4.referrer = t3.referree
                                        LEFT JOIN referrals AS t5 ON t5.referrer = t4.referree
                                        LEFT JOIN referrals AS t6 ON t6.referrer = t5.referree
                                        LEFT JOIN referrals AS t7 ON t7.referrer = t6.referree
                                        LEFT JOIN referrals AS t8 ON t8.referrer = t7.referree
                                        LEFT JOIN referrals AS t9 ON t9.referrer = t8.referree
                                        LEFT JOIN referrals AS t10 ON t10.referrer = t9.referree
                                        LEFT JOIN referrals AS t11 ON t11.referrer = t10.referree
                                        WHERE t1.referrer ='2'));

Body:
assuming all the columns are varchar(10) datatype, try this syntax :

CREATE TABLE new_table (Level1 varchar(10),Level2 varchar(10),Level3 varchar(10),Level4 varchar(10),Level5 varchar(10),Level6 varchar(10),Level7 varchar(10),Level8 varchar(10),Level9 varchar(10),Level10 varchar(10),Level11 varchar(10))
SELECT
t1.referree AS LEVEL1,
t2.referree AS LEVEL2,
 t3.referree AS LEVEL3,
t4.referree AS LEVEL4,
t5.referree AS LEVEL5,
t6.referree AS LEVEL6,
t7.referree AS LEVEL7,
t8.referree AS LEVEL8,
t9.referree AS LEVEL9,
t10.referree LEVEL10,
t11.referree AS LEVEL11
FROM
referrals AS t1 LEFT JOIN referrals AS t2
ON t2.referrer = t1.referree
LEFT JOIN referrals AS t3
ON t3.referrer = t2.referree
LEFT JOIN referrals AS t4
ON t4.referrer = t3.referree
LEFT JOIN referrals AS t5
ON t5.referrer = t4.referree
LEFT JOIN referrals AS t6
ON t6.referrer = t5.referree
LEFT JOIN referrals AS t7
ON t7.referrer = t6.referree
LEFT JOIN referrals AS t8
ON t8.referrer = t7.referree
LEFT JOIN referrals AS t9
ON t9.referrer = t8.referree
LEFT JOIN referrals AS t10
ON t10.referrer = t9.referree
LEFT JOIN referrals AS t11
ON t11.referrer = t10.referree
WHERE
t1.referrer ='2'));


问:
C++ Concepts Lite: Short-circuiting in concept bodies
I am trying to learn about the Concepts Lite TS that is yet to be merged into the standard. I'm confused about the behavior of short-circuiting disjunctions in concept bodies.

Here is a small example:

```<code>#include <type_traits>
#include <iostream>

template <typename T, typename ... Ts> concept bool myconcept =
(sizeof...(Ts) == 0) || (std::is_same_v<T, std::common_type_t<Ts...>>);

template <typename ... Ts>
void myfunc(Ts ... args) requires myconcept<int, Ts...> {
    (... , (std::cout << args << std::endl));
}

int main() {
    myfunc();
    return 0;
}
</code>```

Compiling with gcc 7.1 and -fconcepts, gives the error:

```<code>error: cannot call function 'void myfunc(Ts ...) requires  myconcept<int, Ts ...> [with Ts = {}]'
</code>```

In this example, std::common_type_t<Ts...> does not exist since the struct std::common_type<Ts...> does not have a member type if Ts = {}. However, I think this should compile because cppereference.com's documentation on concepts and constraints states that

Disjunctions are evaluated left to right and short-circuited (if the left constraint is satisfied, template argument deduction into the right constraint is not attempted).

Since sizeof...(Ts) == 0 is satisfied, template argument deduction should not be attempted on the second constraint and the requirement myconcept<int, Ts...> should be satisfied.

Strangely, placing the requirements directly into the function declarator causes the program to compile:

```<code>#include <type_traits>
#include <iostream>

template <typename ... Ts>
void myfunc(Ts ... args) requires (sizeof...(Ts) == 0) || (std::is_same_v<int, std::common_type_t<Ts...>>) {
    (... , (std::cout << args << std::endl));
}

int main() {
    myfunc();
    return 0;
}
</code>```

Is there a good explanation for this behavior?
Thanks.

答:
The layman’s explanation that appears on cppreference is correct. Select wording from the n4674 draft is quite clear as well:

A conjunction is a constraint taking two operands. A conjunction of constraints is satisfied if and only if both operands are satisfied. The satisfaction of a conjunction’s operands are evaluated left-to-right; if the left operand is not satisfied, template arguments are not substituted into the right operand, and the constraint is not satisfied. […]

(From 17.10.1.1 Logical operations [temp.constr.op] §2.) Since all of the wording that precisely establish how we go from concepts and templates to the conjunction or disjunction of atomic constraints is quite long, we will stick to the layman’s explanation.

Is there a good explanation for this behavior? Thanks.

As of this writing the GCC implementation of concepts is very much experimental. As a workaround you can refactor the problematic part into its own concept:

```<code>template<typename T, typename... Ts>
concept bool refactored = std::is_same_v<T, std::common_type_t<Ts...>>;

template<typename T, typename... Ts>
concept bool myconcept = sizeof...(Ts) == 0 || refactored<T, Ts...>;
</code>```

Coliru demo

Body:
I am trying to learn about the Concepts Lite TS that is yet to be merged into the standard. I'm confused about the behavior of short-circuiting disjunctions in concept bodies.

Here is a small example:

#include <type_traits>
#include <iostream>

template <typename T, typename ... Ts> concept bool myconcept =
(sizeof...(Ts) == 0) || (std::is_same_v<T, std::common_type_t<Ts...>>);

template <typename ... Ts>
void myfunc(Ts ... args) requires myconcept<int, Ts...> {
    (... , (std::cout << args << std::endl));
}

int main() {
    myfunc();
    return 0;
}

Compiling with gcc 7.1 and -fconcepts, gives the error:

error: cannot call function 'void myfunc(Ts ...) requires  myconcept<int, Ts ...> [with Ts = {}]'

In this example, std::common_type_t<Ts...> does not exist since the struct std::common_type<Ts...> does not have a member type if Ts = {}. However, I think this should compile because cppereference.com's documentation on concepts and constraints states that

Disjunctions are evaluated left to right and short-circuited (if the left constraint is satisfied, template argument deduction into the right constraint is not attempted).

Since sizeof...(Ts) == 0 is satisfied, template argument deduction should not be attempted on the second constraint and the requirement myconcept<int, Ts...> should be satisfied.

Strangely, placing the requirements directly into the function declarator causes the program to compile:

#include <type_traits>
#include <iostream>

template <typename ... Ts>
void myfunc(Ts ... args) requires (sizeof...(Ts) == 0) || (std::is_same_v<int, std::common_type_t<Ts...>>) {
    (... , (std::cout << args << std::endl));
}

int main() {
    myfunc();
    return 0;
}

Is there a good explanation for this behavior?
Thanks.

Body:
The layman’s explanation that appears on cppreference is correct. Select wording from the n4674 draft is quite clear as well:

A conjunction is a constraint taking two operands. A conjunction of constraints is satisfied if and only if both operands are satisfied. The satisfaction of a conjunction’s operands are evaluated left-to-right; if the left operand is not satisfied, template arguments are not substituted into the right operand, and the constraint is not satisfied. […]

(From 17.10.1.1 Logical operations [temp.constr.op] §2.) Since all of the wording that precisely establish how we go from concepts and templates to the conjunction or disjunction of atomic constraints is quite long, we will stick to the layman’s explanation.

Is there a good explanation for this behavior? Thanks.

As of this writing the GCC implementation of concepts is very much experimental. As a workaround you can refactor the problematic part into its own concept:

template<typename T, typename... Ts>
concept bool refactored = std::is_same_v<T, std::common_type_t<Ts...>>;

template<typename T, typename... Ts>
concept bool myconcept = sizeof...(Ts) == 0 || refactored<T, Ts...>;

Coliru demo


问:
changing the height of column header in Nattable
I'm developing an swt application, in which Nattable is used to display the data read from CSV files. However, the column headers are not displayed completely (see the figure below).

What is the easiest way to change the height of column headers programmatically, and also make it resizable by user?

答:
Change the column header row height programmatically either by using API on the DataLayer of the column header or use the RowResizeCommand

```<code>natTable.doCommand(new RowResizeCommand(natTable, 0, 0));
</code>```

Make it resizable by the user, add the necessary configuration as explained here: Resizable row/column headers in NatTable

Body:
Change the column header row height programmatically either by using API on the DataLayer of the column header or use the RowResizeCommand

natTable.doCommand(new RowResizeCommand(natTable, 0, 0));

Make it resizable by the user, add the necessary configuration as explained here: Resizable row/column headers in NatTable


问:
How does opensocial-jquery overcome the browser's inability to parse the results of a cross domain POST?
I was under the impression that you needed a web proxy to parse the results of a cross-domain AJAX POST.

But apparently, you can accomplish this with opensocial-jquery.

Could someone please explain how opensocial-jquery makes this happen?

答:
Umm... the very first sentence on the page you linked to explains it

From http://code.google.com/p/opensocial-jquery/wiki/Ajax

All requests generated by jQuery.ajax are relayed to the proxy gadget server. This frees up cross-domain restrictions and maintains compatibility.


问:
regex pattern expressions
I have a expression for a field with the pattern as [0-9]* which takes a numeric value followed by a * ex. 0123*****. But I want to also include the pattern of *****0123 in the same expression. How can I do it in java. Right now it is as follows

```<code> String numericPattern = "[*0-9]";
</code>```

答:
If I'm understanding correctly, you want

```<code>^\**\d+\**$
</code>```

which means any numbers of asterisks (\**), followed by at least one digit (\d+), and then again, any number of asterisks (including zero) (\**). Since * is a special character in regex (a quantifier  meaning any number of the preceding character/class/group), it has to be escaped with \ to match a litteral *.

The start of line (^) and end of line ($) anchors ensure nothing else but the matched pattern is present.

Note that in java you'll have to escape the backslashes though, so you should end up with something like

```<code>String numericPattern = "\\**\\d+\\**";
</code>```

See an example here at regex101.

Title: regex pattern expressions

Body:
I have a expression for a field with the pattern as [0-9]* which takes a numeric value followed by a * ex. 0123*****. But I want to also include the pattern of *****0123 in the same expression. How can I do it in java. Right now it is as follows

 String numericPattern = "[*0-9]";

Body:
If I'm understanding correctly, you want

^\**\d+\**$

which means any numbers of asterisks (\**), followed by at least one digit (\d+), and then again, any number of asterisks (including zero) (\**). Since * is a special character in regex (a quantifier  meaning any number of the preceding character/class/group), it has to be escaped with \ to match a litteral *.

The start of line (^) and end of line ($) anchors ensure nothing else but the matched pattern is present.

Note that in java you'll have to escape the backslashes though, so you should end up with something like

String numericPattern = "\\**\\d+\\**";

See an example here at regex101.


问:
JS adding to cart
Hi i am trying to let user to add selected item into carts table. I have tried alot of things but so far no results. I am using postgresql

here is my html file

```<code> <form method="post" action="/products/shopping_cart">
        <div class="row">
            <div class="col-lg-8 col-lg-offset-2">
                <div class="modal-body">
                    <h5 style="color: #18BC9C;" id="productName"> <strong>{{ this.productname }} </strong></h5>

                    <img src="/{{ this.photofile }}" class="img-responsive img-centered" alt="" style="width:400px;height:450px;">

                    <p> "{{ this.description }}" </p>
                    <hr>
                    <ul class="list-inline item-details">
                        <li id="quantity">Stock:
                            <strong> {{ this.quantity }} remaining
                            </strong>
                        </li>
                        <li id="price">Price:
                            <strong> ${{ this.price }} NZD
                            </strong>
                        </li>
                        <li>Shipping:
                            <strong> ${{ this.shippingvalue }} NZD
                            </strong>
                        </li>
                        <br>
                        <li id="category">Style:
                            <strong> {{ this.category }}
                            </strong>
                        </li>
                        <li id="gender">For:
                            <strong>  {{ this.gender }}
                            </strong>
                        </li>
                    </ul>
                    <button type="submit" class="btn btn-default" style="margin-right: 20px;">Add to cart</button>

                    <button type="button" class="btn btn-default" data-dismiss="modal">Back</button>
</code>```

< form>

and here is my js

```<code>client.query(
        'INSERT into cartstable(price,description,productname,uniqueid,  category, gender, size,   quantity, shippingValue, dateadded) Values ((SELECT price FROM productstable WHERE price=($1)),$2, $3, $4, $5, $6, $7, $8, $9,$10)',
         [ price,description,productname,uniqueid, category, gender,size,  quantity, shippingValue,  date]
        );
</code>```

答:
I don't know at all but you can do it to use ajax

Example:

Create a route:

```<code>Route::post('add-to-cart/{product}', CartController@addToCart);
</code>```

In cart controller:

```<code>public function addToCart($product){
  //if you use data as a string
  $data = $product->split(";")

  \App\Cart::create([
    'product_id' => data[0],
    'quantity' => .....,
    'user_id' => .....,\
    ..........
  ]);
}
</code>```

Ajax:

```<code>$('#addToCart').click(function(){
//you can use javascript to get data from html

var data= "";
data += product_id + ";";
//or some thing you like to store in data
//You can use data as a array

  $.ajax({
     url: "{{ url('add-to-cart') }}" + '/' + data,
     type: 'POST',
     data: {
       "_token" : {{csrf_token()}},
       "data" : data
     },
    success: function(data){
      //Do some code to update cart on html
    }

  });
});
</code>```

Title: JS adding to cart

Body:
Hi i am trying to let user to add selected item into carts table. I have tried alot of things but so far no results. I am using postgresql

here is my html file

 <form method="post" action="/products/shopping_cart">

 {{ this.productname }}

 "{{ this.description }}"

Stock:
                             {{ this.quantity }} remaining

Price:
                             ${{ this.price }} NZD

Shipping:
                             ${{ this.shippingvalue }} NZD

Style:
                             {{ this.category }}

For:
                              {{ this.gender }}

                    <button type="submit" class="btn btn-default" style="margin-right: 20px;">Add to cart</button>

                    <button type="button" class="btn btn-default" data-dismiss="modal">Back</button>

< form>

and here is my js

client.query(
        'INSERT into cartstable(price,description,productname,uniqueid,  category, gender, size,   quantity, shippingValue, dateadded) Values ((SELECT price FROM productstable WHERE price=($1)),$2, $3, $4, $5, $6, $7, $8, $9,$10)',
         [ price,description,productname,uniqueid, category, gender,size,  quantity, shippingValue,  date]
        );

Body:
I don't know at all but you can do it to use ajax

Example:

Create a route:

Route::post('add-to-cart/{product}', CartController@addToCart);

In cart controller:

public function addToCart($product){
  //if you use data as a string
  $data = $product->split(";")

  \App\Cart::create([
    'product_id' => data[0],
    'quantity' => .....,
    'user_id' => .....,\
    ..........
  ]);
}

Ajax:

$('#addToCart').click(function(){
//you can use javascript to get data from html

var data= "";
data += product_id + ";";
//or some thing you like to store in data
//You can use data as a array

  $.ajax({
     url: "{{ url('add-to-cart') }}" + '/' + data,
     type: 'POST',
     data: {
       "_token" : {{csrf_token()}},
       "data" : data
     },
    success: function(data){
      //Do some code to update cart on html
    }

  });
});


问:
Change power plan to High Performance
How can I change my power plan on local computer to High performance and also change option: Turn off display after( I want to set never ).

I found all examples for remote computers.

答:
You can do this by calling the activate method in the Win32_PowerPlan class:

```<code>$powerPlan = Get-WmiObject -Namespace root\cimv2\power -Class Win32_PowerPlan -Filter "ElementName = 'High Performance'"

$powerPlan.Activate()
</code>```

This will change the power option to 'High Performance'.

To never turn off display use powercfg as wOxxOm mentioned:

```<code>powercfg -change -monitor-timeout-ac 0
powercfg -change -standby-timeout-ac 0
powercfg -change -hibernate-timeout-ac 0
</code>```

Title: Change power plan to High Performance

Body:
You can do this by calling the activate method in the Win32_PowerPlan class:

$powerPlan = Get-WmiObject -Namespace root\cimv2\power -Class Win32_PowerPlan -Filter "ElementName = 'High Performance'"

$powerPlan.Activate()

This will change the power option to 'High Performance'.

To never turn off display use powercfg as wOxxOm mentioned:

powercfg -change -monitor-timeout-ac 0
powercfg -change -standby-timeout-ac 0
powercfg -change -hibernate-timeout-ac 0


问:
Crystal Reports Error in formula
I have a global variable which was declared in a formula in the Report Header section of my document.  I then try to reference that variable to use it in a for loop, and I get the error:

A number, currency amount, boolean,
  data, time, date-time, or string is
  expected here.

What is wrong here and how can I correct?  Code follows:

Header Formula:

```<code>Global StringVar Array items;
redim items [1];

Global StringVar Array jobs;
redim jobs [1];

Global StringVar Array POs;
redim POs [1];

Global StringVar Array Qty;
redim Qty [1];

Global NumberVar numRecordsPrinted;
numRecordsPrinted := 0;

""
</code>```

Detail Formula:

```<code>    Local NumberVar occurances;
    Local StringVar poTOuse;
    Local NumberVar i;

    if {%Line_PO_Test} <> ''
    and {PackingSlipHeader.CompanyCode} <> '10063'
    and {PackingSlipHeader.CompanyCode} <> '10017'
    then
        //Count the number of occurances
        For i := 0 To numRecordsPrinted Do       //Error on numRecordsPrinted
        (
            if items[i] = {PS_DETAIL_FOR_PRINT.DTSItemNumber}
                AND jobs[i] = {PS_DETAIL_FOR_PRINT.JobNumber}
                And Qty[i] = {PS_DETAIL_FOR_PRINT.Quantity_Shipped}
                THEN
                    occurances := occurances + 1
        )

        //Use the # of occurances to get the right PO number
Select occurances
        case 0: poTOuse := {@LinePOnum}
        case 1: poTOuse := {@Line_PO_3}
        case 2: poTOuse := {@Line_PO_2}

        default: poTOuse := "";

        //Save data into the array and increment for next time
        numRecordsPrinted := numRecordsPrinted + 1
        items[numRecordsPrinted] := {PS_DETAIL_FOR_PRINT.DTSItemNumber}
        jobs[numRecordsPrinted] := {PS_DETAIL_FOR_PRINT.JobNumber}
        Qty[numRecordsPrinted] :=   {PS_DETAIL_FOR_PRINT.Quantity_Shipped}

    //Print to the report
    'PO#: ' + poTOuse;
</code>```

答:
In crystal reports syntax, the variables have to be declared each time you use them.  I wasn't aware that I have to declare the variables both in the header formula, and the detail formula.  I made some other small syntax errors, but that was the main problem.

I didn't even consider this as a possibility because in most languages, declaring a variable more than once will cause the program to not even compile, let alone run.

Header Section

```<code>BeforeReadingRecords;

Global StringVar Array items;

Global StringVar Array jobs;

Global StringVar Array POs;

Global NumberVar Array Qty;

Global NumberVar numRecordsPrinted;

""
</code>```

Detail Section

```<code>WhileReadingRecords;
Global StringVar Array items;

Global StringVar Array jobs;

Global StringVar Array POs;

Global NumberVar Array Qty;

Global NumberVar numRecordsPrinted;
Global NumberVar occurances;
occurances := 0;

Global StringVar poTOuse;
Global NumberVar i;

ReDim Preserve items[CDbl(Ubound(items) + 1)];
ReDim Preserve jobs[CDbl(Ubound(jobs) + 1)];
ReDim Preserve POs[CDbl(Ubound(POs) + 1)];
ReDim Preserve Qty[CDbl(Ubound(Qty) + 1)];

if {%Line_PO_Test} <> ""
and {PackingSlipHeader.CompanyCode} <> "10063"
and {PackingSlipHeader.CompanyCode} <> "10017"
then
    //Count the number of occurances
    For i := 1 To (numRecordsPrinted + 1) Do
    (
        if items[i] = {PS_DETAIL_FOR_PRINT.DTSItemNumber}
            AND jobs[i] = {PS_DETAIL_FOR_PRINT.JobNumber}
            And Qty[i] = {PS_DETAIL_FOR_PRINT.Quantity_Shipped}
            THEN
                occurances := occurances + 1
    );

    //Use the # of occurances to get the right PO number
    Select occurances
        case 0: poTOuse := {%Line_PO_Test}
        case 1: poTOuse := {%Line_PO_3}
        case 2: poTOuse := {%Line_PO_2}

        default: poTOuse := "";

    //Save data into the array and increment for next time
    numRecordsPrinted := numRecordsPrinted + 1;
    items[numRecordsPrinted] := {PS_DETAIL_FOR_PRINT.DTSItemNumber};
    jobs[numRecordsPrinted] := {PS_DETAIL_FOR_PRINT.JobNumber};
    Qty[numRecordsPrinted] :=  {PS_DETAIL_FOR_PRINT.Quantity_Shipped};

//Print to the report
if poTOuse <> "" THEN
'PO#: ' + poTOuse
ELSE
"";
</code>```

Title: Crystal Reports Error in formula

Body:
I have a global variable which was declared in a formula in the Report Header section of my document.  I then try to reference that variable to use it in a for loop, and I get the error:

A number, currency amount, boolean,
  data, time, date-time, or string is
  expected here.

What is wrong here and how can I correct?  Code follows:

Header Formula:

Global StringVar Array items;
redim items [1];

Global StringVar Array jobs;
redim jobs [1];

Global StringVar Array POs;
redim POs [1];

Global StringVar Array Qty;
redim Qty [1];

Global NumberVar numRecordsPrinted;
numRecordsPrinted := 0;

""

Detail Formula:

    Local NumberVar occurances;
    Local StringVar poTOuse;
    Local NumberVar i;

    if {%Line_PO_Test} <> ''
    and {PackingSlipHeader.CompanyCode} <> '10063'
    and {PackingSlipHeader.CompanyCode} <> '10017'
    then
        //Count the number of occurances
        For i := 0 To numRecordsPrinted Do       //Error on numRecordsPrinted
        (
            if items[i] = {PS_DETAIL_FOR_PRINT.DTSItemNumber}
                AND jobs[i] = {PS_DETAIL_FOR_PRINT.JobNumber}
                And Qty[i] = {PS_DETAIL_FOR_PRINT.Quantity_Shipped}
                THEN
                    occurances := occurances + 1
        )

        //Use the # of occurances to get the right PO number
Select occurances
        case 0: poTOuse := {@LinePOnum}
        case 1: poTOuse := {@Line_PO_3}
        case 2: poTOuse := {@Line_PO_2}

        default: poTOuse := "";

        //Save data into the array and increment for next time
        numRecordsPrinted := numRecordsPrinted + 1
        items[numRecordsPrinted] := {PS_DETAIL_FOR_PRINT.DTSItemNumber}
        jobs[numRecordsPrinted] := {PS_DETAIL_FOR_PRINT.JobNumber}
        Qty[numRecordsPrinted] :=   {PS_DETAIL_FOR_PRINT.Quantity_Shipped}

    //Print to the report
    'PO#: ' + poTOuse;

Body:
In crystal reports syntax, the variables have to be declared each time you use them.  I wasn't aware that I have to declare the variables both in the header formula, and the detail formula.  I made some other small syntax errors, but that was the main problem.

I didn't even consider this as a possibility because in most languages, declaring a variable more than once will cause the program to not even compile, let alone run.

Header Section

BeforeReadingRecords;

Global StringVar Array items;

Global StringVar Array jobs;

Global StringVar Array POs;

Global NumberVar Array Qty;

Global NumberVar numRecordsPrinted;

""

Detail Section

WhileReadingRecords;
Global StringVar Array items;

Global StringVar Array jobs;

Global StringVar Array POs;

Global NumberVar Array Qty;

Global NumberVar numRecordsPrinted;
Global NumberVar occurances;
occurances := 0;

Global StringVar poTOuse;
Global NumberVar i;

ReDim Preserve items[CDbl(Ubound(items) + 1)];
ReDim Preserve jobs[CDbl(Ubound(jobs) + 1)];
ReDim Preserve POs[CDbl(Ubound(POs) + 1)];
ReDim Preserve Qty[CDbl(Ubound(Qty) + 1)];

if {%Line_PO_Test} <> ""
and {PackingSlipHeader.CompanyCode} <> "10063"
and {PackingSlipHeader.CompanyCode} <> "10017"
then
    //Count the number of occurances
    For i := 1 To (numRecordsPrinted + 1) Do
    (
        if items[i] = {PS_DETAIL_FOR_PRINT.DTSItemNumber}
            AND jobs[i] = {PS_DETAIL_FOR_PRINT.JobNumber}
            And Qty[i] = {PS_DETAIL_FOR_PRINT.Quantity_Shipped}
            THEN
                occurances := occurances + 1
    );

    //Use the # of occurances to get the right PO number
    Select occurances
        case 0: poTOuse := {%Line_PO_Test}
        case 1: poTOuse := {%Line_PO_3}
        case 2: poTOuse := {%Line_PO_2}

        default: poTOuse := "";

    //Save data into the array and increment for next time
    numRecordsPrinted := numRecordsPrinted + 1;
    items[numRecordsPrinted] := {PS_DETAIL_FOR_PRINT.DTSItemNumber};
    jobs[numRecordsPrinted] := {PS_DETAIL_FOR_PRINT.JobNumber};
    Qty[numRecordsPrinted] :=  {PS_DETAIL_FOR_PRINT.Quantity_Shipped};

//Print to the report
if poTOuse <> "" THEN
'PO#: ' + poTOuse
ELSE
"";


问:
Using regular exp in oracle to remove a group of codes
i've a column in my Oracle table and it has many values with a group of codes as below :

(5000311520) smart tv 40 inch + cinema/internet(high-speed)

now i'm going to remove the code : (5000311520)

it means the result should be : smart tv 40 inch + cinema/internet(high-speed)

anybody can help me?
thanks in advance.

答:
To select without the number code at the start :

```<code>select REGEXP_REPLACE(Comments,'^\([0-9]+\)\s*','') from Table1
</code>```

Explaining the regex:

```<code>^       : start of the text
\(      : a literal '(' character
[0-9]+  : 1 or more digits from 0 to 9
\)      : a literal ')' character
\s*     : 0 or more whitespaces (spaces, tabs, linefeeds, ...)
</code>```

And to strip the code from the column values permanently?

You can use such regex also in the where clause:

```<code>update Table1
set Comments = REGEXP_REPLACE(Comments,'^\([0-9]+\)\s*','')
where REGEXP_LIKE(Comments,'^\([0-9]+\)')
</code>```

Body:
To select without the number code at the start :

select REGEXP_REPLACE(Comments,'^\([0-9]+\)\s*','') from Table1

Explaining the regex:

^       : start of the text
\(      : a literal '(' character
[0-9]+  : 1 or more digits from 0 to 9
\)      : a literal ')' character
\s*     : 0 or more whitespaces (spaces, tabs, linefeeds, ...)

And to strip the code from the column values permanently?

You can use such regex also in the where clause:

update Table1
set Comments = REGEXP_REPLACE(Comments,'^\([0-9]+\)\s*','')
where REGEXP_LIKE(Comments,'^\([0-9]+\)')


问:
How can I include fields from a superclass in the generated Swagger spec (using Scalatra+Swagger)?
I have this case class that's extending an abstract class:

```<code>@ApiModel(description = "A price for an offer.")
case class OfferPrice(
                       override val amount: Double,
                       override val taxAmount: Double,
                       override val taxRate: Option[Double]
                     ) extends Price(amount, taxAmount, taxRate)

abstract class Price(
                      @(ApiModelProperty@field)(description = "The amount.") val amount: Double,
                      @(ApiModelProperty@field)(description = "The tax amount.") val taxAmount: Double,
                      @(ApiModelProperty@field)(description = "The tax rate.") val taxRate: Option[Double]
                    )
</code>```

Exciting stuff, right? My problem is that the definition in the generated swagger.json file looks like this:

```<code>"OfferPrice": {
  "properties": {

  }
}
</code>```

It's not including the fields from the abstract class. How can I include those fields as well?

答:
It wouldn't work because fields and annotations declared in the super class are hidden by fields overridden in the subclass.

I think this is correct definition of your model:

```<code>@ApiModel(description = "A price for an offer.")
case class OfferPrice(
  @ApiModelProperty(description = "The amount.") amount: Double,
  @ApiModelProperty(description = "The tax amount.") taxAmount: Double,
  @ApiModelProperty(description = "The tax rate.") taxRate: Option[Double]
) extends Price(amount, taxAmount, taxRate)

abstract class Price(
  amount: Double,
  taxAmount: Double,
  taxRate: Option[Double]
)
</code>```

but description of model and properties is not rendered in Scalatra's Swagger 2.0 support currently. It will be supported in the future release. See: https://github.com/scalatra/scalatra/issues/684

Body:
I have this case class that's extending an abstract class:

@ApiModel(description = "A price for an offer.")
case class OfferPrice(
                       override val amount: Double,
                       override val taxAmount: Double,
                       override val taxRate: Option[Double]
                     ) extends Price(amount, taxAmount, taxRate)

abstract class Price(
                      @(ApiModelProperty@field)(description = "The amount.") val amount: Double,
                      @(ApiModelProperty@field)(description = "The tax amount.") val taxAmount: Double,
                      @(ApiModelProperty@field)(description = "The tax rate.") val taxRate: Option[Double]
                    )

Exciting stuff, right? My problem is that the definition in the generated swagger.json file looks like this:

"OfferPrice": {
  "properties": {

  }
}

It's not including the fields from the abstract class. How can I include those fields as well?

Body:
It wouldn't work because fields and annotations declared in the super class are hidden by fields overridden in the subclass.

I think this is correct definition of your model:

@ApiModel(description = "A price for an offer.")
case class OfferPrice(
  @ApiModelProperty(description = "The amount.") amount: Double,
  @ApiModelProperty(description = "The tax amount.") taxAmount: Double,
  @ApiModelProperty(description = "The tax rate.") taxRate: Option[Double]
) extends Price(amount, taxAmount, taxRate)

abstract class Price(
  amount: Double,
  taxAmount: Double,
  taxRate: Option[Double]
)

but description of model and properties is not rendered in Scalatra's Swagger 2.0 support currently. It will be supported in the future release. See: https://github.com/scalatra/scalatra/issues/684


问:
Hibernate mappedBy gives com.sun.jdi.InvocationException occurred invoking method
Just need a quick Help from you all. I have used mappedBy Instead of @JoinColumn just for performance Optimization:

```<code>@OneToMany(cascade=CascadeType.ALL,fetch=FetchType.LAZY,mappedBy="user")
</code>```

I have been advised to set fetch=FetchType.EAGER.
But I don't want to do that. Is there any other way to get lazily Loaded Collection Objects.
Or should I use @JoinColumn for that?
And mappedBy is then how useful for other if not able to read it lazily.

Sample entities

```<code>@Entity
@Table(name="users,uniqueConstraints=@UniqueConstraint(columnNames= "username"))
public class Users implements java.io.Serializable {
   private Set<IDPMaster> idpMaster;
    public void setIdpMaster(Set<IDPMaster> idpMaster) {
        this.idpMaster = idpMaster;
    }
    @OneToMany(cascade = CascadeType.ALL,fetch=FetchType.LAZY,mappedBy="user")
    public Set<IDPUserManagerMapping> getIdpMapping() {
        return idpMapping;
    }
    //Getters and Setters
    }

@Entity
@Table(name="IDP_Master",schema="eb")
public class IDPMaster implements Serializable {
    private Users idpUsers;
        @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="paticipant_id",nullable=false)
    public Users getIdpUsers() {
        return idpUsers;
    }
    public void setIdpUsers(Users idpUsers) {
        this.idpUsers = idpUsers;
    }
    }
</code>```

答:
mappedBy can be used only in one entity i.e. the Parent entity whereas @JoinColumn can be used on the both side of the relationship. See JPA JoinColumn vs mappedBy for difference. Can you show the sample entities that you have created.

Also you need not to specify fetch=FetchType.LAZY because by default the fetchType is always lazy in Hibernate. In JPA however the fetch type is different for different mappings.

Edited..
The field name provided in the mappedBy should be "idpUsers" instead of "users". It should match the variable name in the child Entity.

Body:
Just need a quick Help from you all. I have used mappedBy Instead of @JoinColumn just for performance Optimization:

@OneToMany(cascade=CascadeType.ALL,fetch=FetchType.LAZY,mappedBy="user")

I have been advised to set fetch=FetchType.EAGER.
But I don't want to do that. Is there any other way to get lazily Loaded Collection Objects.
Or should I use @JoinColumn for that?
And mappedBy is then how useful for other if not able to read it lazily.

Sample entities

@Entity
@Table(name="users,uniqueConstraints=@UniqueConstraint(columnNames= "username"))
public class Users implements java.io.Serializable {
   private Set<IDPMaster> idpMaster;
    public void setIdpMaster(Set<IDPMaster> idpMaster) {
        this.idpMaster = idpMaster;
    }
    @OneToMany(cascade = CascadeType.ALL,fetch=FetchType.LAZY,mappedBy="user")
    public Set<IDPUserManagerMapping> getIdpMapping() {
        return idpMapping;
    }
    //Getters and Setters
    }

@Entity
@Table(name="IDP_Master",schema="eb")
public class IDPMaster implements Serializable {
    private Users idpUsers;
        @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="paticipant_id",nullable=false)
    public Users getIdpUsers() {
        return idpUsers;
    }
    public void setIdpUsers(Users idpUsers) {
        this.idpUsers = idpUsers;
    }
    }


问:
Ctrl Key KeyUp event with Click in table heading
I want to generate keyup event with . If i click in  click event is populating there but my requirement is generate event when i release CTRL key pressed with click in  area I am using the following code

```<code><html>
<head>
<script
 src="https://code.jquery.com/jquery-3.2.1.min.js"
 integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
 crossorigin="anonymous"></script>
</head>
<body>
<table border="2">
<th>rollno</th>
<th>name</th>
<tr>
<td>4567</td>
<td>john</td>
 </tr>
</table>
 </body>
 <script>
 $('th').click(function(){
 alert("yes its working");
 });
 </script>
 <script>
 $('th').on('keyup', function(e) {
 if (e.keyCode ==17)
 {
 alert("OOps! ctr+click release not working");
 }
 });
 </script>

 </html>
</code>```

答:
Like that ?

```<code>$('th').click(function(e){
    if(e.ctrlKey){
        alert("yes its working");
    }
});
</code>```

EDIT :

```<code>$( 'th' ).click( function ( e ) {

    if ( e.ctrlKey ) {

        $( window ).on( 'keyup' , function () {

            alert( "yes its working" );

            $( window ).off( 'keyup' );

        } );

    }
    else {
        alert( 'nop' );
    }

} );
</code>```

Body:
I want to generate keyup event with . If i click in  click event is populating there but my requirement is generate event when i release CTRL key pressed with click in  area I am using the following code

rollno
name

4567
john

Body:
Like that ?

$('th').click(function(e){
    if(e.ctrlKey){
        alert("yes its working");
    }
});

EDIT :

$( 'th' ).click( function ( e ) {

    if ( e.ctrlKey ) {

        $( window ).on( 'keyup' , function () {

            alert( "yes its working" );

            $( window ).off( 'keyup' );

        } );

    }
    else {
        alert( 'nop' );
    }

} );


问:
Fill a Column for Every Row in a Database
I just added a new column to a table which has over 1000 rows of data. I am wondering how I can update the new column with a piece of data for all of the rows in the database without having to manually do it.

What is the easiest way to accomplish this?

I am working with a MS SQL 2005 server. Thank you in advance for your advice.

答:
Try this out.

```<code>UPDATE table_name SET column_name = value
</code>```

This is given that the value you want to assign is a constant.  Is that correct?

Body:
Try this out.

UPDATE table_name SET column_name = value

This is given that the value you want to assign is a constant.  Is that correct?


问:
Data Tables. fix first column so not sort-able
I have a data table. The first column is the position and is a increments so example has 1, 2, 3, 4. Showing the position a row is in. The rest of the columns i want sort-able. So when sorted by number of jobs, or total value the first column stays the same but the rest change.

I have tried using fixed column but this is not that i want.

```<code><table class="datatable">
                        <thead>
                            <tr>
                                <th>Position</th>
                                <th class="no-sort">Name</th>
                                <th class="no-sort">Jobs</th>
                                <th class="no-sort">Labour</th>
                                <th class="no-sort">Total</th>
                            </tr>
                        </thead>
                        @{int count = 1;}
                        @foreach (Model make in Model.Models)
                        {
                            <tr>
                                <td>@(count)</td>
                                <td>@make.Name</td>
                                <td>@make.Jobs</td>
                                <td>@Math.Round(make.Labour, 2)</td>
                                 <td>@Math.Round(make.Total, 2)</td>
                            </tr>
                            { count++; }
                        }
                    </table>

  var Table = $('.datatable').dataTable({
        "bJQueryUI": true,
        "sPaginationType": "full_numbers",
        "bScrollCollapse": true,
        "bFilter": false, "bInfo": false,
        "aaSorting": [[2, 'desc']],
        "columnDefs": [ {
            "targets": 'no-sort',
            "orderable": false,
        } ],
        "aoColumns": [
            { "bSearchable": false },
            { "bSearchable": false },
            { "bSearchable": false },
       { "bSearchable": false },
          { "bSearchable": false },
            { "bSearchable": false }
        ]
    });
</code>```

答:
You could achieve this functionality by adding Counter Column that contains the position in the table for each row. You need to add it dynamically whenever searching and ordering operations are performed at DataTable.

```<code>oTable.on( 'order.dt search.dt', function () {
        oTable.column(0, {search:'applied', order:'applied'}).nodes().each( function (cell, i) {
            cell.innerHTML = i+1;
        } );
    } ).draw();
</code>```

Please see this Example for demonstration.

JSFiddle Demo

Body:
I have a data table. The first column is the position and is a increments so example has 1, 2, 3, 4. Showing the position a row is in. The rest of the columns i want sort-able. So when sorted by number of jobs, or total value the first column stays the same but the rest change.

I have tried using fixed column but this is not that i want.

                                Position
                                Name
                                Jobs
                                Labour
                                Total

                        @{int count = 1;}
                        @foreach (Model make in Model.Models)
                        {

                                @(count)
                                @make.Name
                                @make.Jobs
                                @Math.Round(make.Labour, 2)
                                 @Math.Round(make.Total, 2)

                            { count++; }
                        }

  var Table = $('.datatable').dataTable({
        "bJQueryUI": true,
        "sPaginationType": "full_numbers",
        "bScrollCollapse": true,
        "bFilter": false, "bInfo": false,
        "aaSorting": [[2, 'desc']],
        "columnDefs": [ {
            "targets": 'no-sort',
            "orderable": false,
        } ],
        "aoColumns": [
            { "bSearchable": false },
            { "bSearchable": false },
            { "bSearchable": false },
       { "bSearchable": false },
          { "bSearchable": false },
            { "bSearchable": false }
        ]
    });

Body:
You could achieve this functionality by adding Counter Column that contains the position in the table for each row. You need to add it dynamically whenever searching and ordering operations are performed at DataTable.

oTable.on( 'order.dt search.dt', function () {
        oTable.column(0, {search:'applied', order:'applied'}).nodes().each( function (cell, i) {
            cell.innerHTML = i+1;
        } );
    } ).draw();

Please see this Example for demonstration.

JSFiddle Demo


问:
Scala: Requiring members on companion objects of abstract classes
I'd like to create an abstract class, and be able to add members to it that reference attributes of the implementing class's companion object.  Something like this (Scala pseudocode):

```<code>abstract class Fruit(cultivar: String) {
    // How do I reference the implementing class's companion object here?
    def isTastyCultivar(): Boolean = Fruit.tastyCultivars.contains(cultivar)
}

// how do I implement what I am thinking of as "the abstract companion object"
abstract object Fruit {
    val tastyCultivars: Set[String]  // must be implemented
                                     // by the concrete object
}

class Apple(cultivar: String) extends Fruit(cultivar) {

}

object Apple extends Fruit{ // presumably this is not correct;
                            // it needs to extend the FruitObject
                            // or whatever it is
    val tastyCultivars: Set[String] = Set("Red Delicious", "Granny Smith")
}

class Tomato(cultivar: String) extends Fruit(cultivar) {

}

object Tomato extends Fruit{
    val tastyCultivars = Set("Roma")
}

val a1 = new Apple("Red Delicious")
val a2 = new Apple("Honeycrisp")

a1.isTastyCultivar()  // should return true
a2.isTastyCultivar()  // should return false

val t1 = new Tomato("Roma")
val t2 = new Tomato("San Marzano")

t1.isTastyCultivar() // should return true
t2.isTastyCultivar() // should return false
</code>```

Sorry if this is a dumb question, or if asked previously (I'm not confident in how to word this question so I couldn't easily search for it).  Thanks in advance!

答:
A simple solution (the one Scala Collections use): just add a method returning the companion to the class.

```<code>trait FruitCompanion {
  val tastyCultivars: Set[String]
}

abstract class Fruit(cultivar: String) {
  def companion: FruitCompanion
  def isTastyCultivar(): Boolean = companion.tastyCultivars.contains(cultivar)
}

class Apple(cultivar: String) extends Fruit(cultivar) {
  def companion = Apple
}

object Apple extends FruitCompanion {
  val tastyCultivars: Set[String] = Set("Red Delicious", "Granny Smith")
}
</code>```

Note that you can't enforce that the companion actually returns the companion object, but you don't really need it.

Body:
I'd like to create an abstract class, and be able to add members to it that reference attributes of the implementing class's companion object.  Something like this (Scala pseudocode):

abstract class Fruit(cultivar: String) {
    // How do I reference the implementing class's companion object here?
    def isTastyCultivar(): Boolean = Fruit.tastyCultivars.contains(cultivar)
}

// how do I implement what I am thinking of as "the abstract companion object"
abstract object Fruit {
    val tastyCultivars: Set[String]  // must be implemented
                                     // by the concrete object
}

class Apple(cultivar: String) extends Fruit(cultivar) {

}

object Apple extends Fruit{ // presumably this is not correct;
                            // it needs to extend the FruitObject
                            // or whatever it is
    val tastyCultivars: Set[String] = Set("Red Delicious", "Granny Smith")
}

class Tomato(cultivar: String) extends Fruit(cultivar) {

}

object Tomato extends Fruit{
    val tastyCultivars = Set("Roma")
}

val a1 = new Apple("Red Delicious")
val a2 = new Apple("Honeycrisp")

a1.isTastyCultivar()  // should return true
a2.isTastyCultivar()  // should return false

val t1 = new Tomato("Roma")
val t2 = new Tomato("San Marzano")

t1.isTastyCultivar() // should return true
t2.isTastyCultivar() // should return false

Sorry if this is a dumb question, or if asked previously (I'm not confident in how to word this question so I couldn't easily search for it).  Thanks in advance!

Body:
A simple solution (the one Scala Collections use): just add a method returning the companion to the class.

trait FruitCompanion {
  val tastyCultivars: Set[String]
}

abstract class Fruit(cultivar: String) {
  def companion: FruitCompanion
  def isTastyCultivar(): Boolean = companion.tastyCultivars.contains(cultivar)
}

class Apple(cultivar: String) extends Fruit(cultivar) {
  def companion = Apple
}

object Apple extends FruitCompanion {
  val tastyCultivars: Set[String] = Set("Red Delicious", "Granny Smith")
}

Note that you can't enforce that the companion actually returns the companion object, but you don't really need it.


问:
Odata - how to parse filters
I have Odata filter which is string and looks like that:

```<code>string odataFilter = "name eq 20 and surname eq 50"
</code>```

What I need to accomplish is to get following dictionary from it:

```<code>dict["name"] = "20"
dict["surname"] = "50"
</code>```

What is also important: I want to handle only "and" and "eq" keywords from odata. Nothing else.

Does anyone have an idea how to touch the problem? Maybe by regular expressions?

答:
I would use Regex.Split like this : https://dotnetfiddle.net/l1wueA

```<code>using System;
using System.Text.RegularExpressions;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        var dic = findAllAndEqFilter("name eq 20 and surname eq 50");

        Console.WriteLine("Test 1\r\n");
        foreach(var kpv in dic)
            Console.WriteLine(kpv.Key + "->" + kpv.Value);

        dic = findAllAndEqFilter("name eq 21 or surname eq 51");

        Console.WriteLine("\r\nTest 2\r\n");
        foreach(var kpv in dic)
            Console.WriteLine(kpv.Key + "->" + kpv.Value);

        dic = findAllAndEqFilter("name eq 22");

        Console.WriteLine("\r\nTest 3\r\n");
        foreach(var kpv in dic)
            Console.WriteLine(kpv.Key + "->" + kpv.Value);

        dic = findAllAndEqFilter("name lt 22");

        Console.WriteLine("\r\nTest 4\r\n");
        foreach(var kpv in dic)
            Console.WriteLine(kpv.Key + "->" + kpv.Value);
    }

    public static Dictionary<string, string> findAllAndEqFilter(string odataFilter)
    {
        Dictionary<string, string> ret = new Dictionary<string, string>();

        string[] byAnd = Regex.Split(odataFilter, "( and )");

        string key = "";

        foreach(var andSplit in byAnd)
            if(!Regex.IsMatch(andSplit, "( and )")) // remove the and
            {
                string[] byEq = Regex.Split(andSplit, "( eq )");
                foreach(var eqSplit in byEq)
                    if(!Regex.IsMatch(eqSplit, "\\s")) // if there is no space, we can assume we got a eq
                        if(key == "")
                            key = eqSplit;
                        else
                        {
                            ret.Add(key, eqSplit);
                            key = "";
                        }

            }

        return ret;
    }
}
</code>```

Title: Odata - how to parse filters

Body:
I have Odata filter which is string and looks like that:

string odataFilter = "name eq 20 and surname eq 50"

What I need to accomplish is to get following dictionary from it:

dict["name"] = "20"
dict["surname"] = "50"

What is also important: I want to handle only "and" and "eq" keywords from odata. Nothing else.

Does anyone have an idea how to touch the problem? Maybe by regular expressions?

Body:
I would use Regex.Split like this : https://dotnetfiddle.net/l1wueA

using System;
using System.Text.RegularExpressions;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        var dic = findAllAndEqFilter("name eq 20 and surname eq 50");

        Console.WriteLine("Test 1\r\n");
        foreach(var kpv in dic)
            Console.WriteLine(kpv.Key + "->" + kpv.Value);

        dic = findAllAndEqFilter("name eq 21 or surname eq 51");

        Console.WriteLine("\r\nTest 2\r\n");
        foreach(var kpv in dic)
            Console.WriteLine(kpv.Key + "->" + kpv.Value);

        dic = findAllAndEqFilter("name eq 22");

        Console.WriteLine("\r\nTest 3\r\n");
        foreach(var kpv in dic)
            Console.WriteLine(kpv.Key + "->" + kpv.Value);

        dic = findAllAndEqFilter("name lt 22");

        Console.WriteLine("\r\nTest 4\r\n");
        foreach(var kpv in dic)
            Console.WriteLine(kpv.Key + "->" + kpv.Value);
    }

    public static Dictionary<string, string> findAllAndEqFilter(string odataFilter)
    {
        Dictionary<string, string> ret = new Dictionary<string, string>();

        string[] byAnd = Regex.Split(odataFilter, "( and )");

        string key = "";

        foreach(var andSplit in byAnd)
            if(!Regex.IsMatch(andSplit, "( and )")) // remove the and
            {
                string[] byEq = Regex.Split(andSplit, "( eq )");
                foreach(var eqSplit in byEq)
                    if(!Regex.IsMatch(eqSplit, "\\s")) // if there is no space, we can assume we got a eq
                        if(key == "")
                            key = eqSplit;
                        else
                        {
                            ret.Add(key, eqSplit);
                            key = "";
                        }

            }

        return ret;
    }
}


问:
Can I loop on a method?
I am using a method to retrieve an enumerable and was wandering a silly thing : is it ok to loop on the method call? say I have a method getDocuments in a Document class that returns an IEnumerable, then can I do:

```<code>Document doc=new Document();
foreach(var item in doc.getDocuments())
{//Code here
}
</code>```

Or is it better to assign a variable to that result and loop on the variable?

答:
You are looping on the same thing in both cases, the only difference is whether you also give it a name (by declaring a variable). You might want to do that for readability, or to access it multiple times - to enumerate over it multiple times1, or for easier debugging2.

1 Usually not recommended because of possible side-effects, or could simply be a waste of performance. It's often better to call ToArray or ToList before enumerating over the same collection multiple times.

2 Note that if you "expand" the variable under the debugger, you are effectively enumerating over it, which may be problematic in the presence of side-effects (as mentioned above).

Title: Can I loop on a method?

Body:
I am using a method to retrieve an enumerable and was wandering a silly thing : is it ok to loop on the method call? say I have a method getDocuments in a Document class that returns an IEnumerable, then can I do:

Document doc=new Document();
foreach(var item in doc.getDocuments())
{//Code here
}

Or is it better to assign a variable to that result and loop on the variable?


问:
Copying files to a remote server in powershell
I am configuring a Jenkins job and Jenkins slave is installed in a windows server(A). I want to copy project build output folder to another windows server(B).

I can execute a batch file manually on Server A, with following content.

```<code>powershell -executionpolicy remotesigned -Command Copy-Item "C:\Jenkins\workspace\DEV_Build\DEPLOY\UAT\build" -Destination "\\SYDUATAPP01\E$\build" -recurse
</code>```

However, when I execute this batch file through Jenkins I get a error "Access Denied"

```<code>Access is denied
 + CategoryInfo          : NotSpecified: (:) [Copy-Item], UnauthorizedAcces
   sException
    + FullyQualifiedErrorId : System.UnauthorizedAccessException,Microsoft.Pow
   erShell.Commands.CopyItemCommand
</code>```

Appreciate your help..... If it is not possible via powershell, I would like to know what other alternatives I have to copy files in my Jenkins job

答:
@Gergard, Thank you very much for your help. I tried putting the provided bit of code to run as admin. However, nothing worked. Execution policy was remotesigned.

Finally below steps solved my problem;

I installed Powershell plugin(1.3) on my windows remote slave. Powershell 1.3, executed with "ByPass" policy

And added a step from powershell to copy item.

Copy-Item "source path" -Destination "\destination path" -recurse

Above steps didn't solve the issue and still complained as unauthorized.

Then I configured jenkins remote slave process -> properties -> run as admin account.

This solved the issue and now I am able to copy files successfully.

Body:
I am configuring a Jenkins job and Jenkins slave is installed in a windows server(A). I want to copy project build output folder to another windows server(B).

I can execute a batch file manually on Server A, with following content.

powershell -executionpolicy remotesigned -Command Copy-Item "C:\Jenkins\workspace\DEV_Build\DEPLOY\UAT\build" -Destination "\\SYDUATAPP01\E$\build" -recurse

However, when I execute this batch file through Jenkins I get a error "Access Denied"

Access is denied
 + CategoryInfo          : NotSpecified: (:) [Copy-Item], UnauthorizedAcces
   sException
    + FullyQualifiedErrorId : System.UnauthorizedAccessException,Microsoft.Pow
   erShell.Commands.CopyItemCommand

Appreciate your help..... If it is not possible via powershell, I would like to know what other alternatives I have to copy files in my Jenkins job


问:
How might I create an acronym by splitting a string at the spaces, taking the character indexed at 0, joining it together, and capitalizing it?
My code

```<code>beginning = input("What would you like to acronymize? : ")

second = beginning.upper()

third = second.split()

fourth = "".join(third[0])

print(fourth)
</code>```

I can't seem to figure out what I'm missing. The code is supposed to the the phrase the user inputs, put it all in caps, split it into words, join the first character of each word together, and print it. I feel like there should be a loop somewhere, but I'm not entirely sure if that's right or where to put it.

答:
```<code>#acronym2.py
#illustrating how to design an acronymn
import string
def main():
    sent=raw_input("Enter the sentence: ")#take input sentence with spaces

    for i in string.split(string.capwords(sent)):#split the string so each word
                                                 #becomes
                                                 #a string
        print string.join(i[0]),                 #loop through the split
                                                 #string(s) and
                                                 #concatenate the first letter
                                                 #of each of the
                                                 #split string to get your
                                                 #acronym

main()
</code>```

Body:
My code

beginning = input("What would you like to acronymize? : ")

second = beginning.upper()

third = second.split()

fourth = "".join(third[0])

print(fourth)

I can't seem to figure out what I'm missing. The code is supposed to the the phrase the user inputs, put it all in caps, split it into words, join the first character of each word together, and print it. I feel like there should be a loop somewhere, but I'm not entirely sure if that's right or where to put it.

ContentLicense: CC BY-SA 4.0


问:
Angular cli with es6 instead of Typescript
I wanted to know if there is any option to use es6 transpiler like
babel instead of type script in an angular cli project.

Is there any flag for script language like you can do with --style?

Thanks.

答:
NO, Angular CLI doesn't allow this.

Theoretically you can write Angular 2+ code in JavaScript, But the framework itself is written in TypeScript and all the code examples is in TypeScript so you'll be "alone in the dark" if you will decide to do that.


问:
How to prevent function call of multiple time to a single time
I have a situation where i want to call a function only a single time but it is firing multiple time how to prevent that.

http://jsfiddle.net/pdzTW/224/

```<code>function howManyTimesIwasCalled(value){
  console.log('i have called so many time '+value);
}

$(document).ready(function() {
  alert('please scroll output window and check the console');

  $(document).scroll(function() {
    var cutoff = $(window).scrollTop() + 200;

    $('div').each(function(e) {
      if ($(this).offset().top + $(this).height() > cutoff) {
        $('div').removeClass('current');
        $(this).addClass('current');
        howManyTimesIwasCalled($(this).data('value'));

        //callGoogleMapHere(data..);

        return false; // stops the iteration after the first one on
      }
  });
});
</code>```

答:
Here you go: http://jsfiddle.net/tvv1tqmb/</p>

```<code>function howManyTimesIwasCalled( value ) {
    console.log( 'i have called so many time ' + value );
}

$( document ).ready( function () {
    alert( 'please scroll output window and check the console' );
    var lastDiv = undefined;
    $( document ).scroll( function () {
        var cutoff = $( window ).scrollTop() + 200;

        $( 'div' ).each( function ( e ) {
            if ( $( this ).offset().top + $( this ).height() > cutoff ) {

                if ( $( this ).data( 'value' ) == lastDiv ) {
                    return false;
                }

                $( 'div' ).removeClass( 'current' );
                $( this ).addClass( 'current' );

                howManyTimesIwasCalled( $( this ).data( 'value' ) );

                //callGoogleMapHere(data..);

                lastDiv = $( this ).data( 'value' );

                return false; // stops the iteration after the first one on
            }
        } );
    } );
} );
</code>```

Body:
I have a situation where i want to call a function only a single time but it is firing multiple time how to prevent that.

http://jsfiddle.net/pdzTW/224/

function howManyTimesIwasCalled(value){
  console.log('i have called so many time '+value);
}

$(document).ready(function() {
  alert('please scroll output window and check the console');

  $(document).scroll(function() {
    var cutoff = $(window).scrollTop() + 200;

    $('div').each(function(e) {
      if ($(this).offset().top + $(this).height() > cutoff) {
        $('div').removeClass('current');
        $(this).addClass('current');
        howManyTimesIwasCalled($(this).data('value'));

        //callGoogleMapHere(data..);

        return false; // stops the iteration after the first one on
      }
  });
});

Body:
Here you go: http://jsfiddle.net/tvv1tqmb/

function howManyTimesIwasCalled( value ) {
    console.log( 'i have called so many time ' + value );
}

$( document ).ready( function () {
    alert( 'please scroll output window and check the console' );
    var lastDiv = undefined;
    $( document ).scroll( function () {
        var cutoff = $( window ).scrollTop() + 200;

        $( 'div' ).each( function ( e ) {
            if ( $( this ).offset().top + $( this ).height() > cutoff ) {

                if ( $( this ).data( 'value' ) == lastDiv ) {
                    return false;
                }

                $( 'div' ).removeClass( 'current' );
                $( this ).addClass( 'current' );

                howManyTimesIwasCalled( $( this ).data( 'value' ) );

                //callGoogleMapHere(data..);

                lastDiv = $( this ).data( 'value' );

                return false; // stops the iteration after the first one on
            }
        } );
    } );
} );