问:
Java Streams - forEach with pre-Action and post-Action
When using Stream.forEach(), I was thinking if it is not possible to add a pre-action and post-action to be executed when the stream is not empty. For example, when printing a List, one could prepend something or write something else when the stream is empty.

Now I came up with something like

```<code>private static <T> void forEach(Stream<T> stream, Consumer<? super T> action,
    Runnable preAction, Runnable postAction, Runnable ifEmpty) {
    AtomicBoolean hasElements = new AtomicBoolean(false);
    Consumer<T> preActionConsumer = x -> {
        if (hasElements.compareAndSet(false, true)) {
            preAction.run();
        }
    };
    stream.forEach(preActionConsumer.andThen(action));
    if (hasElements.get()) {
        postAction.run();
    } else {
        ifEmpty.run();
    }
}
</code>```

For sequential streams, this should work, should it not?
Is this method correct, is it as "good idea" have such a method or are there any caveats?

This does not work for parallel streams, since the preAction might be slower than another thread executing the action, but implementing it correctly without resorting to synchronized or other concurrency utils which defeat the purpose of parallel streams will probably be not easy...

edit: adding use-case. Reading searching integers from a file using a regex and writing them to another file. Using this approach, I don't have to create a String in memory and after that write it to some file. (Obviously, for my real task, I am using more complicated regexes.)

```<code>public static void main(String[] args) throws IOException {
    Stream<String> lines = Files.lines(Paths.get("foo.txt"));

    Pattern findInts = Pattern.compile("(\\d+)");
    Path barFile = Paths.get("bar.txt");
    try (BufferedWriter writer = Files.newBufferedWriter(barFile , StandardOpenOption.CREATE_NEW)) {
        lines.flatMap(x -> findInts.matcher(x).results())
                .forEach(x-> convertCheckedIOException(() ->  {
                            writer.write(x.group(1));
                            writer.newLine();
                        })
                );
    }
}

public static void convertCheckedIOException(Run r) {
    try {
        r.run();
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}

interface Run {
    void run() throws IOException;
}
</code>```

答:
Use the right tool for your job. This task does not benefit from the Stream API.

```<code>Pattern intPattern = Pattern.compile("\\d+");
try(Scanner scanner = new Scanner(Paths.get("foo.txt"));
    BufferedWriter writer = Files.newBufferedWriter(Paths.get("bar.txt"), CREATE_NEW)) {

    String s = scanner.findWithinHorizon(intPattern, 0);
    if(s == null) {
        // perform empty action
    } else {
        // perform pre action
        do {
            writer.append(s);
            writer.newLine();
        } while( (s=scanner.findWithinHorizon(intPattern, 0)) != null);
        // perform post action
    }
}
</code>```

You could still bring in a Stream operation, e.g.

```<code>Pattern intPattern = Pattern.compile("\\d+");
try(Scanner scanner = new Scanner(Paths.get("foo.txt"));
    BufferedWriter writer = Files.newBufferedWriter(Paths.get("bar.txt"), CREATE_NEW)) {

    String firstLine = scanner.findWithinHorizon(intPattern, 0);
    if(firstLine == null) {
        // perform empty action
    } else {
        // perform pre action
        Stream.concat(Stream.of(firstLine),
                      scanner.findAll(intPattern).map(MatchResult::group))
            .forEach(line -> convertCheckedIOException(() ->  {
                    writer.write(line);
                    writer.newLine();
                })
            );
        // perform post action
    }
}
</code>```

but having to deal with the checked IOException just complicates the code for no benefit.

Body:
When using Stream.forEach(), I was thinking if it is not possible to add a pre-action and post-action to be executed when the stream is not empty. For example, when printing a List, one could prepend something or write something else when the stream is empty.

Now I came up with something like

private static <T> void forEach(Stream<T> stream, Consumer<? super T> action,
    Runnable preAction, Runnable postAction, Runnable ifEmpty) {
    AtomicBoolean hasElements = new AtomicBoolean(false);
    Consumer<T> preActionConsumer = x -> {
        if (hasElements.compareAndSet(false, true)) {
            preAction.run();
        }
    };
    stream.forEach(preActionConsumer.andThen(action));
    if (hasElements.get()) {
        postAction.run();
    } else {
        ifEmpty.run();
    }
}

For sequential streams, this should work, should it not?
Is this method correct, is it as "good idea" have such a method or are there any caveats?

This does not work for parallel streams, since the preAction might be slower than another thread executing the action, but implementing it correctly without resorting to synchronized or other concurrency utils which defeat the purpose of parallel streams will probably be not easy...

edit: adding use-case. Reading searching integers from a file using a regex and writing them to another file. Using this approach, I don't have to create a String in memory and after that write it to some file. (Obviously, for my real task, I am using more complicated regexes.)

public static void main(String[] args) throws IOException {
    Stream<String> lines = Files.lines(Paths.get("foo.txt"));

    Pattern findInts = Pattern.compile("(\\d+)");
    Path barFile = Paths.get("bar.txt");
    try (BufferedWriter writer = Files.newBufferedWriter(barFile , StandardOpenOption.CREATE_NEW)) {
        lines.flatMap(x -> findInts.matcher(x).results())
                .forEach(x-> convertCheckedIOException(() ->  {
                            writer.write(x.group(1));
                            writer.newLine();
                        })
                );
    }
}

public static void convertCheckedIOException(Run r) {
    try {
        r.run();
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}

interface Run {
    void run() throws IOException;
}

Body:
Use the right tool for your job. This task does not benefit from the Stream API.

Pattern intPattern = Pattern.compile("\\d+");
try(Scanner scanner = new Scanner(Paths.get("foo.txt"));
    BufferedWriter writer = Files.newBufferedWriter(Paths.get("bar.txt"), CREATE_NEW)) {

    String s = scanner.findWithinHorizon(intPattern, 0);
    if(s == null) {
        // perform empty action
    } else {
        // perform pre action
        do {
            writer.append(s);
            writer.newLine();
        } while( (s=scanner.findWithinHorizon(intPattern, 0)) != null);
        // perform post action
    }
}

You could still bring in a Stream operation, e.g.

Pattern intPattern = Pattern.compile("\\d+");
try(Scanner scanner = new Scanner(Paths.get("foo.txt"));
    BufferedWriter writer = Files.newBufferedWriter(Paths.get("bar.txt"), CREATE_NEW)) {

    String firstLine = scanner.findWithinHorizon(intPattern, 0);
    if(firstLine == null) {
        // perform empty action
    } else {
        // perform pre action
        Stream.concat(Stream.of(firstLine),
                      scanner.findAll(intPattern).map(MatchResult::group))
            .forEach(line -> convertCheckedIOException(() ->  {
                    writer.write(line);
                    writer.newLine();
                })
            );
        // perform post action
    }
}

but having to deal with the checked IOException just complicates the code for no benefit.


来源: stackexchange

问:
How to get the exact week number if the week is starting with specified weekday on moment js?
Example:

Week day is starting from

moment().weekYear(yearValue).week(weekNumber).startOf('week').weekday(2)

which is Tuesday.

First week on 2017 the days are,

```<code>[3-Jan-2017, 4-Jan-2017, 5-Jan-2017, 6-Jan-2017, 7-Jan-2017, 8-Jan-2017, 9-Jan-2017]
</code>```

How to get the exact week number for 1-Jan-2017?

答:
Week numbers can be retrieved by:

```<code>var weeknumber = moment("1-Jan-2017", "d-MMM-YYYY", "en").week();
</code>```

And be careful, passing the locale might change the week number because of starting on Monday or Dunday.

ContentLicense: CC BY-SA 3.0

Body:
Example:

Week day is starting from

moment().weekYear(yearValue).week(weekNumber).startOf('week').weekday(2)

which is Tuesday.

First week on 2017 the days are,

[3-Jan-2017, 4-Jan-2017, 5-Jan-2017, 6-Jan-2017, 7-Jan-2017, 8-Jan-2017, 9-Jan-2017]

How to get the exact week number for 1-Jan-2017?

Body:
Week numbers can be retrieved by:

var weeknumber = moment("1-Jan-2017", "d-MMM-YYYY", "en").week();

And be careful, passing the locale might change the week number because of starting on Monday or Dunday.


问:
Put age restriction of 18 years - Bootstrap Datepicker
I am using Bootstrap Datepicker.

I want to put an Age Restriction of 18 Years.

Dates less than Age 18 Years from current date should be disabled.

Here is my Fiddle:

http://jsfiddle.net/kGGCZ/17/

JS:

```<code>$(function()
{
    $('#datepicker').datepicker(
    {
        viewMode: "years",
        defaultDate: '-2yr',
    }
    );
});
</code>```

答:
You can use yearRange, to let users choose only years which comes under 18+ from current year. Like,</p>

```<code>jQuery('#dateob').datepicker({
changeMonth: true,
changeYear: true,
yearRange: '-110:-18',
showButtonPanel: true
});
</code>```

Body:
I am using Bootstrap Datepicker.

I want to put an Age Restriction of 18 Years.

Dates less than Age 18 Years from current date should be disabled.

Here is my Fiddle:

http://jsfiddle.net/kGGCZ/17/

JS:

$(function()
{
    $('#datepicker').datepicker(
    {
        viewMode: "years",
        defaultDate: '-2yr',
    }
    );
});

Body:
You can use yearRange, to let users choose only years which comes under 18+ from current year. Like,

jQuery('#dateob').datepicker({
changeMonth: true,
changeYear: true,
yearRange: '-110:-18',
showButtonPanel: true
});


问:
SQL Server stored procedure does not return any values
I have this stored procedure which doesn't return any values I run EXEC command

```<code>SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[GClient]
    @CLIENT_CODE INT = NULL output,
    @CLIENT_NAME VARCHAR = 50 output,
    @CATEGORY VARCHAR = 50 output,
    @ATC VARCHAR = 50 output
AS
BEGIN
    SELECT
        *
    FROM
        dbo.CLIENT
    WHERE
        CLIENT_CODE = @CLIENT_CODE OR
        CLIENT_NAME = @CLIENT_NAME OR
        CATEGORY = @CATEGORY OR
        ATC = @ATC;
END
</code>```

I execute it like this:

```<code> DECLARE @client_name varchar(50)
 EXEC GCLIENT @client_name='rillera general merchandise'
</code>```

There is a record on the table with that value, I don't why it doesn't return any records at all.

答:
Simply u can remove out put clause, as u have output columns specified in the table and give one input parameter

```<code>Create  PROCEDURE USP_GClient
@CLIENT_NAME varchar(50)
AS
BEGIN
SELECT
    CLIENT_CODE
    ,CLIENT_NAME
    ,CATEGORY
    ,ATC
FROM
     DBO.CLIENT
WHERE
    CLIENT_NAME=@CLIENT_NAME
END
</code>```

and execute the proc

```<code>EXEC USP_GClient @CLIENT_NAME
</code>```

Body:
I have this stored procedure which doesn't return any values I run EXEC command

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[GClient]
    @CLIENT_CODE INT = NULL output,
    @CLIENT_NAME VARCHAR = 50 output,
    @CATEGORY VARCHAR = 50 output,
    @ATC VARCHAR = 50 output
AS
BEGIN
    SELECT
        *
    FROM
        dbo.CLIENT
    WHERE
        CLIENT_CODE = @CLIENT_CODE OR
        CLIENT_NAME = @CLIENT_NAME OR
        CATEGORY = @CATEGORY OR
        ATC = @ATC;
END

I execute it like this:

 DECLARE @client_name varchar(50)
 EXEC GCLIENT @client_name='rillera general merchandise'

There is a record on the table with that value, I don't why it doesn't return any records at all.

Body:
Simply u can remove out put clause, as u have output columns specified in the table and give one input parameter

Create  PROCEDURE USP_GClient
@CLIENT_NAME varchar(50)
AS
BEGIN
SELECT
    CLIENT_CODE
    ,CLIENT_NAME
    ,CATEGORY
    ,ATC
FROM
     DBO.CLIENT
WHERE
    CLIENT_NAME=@CLIENT_NAME
END

and execute the proc

EXEC USP_GClient @CLIENT_NAME


问:
Bash - get process pid and parse output line by line
I am trying to write a bash script that runs a process and parses its output line by line (like here).

I would also like to get the process PID so for each line I can run ps and get CPU and memory usage (and print them with the output line).

I know I can get the PID with $! if I run the process in background, but then I won't know how to read the output.

Thanks in advance

答:
You can create a FIFO and read that while the background process is running. For each line you read, you can do whatever you want with the child_pid.

First we need a small sample program:

```<code>bgp() { sleep 1; echo 1; sleep 1; echo 2; sleep 1; echo 3; }
</code>```

Then create a fifo (maybe choose some path in /tmp)

```<code>tmp_fifo="/tmp/my_fifo"
rm "${tmp_fifo}" &>/dev/null
mkfifo "${tmp_fifo}"
</code>```

Start your process in the background and redirect the output to the FIFO:

```<code>bgp > "${tmp_fifo}" &
child_pid=$!
</code>```

Now read the output until the child process dies.

```<code>while true; do
    if jobs %% >&/dev/null; then
        if read -r -u 9 line; then
            # Do whatever with $child_pid
            echo -n "output from [$child_pid]: "
            echo $line
        fi
    else
        echo "info: child finished or died"
        break
    fi
done 9< "${tmp_fifo}"
</code>```

Body:
You can create a FIFO and read that while the background process is running. For each line you read, you can do whatever you want with the child_pid.

First we need a small sample program:

bgp() { sleep 1; echo 1; sleep 1; echo 2; sleep 1; echo 3; }

Then create a fifo (maybe choose some path in /tmp)

tmp_fifo="/tmp/my_fifo"
rm "${tmp_fifo}" &>/dev/null
mkfifo "${tmp_fifo}"

Start your process in the background and redirect the output to the FIFO:

bgp > "${tmp_fifo}" &
child_pid=$!

Now read the output until the child process dies.

while true; do
    if jobs %% >&/dev/null; then
        if read -r -u 9 line; then
            # Do whatever with $child_pid
            echo -n "output from [$child_pid]: "
            echo $line
        fi
    else
        echo "info: child finished or died"
        break
    fi
done 9< "${tmp_fifo}"


问:
Logstash cannot consume from Kafka
My structure is like this: Logfiles > Filebeat > Kafka > Logstash > Elasticsearch > Kibana

But I am stuck at the Kafka to Logstash part.

First, Filebeat can produce the message to Kafka and i can check it by using:

```<code>kafka-console-consumer.bat --zookeeper localhost:2181 --topic {topicName} --from-beginning
</code>```

And it can also be consumed by command:

```<code>kafka-console-consumer.bat --zookeeper localhost:2181 --topic {topicName}
</code>```

However, when I try to use logstash to consume the topic, nothing can be retrieved and Zookeeper keep throwing:

2017-11-13 16:11:59,205 [myid:] - INFO
  [NIOServerCxn.Factory:0.0.0.0/0.0.0.0:2181:NIOServerCnxnFactory@215] -
  Accepted socket connection from /127.0.0.1:53201

2017-11-13 16:11:59,207 [myid:] - WARN
  [NIOServerCxn.Factory:0.0.0.0/0.0.0.0:21 81:NIOServerCnxn@383] -
  Exception causing close of session 0x0: null

2017-11-13 16:11:59,209 [myid:] - INFO
  [NIOServerCxn.Factory:0.0.0.0/0.0.0.0:2181:NIOServerCnxn@1040] -
  Closed socket connection for client /127.0.0.1:53201 (no session
  established for client)

Also, the port number in this statement keep increasing"Accepted socket connection from /127.0.0.1:53201". Is it scanning the port?

Below are some background.
Version:

zookeeper-3.4.11

kafka_2.10-0.10.2.1

logstash-5.4.0

(Plugin)logstash-input-kafka (5.1.6)

And here are my config:

Zoo.cfg (zookeeper)

```<code>tickTime=2000
initLimit=10
syncLimit=5
clientPort=2181
</code>```

server.properties (Kafka)

```<code>listeners=PLAINTEXT://localhost:9092
zookeeper.connect=127.0.0.1:2181
</code>```

logstash.config (logstash)

```<code>input {
    kafka {
        bootstrap_servers => "localhost:2181"
        topics => "test"
    }
}
</code>```

I guess the problem is due to the config between zookeeper and kafka but i have no idea how to figure it out. Pls help.

答:
You need to use localhost:9092 for configuration parameter bootstrap_servers - you're pointing Logstash to Zookeeper, but you need to point to Kafka itself.

Another error is that topics requires an array, so it should be ["test"] instead of "test"

Title: Logstash cannot consume from Kafka

Body:
My structure is like this: Logfiles > Filebeat > Kafka > Logstash > Elasticsearch > Kibana

But I am stuck at the Kafka to Logstash part.

First, Filebeat can produce the message to Kafka and i can check it by using:

kafka-console-consumer.bat --zookeeper localhost:2181 --topic {topicName} --from-beginning

And it can also be consumed by command:

kafka-console-consumer.bat --zookeeper localhost:2181 --topic {topicName}

However, when I try to use logstash to consume the topic, nothing can be retrieved and Zookeeper keep throwing:

2017-11-13 16:11:59,205 [myid:] - INFO
  [NIOServerCxn.Factory:0.0.0.0/0.0.0.0:2181:NIOServerCnxnFactory@215] -
  Accepted socket connection from /127.0.0.1:53201

2017-11-13 16:11:59,207 [myid:] - WARN
  [NIOServerCxn.Factory:0.0.0.0/0.0.0.0:21 81:NIOServerCnxn@383] -
  Exception causing close of session 0x0: null

2017-11-13 16:11:59,209 [myid:] - INFO
  [NIOServerCxn.Factory:0.0.0.0/0.0.0.0:2181:NIOServerCnxn@1040] -
  Closed socket connection for client /127.0.0.1:53201 (no session
  established for client)

Also, the port number in this statement keep increasing"Accepted socket connection from /127.0.0.1:53201". Is it scanning the port?

Below are some background.
Version:

zookeeper-3.4.11

kafka_2.10-0.10.2.1

logstash-5.4.0

(Plugin)logstash-input-kafka (5.1.6)

And here are my config:

Zoo.cfg (zookeeper)

tickTime=2000
initLimit=10
syncLimit=5
clientPort=2181

server.properties (Kafka)

listeners=PLAINTEXT://localhost:9092
zookeeper.connect=127.0.0.1:2181

logstash.config (logstash)

input {
    kafka {
        bootstrap_servers => "localhost:2181"
        topics => "test"
    }
}

I guess the problem is due to the config between zookeeper and kafka but i have no idea how to figure it out. Pls help.


问:
Margin on child element moves parent element
I have a div (parent) that contains another div (child). Parent is the first element in body with no particular CSS style. When I set

```<code>.child
{
    margin-top: 10px;
}
</code>```

The end result is that top of my child is still aligned with parent. Instead of child being shifted for 10px downwards, my parent moves 10px down.

My DOCTYPE is set to XHTML Transitional.

What am I missing here?

edit 1

My parent needs to have strictly defined dimensions because it has a background that has to be displayed under it from top to bottom (pixel perfect). So setting vertical margins on it is a no go.

edit 2

This behaviour is the same on FF, IE as well as CR.

答:
Neat CSS-only solution

Use the following code to prepend a contentless first-child to the unintentionally moving div:

```<code>.parent:before
{content: '';position: relative;height: 0px;width: 0px;overflow: hidden;white-space: pre;}
</code>```

The advantage of this method is that you do not need to change the CSS of any existing element, and therefore has minimal impact on design. Next to this, the element that is added is a pseudo-element, which is not in the DOM-tree.

Support for pseudo-elements is wide-spread: Firefox 3+, Safari 3+, Chrome 3+, Opera 10+, and IE 8+. This will work in any modern browser (be careful with the newer ::before, which is not supported in IE8).

Context

If the first child of an element has a margin-top, the parent will adjust its position as a way of collapsing redundant margins. Why? It's just like that.

Given the following problem:

```<code><style type="text/css">
div {position: relative;}
.parent {background-color: #ccc;}
.child {margin-top: 40px;}
</style>

<div class="parent"><!--This div moves 40px too-->
    <div class="child">Hello world!</div>
</div>
</code>```

You can fix it by adding a child with content, such as a simple space. But we all hate to add spaces for what is a design-only issue. Therefore, use the white-space property to fake content.

```<code><style type="text/css">
div {position: relative;}
.parent {background-color: #ccc;}
.child {margin-top: 40px;}
.fix {position: relative;white-space: pre;height: 0px;width: 0px;overflow: hidden;}
</style>

<div class="parent"><!--This div won't move anymore-->
    <div class="fix"></div>
    <div class="child">Hello world!</div>
</div>
</code>```

Where position: relative; ensures correct positioning of the fix. And white-space: pre; makes you not having to add any content - like a white space - to the fix. And height: 0px;width: 0px;overflow: hidden; makes sure you'll never see the fix.

You might need to add line-height: 0px; or max-height: 0px; to ensure the height is actually zero in ancient IE browsers (I'm unsure). And optionally you could add  to it in old IE browsers, if it does not work.

In short, you can do all this with only CSS (which removes the need to add an actual child to the HTML DOM-tree):

```<code><style type="text/css">
div {position: relative;}
.parent {background-color: #ccc;}
.child {margin-top: 40px;}

.parent:before {content: '';position: relative;height: 0px;width: 0px;overflow: hidden;white-space: pre;}
</style>

<div class="parent"><!--This div won't move anymore-->
    <div class="child">Hello world!</div>
</div>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a div (parent) that contains another div (child). Parent is the first element in body with no particular CSS style. When I set

.child
{
    margin-top: 10px;
}

The end result is that top of my child is still aligned with parent. Instead of child being shifted for 10px downwards, my parent moves 10px down.

My DOCTYPE is set to XHTML Transitional.

What am I missing here?

edit 1

My parent needs to have strictly defined dimensions because it has a background that has to be displayed under it from top to bottom (pixel perfect). So setting vertical margins on it is a no go.

edit 2

This behaviour is the same on FF, IE as well as CR.

Body:
Neat CSS-only solution

Use the following code to prepend a contentless first-child to the unintentionally moving div:

.parent:before
{content: '';position: relative;height: 0px;width: 0px;overflow: hidden;white-space: pre;}

The advantage of this method is that you do not need to change the CSS of any existing element, and therefore has minimal impact on design. Next to this, the element that is added is a pseudo-element, which is not in the DOM-tree.

Support for pseudo-elements is wide-spread: Firefox 3+, Safari 3+, Chrome 3+, Opera 10+, and IE 8+. This will work in any modern browser (be careful with the newer ::before, which is not supported in IE8).

Context

If the first child of an element has a margin-top, the parent will adjust its position as a way of collapsing redundant margins. Why? It's just like that.

Given the following problem:

<style type="text/css">
div {position: relative;}
.parent {background-color: #ccc;}
.child {margin-top: 40px;}
</style>

<div class="parent"><!--This div moves 40px too-->
    <div class="child">Hello world!</div>
</div>

You can fix it by adding a child with content, such as a simple space. But we all hate to add spaces for what is a design-only issue. Therefore, use the white-space property to fake content.

<style type="text/css">
div {position: relative;}
.parent {background-color: #ccc;}
.child {margin-top: 40px;}
.fix {position: relative;white-space: pre;height: 0px;width: 0px;overflow: hidden;}
</style>

<div class="parent"><!--This div won't move anymore-->
    <div class="fix"></div>
    <div class="child">Hello world!</div>
</div>

Where position: relative; ensures correct positioning of the fix. And white-space: pre; makes you not having to add any content - like a white space - to the fix. And height: 0px;width: 0px;overflow: hidden; makes sure you'll never see the fix.

You might need to add line-height: 0px; or max-height: 0px; to ensure the height is actually zero in ancient IE browsers (I'm unsure). And optionally you could add <!--dummy--> to it in old IE browsers, if it does not work.

In short, you can do all this with only CSS (which removes the need to add an actual child to the HTML DOM-tree):

<style type="text/css">
div {position: relative;}
.parent {background-color: #ccc;}
.child {margin-top: 40px;}

.parent:before {content: '';position: relative;height: 0px;width: 0px;overflow: hidden;white-space: pre;}
</style>

<div class="parent"><!--This div won't move anymore-->
    <div class="child">Hello world!</div>
</div>


问:
Fill 'As Workbook' variable with 'As String' variable
My VBA project has a dynamic name since it contains e.g. the 'version number'.
But I would like to refer to 1 of its sheets from another workbook (that workbook has been created by my project to do the work in there).

I have this code and that works, but it is not dynamically:

```<code>   Dim ProjectPathName As String
    Dim ProjectPathNameLength As Integer
    Dim ProjectFileName As String
    Dim PosLastBackSlash As Integer
    Dim RDXX As Workbook

    ProjectPathName = Application.VBE.ActiveVBProject.FileName
    ProjectPathNameLength = Len(ProjectPathName)
    PosLastBackSlash = InStrRev(ProjectPathName, "\")
    ProjectFileName = Right(ProjectPathName, (ProjectPathNameLength - PosLastBackSlash))

    Set RDXX = Workbooks("RDXX 2017-10_2_DEV.xlam")
</code>```

This is what I have tried so far:

```<code>'    Set wbDeltaWorks = Workbooks(FileName:=ProjectFileName)
    '   Set wbDeltaWorks = Workbooks(FileName = ProjectFileName)
    '    Set wbDeltaWorks = Workbooks(ProjectFileName)
    '    Set wbDeltaWorks = Workbooks("ProjectFileName")
    '    Set wbDeltaWorks = Workbooks("" & ProjectFileName & "")
    '    Set wbDeltaWorks = Workbooks(""" & ProjectFileName & """)
    '    Set wbDeltaWorks = Workbooks(ProjectFileName.Value)
    '    Set wbDeltaWorks = Workbooks(1)
    '    Set wbDeltaWorks = ProjectFileName
</code>```

Can you help me on this?

All help is much appreciated!

答:
Thanks for the help, it got me on the right track! I went for what Rory said, since that already worked "the Set wbDeltaWorks = Workbooks(ProjectFileName) should work assuming the name is correct and it includes the extension.".
I only used it to late in the process at a stage where another workbook was active. Therefore I got the wrong project name.

thanks again!

Body:
My VBA project has a dynamic name since it contains e.g. the 'version number'.
But I would like to refer to 1 of its sheets from another workbook (that workbook has been created by my project to do the work in there).

I have this code and that works, but it is not dynamically:

   Dim ProjectPathName As String
    Dim ProjectPathNameLength As Integer
    Dim ProjectFileName As String
    Dim PosLastBackSlash As Integer
    Dim RDXX As Workbook

    ProjectPathName = Application.VBE.ActiveVBProject.FileName
    ProjectPathNameLength = Len(ProjectPathName)
    PosLastBackSlash = InStrRev(ProjectPathName, "\")
    ProjectFileName = Right(ProjectPathName, (ProjectPathNameLength - PosLastBackSlash))

    Set RDXX = Workbooks("RDXX 2017-10_2_DEV.xlam")

This is what I have tried so far:

'    Set wbDeltaWorks = Workbooks(FileName:=ProjectFileName)
    '   Set wbDeltaWorks = Workbooks(FileName = ProjectFileName)
    '    Set wbDeltaWorks = Workbooks(ProjectFileName)
    '    Set wbDeltaWorks = Workbooks("ProjectFileName")
    '    Set wbDeltaWorks = Workbooks("" & ProjectFileName & "")
    '    Set wbDeltaWorks = Workbooks(""" & ProjectFileName & """)
    '    Set wbDeltaWorks = Workbooks(ProjectFileName.Value)
    '    Set wbDeltaWorks = Workbooks(1)
    '    Set wbDeltaWorks = ProjectFileName

Can you help me on this?

All help is much appreciated!


问:
PHP file structure array to json string only displaying first file properly
I have a bit of code that scans a given directory and outputs the contents into an array, a sample array is as follow;

```<code>Array
(
    [0] => docker-vs-vagrant.png
    [floor] => Array
        (
            [moretesting] => Array
                (
                    [0] => Webserver_requests_graph.jpg
                )

        )

    [plans] => Array
        (
            [0] => Screen Shot 2017-10-09 at 7.08.52 pm.png
        )

    [1] => screenshot.png
    [screenshots] => Array
        (
        )

    [test] => Array
        (
            [0] => Screen_Shot_2017-10-09_at_4_52_32_pm.png
        )

    [test2] => Array
        (
            [0] => testScreen Shot 2017-10-09 at 7.08.52 pm.png
        )

)
</code>```

As you can tell, the files marked with the keys [0] and [1] are in the root directory, and everything else is organised into folder structure.

The code I am using to generate this array is as follows;

```<code>function dirToArray($dir) {
    $contents = array();

    foreach (scandir($dir) as $node) {
        if ($node == '.' || $node == '..') continue;

        if (is_dir($dir . '/' . $node)) {
            $contents[$node] = $this->dirToArray($dir . '/' . $node);
        } else {
            $contents[] = $node;
        }
    }

    return $contents;
}
</code>```

After this I am using a inbuilt cakephp function to flatten the array so it looks like the following;

```<code>Array
(
    [0] => docker-vs-vagrant.png
    [floor.moretesting.0] => Webserver_requests_graph.jpg
    [plans.0] => Screen Shot 2017-10-09 at 7.08.52 pm.png
    [1] => screenshot.png
    [test.0] => Screen_Shot_2017-10-09_at_4_52_32_pm.png
    [test2.0] => testScreen Shot 2017-10-09 at 7.08.52 pm.png
)
</code>```

After that i need to format it into json that my javascript api can read, the function to do this is as follows;

```<code>function flatArrayToJsonString($flatArray)
{
    $arrayId = 1;
    $final_array = [[0, '/', '/', false]];

    foreach ($flatArray as $key => $val) {
        if ($key == '0') {
            $final_array[] = [$arrayId, '/' . $val, $val, true];
            $arrayId++;
        } else {
            $exploded_key = explode('.', $key);
            foreach ($exploded_key as $k => $v) {
                if ($v == '0') {
                    $dots = '.. ';
                    for ($i = 0; $i < count(array_slice($exploded_key, 0, $k)); $i++) {
                        $dots .= '.. ';
                    }
                    $final_array[] = [$arrayId, '/' . join('/', array_slice($exploded_key, 0, $k)) . '/' . $val, $dots . $val, true];
                    $arrayId++;
                } else {
                    $dots = '.. ';
                    for ($i = 0; $i < count(array_slice($exploded_key, 0, $k)); $i++) {
                        $dots .= '.. ';
                    }
                    $final_array[] = [$arrayId, '/' . join('/', array_slice($exploded_key, 0, $k + 1)), $dots . $v, false];
                    $arrayId++;
                }
            }
        }
    }

    return json_encode($final_array);
}
</code>```

The final result that is being returned to me is as follows;

```<code>[
    [0,"\/","\/",false],
    [1,"\/docker-vs-vagrant.png","docker-vs-vagrant.png",true],
    [2,"\/floor",".. floor",false],
    [3,"\/floor\/moretesting",".. .. moretesting",false],
    [4,"\/floor\/moretesting\/Webserver_requests_graph.jpg",".. .. .. Webserver_requests_graph.jpg",true],
    [5,"\/plans",".. plans",false],
    [6,"\/plans\/Screen Shot 2017-10-09 at 7.08.52 pm.png",".. .. Screen Shot 2017-10-09 at 7.08.52 pm.png",true],
    [7,"\/1",".. 1",false],
    [8,"\/test",".. test",false],
    [9,"\/test\/Screen_Shot_2017-10-09_at_4_52_32_pm.png",".. .. Screen_Shot_2017-10-09_at_4_52_32_pm.png",true],
    [10,"\/test2",".. test2",false],
    [11,"\/test2\/testScreen Shot 2017-10-09 at 7.08.52 pm.png",".. .. testScreen Shot 2017-10-09 at 7.08.52 pm.png",true]
]
</code>```

This works perfect only if there is 1 file in the root or any of the subdirectories.

But once another file is added it breaks.

You can see that the following value;

```<code>[1] => screenshot.png
</code>```

is in the wrong place, and in the final output is broken, being displayed as;

```<code>[7,"\/1",".. 1",false],
</code>```

as im trying to display a hierarchy, this should displayed like so;

```<code>[1,"\/docker-vs-vagrant.png","docker-vs-vagrant.png",true],
[2,"\/screenshot.png","screenshot.png",true],
</code>```

The description of the final output is as follows;

```<code>[id, fullpath, displayname, leaf]
</code>```

where leaf means if it is a file or a directory.

Im sorry its such a big post, but im stumped on how to go about fixing this.

Any help would be greatly appreciated.

答:
Do you particularly need to flatten the array? Because if not, you could literally just have this:

```<code>function flatArrayToJsonString($flatArray)
{
    return json_encode($flatArray); //returns string
}
</code>```

and then do appropriate formatting in javascript.

However, i don't recommend flattening the original array, as it has directory structure/hierarchy in the layout of your original array before you flatten it with cakephp.

Edit: Also to have an id doesn't quite make sense in a lot of scenarios, because files and directories could be added or removed, invalidating any id's originally sent through by php. Perhaps you should re-look at your current approach to the problem

Body:
I have a bit of code that scans a given directory and outputs the contents into an array, a sample array is as follow;

Array
(
    [0] => docker-vs-vagrant.png
    [floor] => Array
        (
            [moretesting] => Array
                (
                    [0] => Webserver_requests_graph.jpg
                )

        )

    [plans] => Array
        (
            [0] => Screen Shot 2017-10-09 at 7.08.52 pm.png
        )

    [1] => screenshot.png
    [screenshots] => Array
        (
        )

    [test] => Array
        (
            [0] => Screen_Shot_2017-10-09_at_4_52_32_pm.png
        )

    [test2] => Array
        (
            [0] => testScreen Shot 2017-10-09 at 7.08.52 pm.png
        )

)

As you can tell, the files marked with the keys [0] and [1] are in the root directory, and everything else is organised into folder structure.

The code I am using to generate this array is as follows;

function dirToArray($dir) {
    $contents = array();

    foreach (scandir($dir) as $node) {
        if ($node == '.' || $node == '..') continue;

        if (is_dir($dir . '/' . $node)) {
            $contents[$node] = $this->dirToArray($dir . '/' . $node);
        } else {
            $contents[] = $node;
        }
    }

    return $contents;
}

After this I am using a inbuilt cakephp function to flatten the array so it looks like the following;

Array
(
    [0] => docker-vs-vagrant.png
    [floor.moretesting.0] => Webserver_requests_graph.jpg
    [plans.0] => Screen Shot 2017-10-09 at 7.08.52 pm.png
    [1] => screenshot.png
    [test.0] => Screen_Shot_2017-10-09_at_4_52_32_pm.png
    [test2.0] => testScreen Shot 2017-10-09 at 7.08.52 pm.png
)

After that i need to format it into json that my javascript api can read, the function to do this is as follows;

function flatArrayToJsonString($flatArray)
{
    $arrayId = 1;
    $final_array = [[0, '/', '/', false]];

    foreach ($flatArray as $key => $val) {
        if ($key == '0') {
            $final_array[] = [$arrayId, '/' . $val, $val, true];
            $arrayId++;
        } else {
            $exploded_key = explode('.', $key);
            foreach ($exploded_key as $k => $v) {
                if ($v == '0') {
                    $dots = '.. ';
                    for ($i = 0; $i < count(array_slice($exploded_key, 0, $k)); $i++) {
                        $dots .= '.. ';
                    }
                    $final_array[] = [$arrayId, '/' . join('/', array_slice($exploded_key, 0, $k)) . '/' . $val, $dots . $val, true];
                    $arrayId++;
                } else {
                    $dots = '.. ';
                    for ($i = 0; $i < count(array_slice($exploded_key, 0, $k)); $i++) {
                        $dots .= '.. ';
                    }
                    $final_array[] = [$arrayId, '/' . join('/', array_slice($exploded_key, 0, $k + 1)), $dots . $v, false];
                    $arrayId++;
                }
            }
        }
    }

    return json_encode($final_array);
}

The final result that is being returned to me is as follows;

[
    [0,"\/","\/",false],
    [1,"\/docker-vs-vagrant.png","docker-vs-vagrant.png",true],
    [2,"\/floor",".. floor",false],
    [3,"\/floor\/moretesting",".. .. moretesting",false],
    [4,"\/floor\/moretesting\/Webserver_requests_graph.jpg",".. .. .. Webserver_requests_graph.jpg",true],
    [5,"\/plans",".. plans",false],
    [6,"\/plans\/Screen Shot 2017-10-09 at 7.08.52 pm.png",".. .. Screen Shot 2017-10-09 at 7.08.52 pm.png",true],
    [7,"\/1",".. 1",false],
    [8,"\/test",".. test",false],
    [9,"\/test\/Screen_Shot_2017-10-09_at_4_52_32_pm.png",".. .. Screen_Shot_2017-10-09_at_4_52_32_pm.png",true],
    [10,"\/test2",".. test2",false],
    [11,"\/test2\/testScreen Shot 2017-10-09 at 7.08.52 pm.png",".. .. testScreen Shot 2017-10-09 at 7.08.52 pm.png",true]
]

This works perfect only if there is 1 file in the root or any of the subdirectories.

But once another file is added it breaks.

You can see that the following value;

[1] => screenshot.png

is in the wrong place, and in the final output is broken, being displayed as;

[7,"\/1",".. 1",false],

as im trying to display a hierarchy, this should displayed like so;

[1,"\/docker-vs-vagrant.png","docker-vs-vagrant.png",true],
[2,"\/screenshot.png","screenshot.png",true],

The description of the final output is as follows;

[id, fullpath, displayname, leaf]

where leaf means if it is a file or a directory.

Im sorry its such a big post, but im stumped on how to go about fixing this.

Any help would be greatly appreciated.

Body:
Do you particularly need to flatten the array? Because if not, you could literally just have this:

function flatArrayToJsonString($flatArray)
{
    return json_encode($flatArray); //returns string
}

and then do appropriate formatting in javascript.

However, i don't recommend flattening the original array, as it has directory structure/hierarchy in the layout of your original array before you flatten it with cakephp.

Edit: Also to have an id doesn't quite make sense in a lot of scenarios, because files and directories could be added or removed, invalidating any id's originally sent through by php. Perhaps you should re-look at your current approach to the problem


问:
Can't extract data from Json
I can't extract data from json that I got from an api.
I tried for hours, tried all kinds of formats. Read Stackoverflow threads like How do I extract data from JSON with PHP?, but I can't see what I am doing wrong.

This is the code so far:

```<code>$api_results = '{"status":"0000","data":{"opening_price":"6998000","closing_price":"7270000","min_price":"6750000","max_price":"7997000","average_price":"7188302.5804","units_traded":"78484.9241002","volume_1day":"78484.9241002","volume_7day":"335611.84181738","buy_price":"7268000","sell_price":"7274000","date":"1510563513031"}}';

$results = json_decode($api_results, true);

// Some variations I tried:
var_dump($results->status[1]);
var_dump($results->data[1]->opening_price);
var_dump($results["data"][1]["opening_price"]);
</code>```

End result: NULL NULL NULL

What am I doing wrong?

Thanks for the answers! I will upvote the working ones. Seems I got confused in the formating!

Title: Can't extract data from Json

Body:
I can't extract data from json that I got from an api.
I tried for hours, tried all kinds of formats. Read Stackoverflow threads like How do I extract data from JSON with PHP?, but I can't see what I am doing wrong.

This is the code so far:

$api_results = '{"status":"0000","data":{"opening_price":"6998000","closing_price":"7270000","min_price":"6750000","max_price":"7997000","average_price":"7188302.5804","units_traded":"78484.9241002","volume_1day":"78484.9241002","volume_7day":"335611.84181738","buy_price":"7268000","sell_price":"7274000","date":"1510563513031"}}';

$results = json_decode($api_results, true);

// Some variations I tried:
var_dump($results->status[1]);
var_dump($results->data[1]->opening_price);
var_dump($results["data"][1]["opening_price"]);

End result: NULL NULL NULL

What am I doing wrong?

Thanks for the answers! I will upvote the working ones. Seems I got confused in the formating!

Body:
Use this code like i think work it fine..

<?php
$api_results = '{"status":"0000","data":{"opening_price":"6998000","closing_price":"7270000","min_price":"6750000","max_price":"7997000","average_price":"7188302.5804","units_traded":"78484.9241002","volume_1day":"78484.9241002","volume_7day":"335611.84181738","buy_price":"7268000","sell_price":"7274000","date":"1510563513031"}}';
$results = json_decode($api_results);

print_r($results);
var_dump($results->status);
$var = $results->data;
var_dump($var->opening_price);
?>

stdClass Object
(
    [status] => 0000
    [data] => stdClass Object
        (
            [opening_price] => 6998000
            [closing_price] => 7270000
            [min_price] => 6750000
            [max_price] => 7997000
            [average_price] => 7188302.5804
            [units_traded] => 78484.9241002
            [volume_1day] => 78484.9241002
            [volume_7day] => 335611.84181738
            [buy_price] => 7268000
            [sell_price] => 7274000
            [date] => 1510563513031
        )

)

string(4) "0000"
string(7) "6998000"


问:
How can I transform XML into a List<string> or String[]?
How can I transform the following XML into a List<string> or String[]:

```<code><Ids>
  <id>1</id>
  <id>2</id>
</Ids>
</code>```

答:
the code to convert a string array to xml

items is a string array

```<code>items.Aggregate("", (current, x) => current + ("<item>" + x + "</item>"))
</code>```

Body:
How can I transform the following XML into a List<string> or String[]:

<Ids>
  <id>1</id>
  <id>2</id>
</Ids>

Body:
the code to convert a string array to xml

items is a string array

items.Aggregate("", (current, x) => current + ("<item>" + x + "</item>"))


问:
Python: adding comments to specific cell using Drive API
I am trying to automate some simple updating of a Google spreadsheet and I'm using the gspread library to do so. One task that is critical and not currently supported by gspread is the ability to add comments to a specific cell (there's an open issue for this and even a gist solution but I was getting a 404 error when trying to use it).

I know that the Google Drive API (v3) supports adding comments as described here, but I'm having issues with authenticating and could use some help.

What I have/know:

I have already setup the OAuth 2.0 and registered for the API through Google, as well as have the client_secret.json in my directory, but my knowledge of web requests and responses is limited so going through the Drive API documentation hardly makes sense. I know in order to create the comments I will have to make use of anchors and specify the cell location using column/row numbers.

What I'm stuck on:

When using the Google API Explorer, I'm getting a 400 error with the message: The 'fields' parameter is required for this method. How can I make the POST request using my authentication? I think from there I'd be able to actually add the comments myself.

答:
I'm getting a 400 error with the message: The 'fields' parameter is required for this method

The error is asking for a property which you want returned (these properties are listed in Drive API files resource).

You can just place ' * ' to indicate you want it to return a complete response. That's the quick fix.


问:
Generalizing integer calculator example from PLY to floating number
I am reading the first example from

https://github.com/dabeaz/ply

It is a basic calculator allowing for only expression involving '(',')','+','-','*','/', integers and assignement (for instance x=3) and throwing the evaluation of the expression (even it it's result is not an integer, for instance '3/4').

I would like to allow for floating numbers, so that I basically modified the code from the example as follows but it doesn't work :

```<code># -----------------------------------------------------------------------------
# calc.py
#
# A simple calculator with variables.
# -----------------------------------------------------------------------------

tokens = (
    'NAME','INTEGER', 'FLOAT',
    'PLUS','MINUS','TIMES','DIVIDE','EQUALS',
    'LPAREN','RPAREN',
    )

# Tokens

t_PLUS    = r'\+'
t_MINUS   = r'-'
t_TIMES   = r'\*'
t_DIVIDE  = r'/'
t_EQUALS  = r'='
t_LPAREN  = r'\('
t_RPAREN  = r'\)'
t_NAME    = r'[a-zA-Z_][a-zA-Z0-9_]*'

def t_INTEGER(t):
    r'\d+'
    t.value = int(t.value)
    return t

def t_FLOAT(t):
    r'/^(?!0\d)\d*(\.\d+)?$/mg'
    t.value = float(t.value)
    return t

# Ignored characters
t_ignore = " \t"

def t_newline(t):
    r'\n+'
    t.lexer.lineno += t.value.count("\n")

def t_error(t):
    print("Illegal character '%s'" % t.value[0])
    t.lexer.skip(1)

# Build the lexer
import ply.lex as lex
lex.lex()

# Precedence rules for the arithmetic operators
precedence = (
    ('left','PLUS','MINUS'),
    ('left','TIMES','DIVIDE'),
    ('right','UMINUS'),
    )

# dictionary of names (for storing variables)
names = { }

def p_statement_assign(p):
    'statement : NAME EQUALS expression'
    names[p[1]] = p[3]

def p_statement_expr(p):
    'statement : expression'
    print(p[1])

def p_expression_binop(p):
    '''expression : expression PLUS expression
                  | expression MINUS expression
                  | expression TIMES expression
                  | expression DIVIDE expression'''
    if p[2] == '+'  : p[0] = p[1] + p[3]
    elif p[2] == '-': p[0] = p[1] - p[3]
    elif p[2] == '*': p[0] = p[1] * p[3]
    elif p[2] == '/': p[0] = p[1] / p[3]

def p_expression_uminus(p):
    'expression : MINUS expression %prec UMINUS'
    p[0] = -p[2]

def p_expression_group(p):
    'expression : LPAREN expression RPAREN'
    p[0] = p[2]

def p_expression_integer(p):
    'expression : INTEGER'
    p[0] = p[1]

def p_expression_float(p):
    'expression : FLOAT'
    p[0] = p[1]

def p_expression_name(p):
    'expression : NAME'
    try:
        p[0] = names[p[1]]
    except LookupError:
        print("Undefined name '%s'" % p[1])
        p[0] = 0

def p_error(p):
    print("Syntax error at '%s'" % p.value)

import ply.yacc as yacc
yacc.yacc()

while True:
    try:
        s = input('calc > ')
    except EOFError:
        break
    yacc.parse(s)
</code>```

I have error :

```<code>calc > 3.14+1
Illegal character '.'
Syntax error at '14'
</code>```

答:
ply parses the T_xxx members in the order of declaration (using reflection on your module). What happens here is that T_INTEGER matches before T_FLOAT. So the integer part of your float is parsed, then ply chokes on the dot.

That would directly work if your regex for floats wasn't off (completely missed that point in my first answer, blinded by the obvious wrong order).

I've simplified it to \d+\.\d+ (which doesn't match 1. or .9 so not the best choice), but you can borrow a better one taken from a similar issue: PLY lexer for numbers always returns double

You have to get T_FLOAT parsed before T_INTEGER. Just swap both declarations to do so:

```<code>def t_FLOAT(t):
    r'\d+\.\d+'
    # a better regex taking exponents into account:
    '[-+]?[0-9]+(\.([0-9]+)?([eE][-+]?[0-9]+)?|[eE][-+]?[0-9]+)'
    t.value = float(t.value)
    return t

def t_INTEGER(t):
    r'\d+'
    t.value = int(t.value)
    return t
</code>```

As a general rule for ply, do this for all patterns that are longer/more specific than others to avoid conflicts.

Body:
I am reading the first example from

https://github.com/dabeaz/ply

It is a basic calculator allowing for only expression involving '(',')','+','-','*','/', integers and assignement (for instance x=3) and throwing the evaluation of the expression (even it it's result is not an integer, for instance '3/4').

I would like to allow for floating numbers, so that I basically modified the code from the example as follows but it doesn't work :

# -----------------------------------------------------------------------------
# calc.py
#
# A simple calculator with variables.
# -----------------------------------------------------------------------------

tokens = (
    'NAME','INTEGER', 'FLOAT',
    'PLUS','MINUS','TIMES','DIVIDE','EQUALS',
    'LPAREN','RPAREN',
    )

# Tokens

t_PLUS    = r'\+'
t_MINUS   = r'-'
t_TIMES   = r'\*'
t_DIVIDE  = r'/'
t_EQUALS  = r'='
t_LPAREN  = r'\('
t_RPAREN  = r'\)'
t_NAME    = r'[a-zA-Z_][a-zA-Z0-9_]*'

def t_INTEGER(t):
    r'\d+'
    t.value = int(t.value)
    return t

def t_FLOAT(t):
    r'/^(?!0\d)\d*(\.\d+)?$/mg'
    t.value = float(t.value)
    return t

# Ignored characters
t_ignore = " \t"

def t_newline(t):
    r'\n+'
    t.lexer.lineno += t.value.count("\n")

def t_error(t):
    print("Illegal character '%s'" % t.value[0])
    t.lexer.skip(1)

# Build the lexer
import ply.lex as lex
lex.lex()

# Precedence rules for the arithmetic operators
precedence = (
    ('left','PLUS','MINUS'),
    ('left','TIMES','DIVIDE'),
    ('right','UMINUS'),
    )

# dictionary of names (for storing variables)
names = { }

def p_statement_assign(p):
    'statement : NAME EQUALS expression'
    names[p[1]] = p[3]

def p_statement_expr(p):
    'statement : expression'
    print(p[1])

def p_expression_binop(p):
    '''expression : expression PLUS expression
                  | expression MINUS expression
                  | expression TIMES expression
                  | expression DIVIDE expression'''
    if p[2] == '+'  : p[0] = p[1] + p[3]
    elif p[2] == '-': p[0] = p[1] - p[3]
    elif p[2] == '*': p[0] = p[1] * p[3]
    elif p[2] == '/': p[0] = p[1] / p[3]

def p_expression_uminus(p):
    'expression : MINUS expression %prec UMINUS'
    p[0] = -p[2]

def p_expression_group(p):
    'expression : LPAREN expression RPAREN'
    p[0] = p[2]

def p_expression_integer(p):
    'expression : INTEGER'
    p[0] = p[1]

def p_expression_float(p):
    'expression : FLOAT'
    p[0] = p[1]

def p_expression_name(p):
    'expression : NAME'
    try:
        p[0] = names[p[1]]
    except LookupError:
        print("Undefined name '%s'" % p[1])
        p[0] = 0

def p_error(p):
    print("Syntax error at '%s'" % p.value)

import ply.yacc as yacc
yacc.yacc()

while True:
    try:
        s = input('calc > ')
    except EOFError:
        break
    yacc.parse(s)

I have error :

calc > 3.14+1
Illegal character '.'
Syntax error at '14'

Body:
ply parses the T_xxx members in the order of declaration (using reflection on your module). What happens here is that T_INTEGER matches before T_FLOAT. So the integer part of your float is parsed, then ply chokes on the dot.

That would directly work if your regex for floats wasn't off (completely missed that point in my first answer, blinded by the obvious wrong order).

I've simplified it to \d+\.\d+ (which doesn't match 1. or .9 so not the best choice), but you can borrow a better one taken from a similar issue: PLY lexer for numbers always returns double

You have to get T_FLOAT parsed before T_INTEGER. Just swap both declarations to do so:

def t_FLOAT(t):
    r'\d+\.\d+'
    # a better regex taking exponents into account:
    '[-+]?[0-9]+(\.([0-9]+)?([eE][-+]?[0-9]+)?|[eE][-+]?[0-9]+)'
    t.value = float(t.value)
    return t

def t_INTEGER(t):
    r'\d+'
    t.value = int(t.value)
    return t

As a general rule for ply, do this for all patterns that are longer/more specific than others to avoid conflicts.


问:
Is PHP ArgumentCountError server specific?
I am facing very weird problem since last two days, I have two different servers one is windows(php v5.3) and second is linux(php v7.1 ngnix). I have a project(written by someone) which is already running on windows server, now I have to move this project on linux server (with no code change). My issue, There is a login function -

```<code>Function userAuthentication($username,$password,$locationId,$url,$source)
{
....
}
</code>```

And It is calling as (On windows server)

```<code>userAuthentication($username, $password,'',$url) ;
</code>```

I know parameters are mismatched in this case but as I tested, this code is actually giving me result and working fine on windows but that same code is giving me obvious error on Linux server-

ArgumentCountError: Too few arguments to function
  Authentication::userAuthentication(), 4 passed in

It can be resolve by changing that code but I don't want (can to be many function with same error).
I already googled but not found anything. I am very curious to know Why this is not happening on windows. Is that ArgumentCountError server specific or windows server not taking it as critical as linux, or php version issue or any other config.? what I suppose to fix to resolve this issue.?

Anyone have any idea about that please help me out, Thanks

答:
This has everything to do with the newer PHP versions that are (as they should) be more strict about calling. If you want this to work again make the additional parameters optional by giving them default values.

You should update to 7.x locally to prevent this sort of issues.

Like:

```<code>Function userAuthentication($username,$password,$locationId,$url,$source = '')
</code>```

Body:
I am facing very weird problem since last two days, I have two different servers one is windows(php v5.3) and second is linux(php v7.1 ngnix). I have a project(written by someone) which is already running on windows server, now I have to move this project on linux server (with no code change). My issue, There is a login function -

Function userAuthentication($username,$password,$locationId,$url,$source)
{
....
}

And It is calling as (On windows server)

userAuthentication($username, $password,'',$url) ;

I know parameters are mismatched in this case but as I tested, this code is actually giving me result and working fine on windows but that same code is giving me obvious error on Linux server-

ArgumentCountError: Too few arguments to function
  Authentication::userAuthentication(), 4 passed in

It can be resolve by changing that code but I don't want (can to be many function with same error).
I already googled but not found anything. I am very curious to know Why this is not happening on windows. Is that ArgumentCountError server specific or windows server not taking it as critical as linux, or php version issue or any other config.? what I suppose to fix to resolve this issue.?

Anyone have any idea about that please help me out, Thanks

Body:
This has everything to do with the newer PHP versions that are (as they should) be more strict about calling. If you want this to work again make the additional parameters optional by giving them default values.

You should update to 7.x locally to prevent this sort of issues.

Like:

Function userAuthentication($username,$password,$locationId,$url,$source = '')


问:
JPA Unidirectional OneToOne FK in Child Table
I've got fk in child, but i need @JoinColumn in parent. By default, in OneToOne, joincolumn creates fk in parent table (where it is specified), i have existing tables with fk in child. (project new demands) Before it was mapped using mappedBy clause.

How can I use @JoinColumn for @OneToOne linking in the parent entity?

I want to make unidirectional relationship.

Why cant I use this:

```<code>@JoinColumn(name = "parent_id", referencedColumn = "childs_fk")
</code>```

ty!

Update:

In this example FK column "WEBSITE_ID" would be in Player table. My FK is in Website table.

In a bi-directional OneToOne relationship, a single foreign key is
  used in the owning side of the relationship. On the other hand, the
  target entity must use the mappedBy attribute.

I've got existing tables and my fk is not on the owner side,
+ I know for a fact that FK could be on both sides. This answer is not what I need.

答:
If you have a table Parent and one table Child and the foreign key is on the Child table with name PARENT_ID and pointing to the ID in table Parent then the annotation must look like:</p>

```<code>@JoinColumn(name="PARENT_ID")
</code>```

Body:
I've got fk in child, but i need @JoinColumn in parent. By default, in OneToOne, joincolumn creates fk in parent table (where it is specified), i have existing tables with fk in child. (project new demands) Before it was mapped using mappedBy clause.

How can I use @JoinColumn for @OneToOne linking in the parent entity?

I want to make unidirectional relationship.

Why cant I use this:

@JoinColumn(name = "parent_id", referencedColumn = "childs_fk")

ty!

Update:

In this example FK column "WEBSITE_ID" would be in Player table. My FK is in Website table.

In a bi-directional OneToOne relationship, a single foreign key is
  used in the owning side of the relationship. On the other hand, the
  target entity must use the mappedBy attribute.

I've got existing tables and my fk is not on the owner side,
+ I know for a fact that FK could be on both sides. This answer is not what I need.

Body:
If you have a table Parent and one table Child and the foreign key is on the Child table with name PARENT_ID and pointing to the ID in table Parent then the annotation must look like:

@JoinColumn(name="PARENT_ID")


问:
Page scrolling not working on asp.net after implement AM Chart
In my ASP.Net project page scrolling not working after implement AM chart in google chrome.

I have test in Mozilla Firefox, and safari browser Page scrolling is working properly in In google chrome page down scroll working but page up scroll not working.

答: Page Scroll not working because of Bootstrap CSS Conflict issue now page Scroll working properly </p>


问:
Multicolumn table in django template
How to fill multicolumn table in django template?
I have list of n elements (let's say just numbers there) and I want to create a table (looks like grid) with 5 cells in a row.

Very easy to create table of 1 column, but to create 5? Of course we assume than list may have arbitrary number of items from zero to couple hundreds.

```<code><tbody>
  {% for item in data.items.all %}
    <tr class="item-{{ item.number }}">{{ item.number }}</tr>
  {% endfor %}
</tbody>
</code>```

答:
Try the following code:

View

```<code>data = [1,2,3,4,......,99,100]
</code>```

Template

```<code><table border="1">
  <tbody>
    <tr>
      {% for item in data %}
        {% if forloop.counter|divisibleby:5 %}
          <td>{{ item }}</td>
          </tr>
          <tr>
        {% else %}
          <td>{{ item }}</td>
        {% endif %}
      {% endfor %}
    </tr>
  </tbody>
</table>
</code>```

This code checks the loop count each time. if it is divisible by 5 then close the current tr tag and add a new one.

This may not be the right way to achieve this.

Hope that helps.

Title: Multicolumn table in django template

Body:
How to fill multicolumn table in django template?
I have list of n elements (let's say just numbers there) and I want to create a table (looks like grid) with 5 cells in a row.

Very easy to create table of 1 column, but to create 5? Of course we assume than list may have arbitrary number of items from zero to couple hundreds.

  {% for item in data.items.all %}

{{ item.number }}

  {% endfor %}

Body:
Try the following code:

View

data = [1,2,3,4,......,99,100]

Template

<table border="1">
  <tbody>
    <tr>
      {% for item in data %}
        {% if forloop.counter|divisibleby:5 %}
          <td>{{ item }}</td>
          </tr>
          <tr>
        {% else %}
          <td>{{ item }}</td>
        {% endif %}
      {% endfor %}
    </tr>
  </tbody>
</table>

This code checks the loop count each time. if it is divisible by 5 then close the current tr tag and add a new one.

This may not be the right way to achieve this.

Hope that helps.


答:
The difference isn't in the Environment (windows vs. linux) rather the PHP version.

As you can see in the migration from PHP 7.0 to 7.1 (link: http://php.net/manual/en/migration71.incompatible.php)

Throw on passing too few function arguments

Previously, a warning would be emitted for invoking user-defined
  functions with too few arguments. Now, this warning has been promoted
  to an Error exception. This change only applies to user-defined
  functions, not internal functions. For example:

```<code><?php
function test($param){}
test();
</code>```

The above example will output something similar to:

Fatal error: Uncaught ArgumentCountError: Too few arguments to
  function test(), 0 passed in %s on line %d and exactly 1 expected in
  %s:%d

How to solve it?

You'll have to define all the parameters in the function. It might be "uncomfortable" but it's a better practice as a developer. Don't be lazy regarding this issue.

Title: Is PHP ArgumentCountError server specific?

Body:
The difference isn't in the Environment (windows vs. linux) rather the PHP version.

As you can see in the migration from PHP 7.0 to 7.1 (link: http://php.net/manual/en/migration71.incompatible.php)

Throw on passing too few function arguments

Previously, a warning would be emitted for invoking user-defined
  functions with too few arguments. Now, this warning has been promoted
  to an Error exception. This change only applies to user-defined
  functions, not internal functions. For example:

<?php
function test($param){}
test();

The above example will output something similar to:

Fatal error: Uncaught ArgumentCountError: Too few arguments to
  function test(), 0 passed in %s on line %d and exactly 1 expected in
  %s:%d

How to solve it?

You'll have to define all the parameters in the function. It might be "uncomfortable" but it's a better practice as a developer. Don't be lazy regarding this issue.


问:
Call function from activity to close the soft keyboard android
I'm new to mobile automation and I've been trying to find a way to close the soft keyboard on Android (using Java). The best solution I've come across so far was from this post:

Close/hide the Android Soft Keyboard

The function that I'm trying to use from there is:

```<code>public static void hideKeyboard(Activity activity) {
    InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
    //Find the currently focused view, so we can grab the correct window token from it.
    View view = activity.getCurrentFocus();
    //If no view currently has focus, create a new one, just so we can grab a window token from it
    if (view == null) {
        view = new View(activity);
    }
    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
</code>```

I want to be able to call this function when the keyboard pops up, but what I don't understand is how to pass through the Activity when I call this function?

Before calling the function to close the keyboard I have the following:

```<code>    // Create object of  DesiredCapabilities class and specify android platform
    DesiredCapabilities capabilities = DesiredCapabilities.android();

    // set the capability to execute test in android app
    capabilities.setCapability(MobileCapabilityType.PLATFORM, Platform.ANDROID);
    capabilities.setCapability(MobileCapabilityType.PLATFORM_NAME, "Android");
    capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "Emulator_1");
    capabilities.setCapability(MobileCapabilityType.VERSION, "8.0");
    capabilities.setCapability("appPackage", "com.spreeza.shop.stag.debug");
    capabilities.setCapability("appActivity", "com.spreeza.shop.ui.features.splash.EntryPointActivity");

    driver = new RemoteWebDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);

// click on the login button
driver.findElement(By.id(identifierName)).click();

// close the keyboard
hideKeyboard();
</code>```

答:
Activity  => activity mean a reference of a Activity object.

Call the method as below .

hideKeyboard(YourActivity.this);

Checkout your Activity name and replace YourActivity with the name .

Body:
I'm new to mobile automation and I've been trying to find a way to close the soft keyboard on Android (using Java). The best solution I've come across so far was from this post:

Close/hide the Android Soft Keyboard

The function that I'm trying to use from there is:

public static void hideKeyboard(Activity activity) {
    InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
    //Find the currently focused view, so we can grab the correct window token from it.
    View view = activity.getCurrentFocus();
    //If no view currently has focus, create a new one, just so we can grab a window token from it
    if (view == null) {
        view = new View(activity);
    }
    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}

I want to be able to call this function when the keyboard pops up, but what I don't understand is how to pass through the Activity when I call this function?

Before calling the function to close the keyboard I have the following:

    // Create object of  DesiredCapabilities class and specify android platform
    DesiredCapabilities capabilities = DesiredCapabilities.android();

    // set the capability to execute test in android app
    capabilities.setCapability(MobileCapabilityType.PLATFORM, Platform.ANDROID);
    capabilities.setCapability(MobileCapabilityType.PLATFORM_NAME, "Android");
    capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "Emulator_1");
    capabilities.setCapability(MobileCapabilityType.VERSION, "8.0");
    capabilities.setCapability("appPackage", "com.spreeza.shop.stag.debug");
    capabilities.setCapability("appActivity", "com.spreeza.shop.ui.features.splash.EntryPointActivity");

    driver = new RemoteWebDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);

// click on the login button
driver.findElement(By.id(identifierName)).click();

// close the keyboard
hideKeyboard();


问:
Is there a Firefox 3 addon similar to View Source Chart?
Before I upgraded to Firefox 3 I used to constantly use the View Source Chart Firefox Addon which shows the source HTML in a very organized, graphical form. Unfortunately, this addon is only for Firefox 2 and the beta version for Firefox 3 now costs $10 on the author's site.

Anyone know of a similar addon that works for Firefox 3?

(of course, I might indeed pay $10 for this, but first want to ask around if there isn't anything better and free, as the version for Firefox 2 had its limitations and I don't really want to pay $10 for something in beta that I can't test out before paying for it.)

答: You could always try Firefug. It sounds like it does a similar thing, plus more :)</p>

OwnerDisplayName: Edward Tanguay

LastEditorDisplayName: Oli

OwnerDisplayName: joshhunt


问:
Take action when an image on a webpage is loaded and seen by the user
I need to take an action (Call a WEB URL) when an image on a webpage is loaded and is seen by the user (image is not hidden in a scrollable area). If the user scrolls down, and the image gets displayed, then we take the same action.

Is this possible? Using AJAX and Javascript focus? Does focus differentiate between (a) images that are loaded and displayed on screen and (b) images that are loaded but not displayed (because they are still down the scrollable page).

Would really appreciate your help.

Thanks

答:
Look into the following properties: document.body.scrollTop, document.body.clientHeight and image.offsetTop.

Doing a quick calculation using those every time the page scrolls (window.onscroll) should let you know if the image is visible or not.


问:
How to Build Curses Program That Supports More Than 223 Columns of Mouse Input
I'm trying to get a curses program working with my terminal spanning my monitor. However, the x coordinate can't move past the 223rd column, instead it loops around. In the source, this seems to be due to them being defined as 8-bits, and having the position values start only after the first 32 values (i.e. x = raw_x - ' ').

Here's an example program from https://gist.github.com/sylt/93d3f7b77e7f3a881603 that demonstrates the issue when compiled with libncurses5. In it, if your cursor moves more than 233 columns to the right of the window, the x value will loop back over to 0 - ' ', i.e. -32

```<code>#include <curses.h>
#include <stdio.h>

int main()
{
  initscr();
  cbreak();
  noecho();

  // Enables keypad mode. This makes (at least for me) mouse events getting
  // reported as KEY_MOUSE, instead as of random letters.
  keypad(stdscr, TRUE);

  // Don't mask any mouse events
  mousemask(ALL_MOUSE_EVENTS | REPORT_MOUSE_POSITION, NULL);

  printf("\033[?1003h\n"); // Makes the terminal report mouse movement events

  for (;;) {
    int c = wgetch(stdscr);

    // Exit the program on new line fed
    if (c == '\n')
      break;

    char buffer[512];
    size_t max_size = sizeof(buffer);
    if (c == ERR) {
      snprintf(buffer, max_size, "Nothing happened.");
    }
    else if (c == KEY_MOUSE) {
      MEVENT event;
      if (getmouse(&event) == OK) {
        snprintf(buffer, max_size, "Mouse at row=%d, column=%d bstate=0x%08lx",
                 event.y, event.x, event.bstate);
      }
      else {
        snprintf(buffer, max_size, "Got bad mouse event.");
      }
    }
    else {
      snprintf(buffer, max_size, "Pressed key %d (%s)", c, keyname(c));
    }

    move(0, 0);
    insertln();
    addstr(buffer);
    clrtoeol();
    move(0, 0);
  }

  printf("\033[?1003l\n"); // Disable mouse movement events, as l = low

  endwin();

  return 0;
}
</code>```

for the curious, you can build this with gcc file.c -lcurses

How do I workaround this? I can use vim in full-screen mode mode, and tmux mouse interactions also work. These both depend on ncurses, so it must be fixed somehow. I tried reading their source for hours and attempting samples of what I thought would work. I've also tried several printf() terminal modes, but none seem to enable this mode. How can I get my mouse event to hold more than 8 bits, and thus let the columns field hold values larger than 232?

答:
That's a terminal-dependent feature (not an ncurses limitation as such).  The original xterm protocol dating from the late 1980s encodes each ordinate in a byte, reserving the first 32 for control characters.  That gives 256 - 32 = 223.

xterm introduced an experimental feature in 2010 to extend the range. There is an ncurses terminal description "xterm-1005" which uses that.  Some criticized that, and xterm introduced an different feature in 2012.  Again, there is a "xterm-1006" using that feature.

The descriptions in ncurses were added in 2014.  ncurses 6 was released in 2015, and still supports (by compile-time options) the ABI 5 for ncurses 5.  If your "ncurses5" is at least as new as the changes in 2014, the library supports SGR 1006 without change.

The reason for not making one of those part of the default "xterm" is that portability across the various xterm imitators is poor (as is their documentation), and that would only increase bug reports.  But if you happen to be using one of the terminals (such as xterm...) which support the SGR 1006 feature, that's supported in the ncurses library.

Body:
I'm trying to get a curses program working with my terminal spanning my monitor. However, the x coordinate can't move past the 223rd column, instead it loops around. In the source, this seems to be due to them being defined as 8-bits, and having the position values start only after the first 32 values (i.e. x = raw_x - ' ').

Here's an example program from https://gist.github.com/sylt/93d3f7b77e7f3a881603 that demonstrates the issue when compiled with libncurses5. In it, if your cursor moves more than 233 columns to the right of the window, the x value will loop back over to 0 - ' ', i.e. -32

#include <curses.h>
#include <stdio.h>

int main()
{
  initscr();
  cbreak();
  noecho();

  // Enables keypad mode. This makes (at least for me) mouse events getting
  // reported as KEY_MOUSE, instead as of random letters.
  keypad(stdscr, TRUE);

  // Don't mask any mouse events
  mousemask(ALL_MOUSE_EVENTS | REPORT_MOUSE_POSITION, NULL);

  printf("\033[?1003h\n"); // Makes the terminal report mouse movement events

  for (;;) {
    int c = wgetch(stdscr);

    // Exit the program on new line fed
    if (c == '\n')
      break;

    char buffer[512];
    size_t max_size = sizeof(buffer);
    if (c == ERR) {
      snprintf(buffer, max_size, "Nothing happened.");
    }
    else if (c == KEY_MOUSE) {
      MEVENT event;
      if (getmouse(&event) == OK) {
        snprintf(buffer, max_size, "Mouse at row=%d, column=%d bstate=0x%08lx",
                 event.y, event.x, event.bstate);
      }
      else {
        snprintf(buffer, max_size, "Got bad mouse event.");
      }
    }
    else {
      snprintf(buffer, max_size, "Pressed key %d (%s)", c, keyname(c));
    }

    move(0, 0);
    insertln();
    addstr(buffer);
    clrtoeol();
    move(0, 0);
  }

  printf("\033[?1003l\n"); // Disable mouse movement events, as l = low

  endwin();

  return 0;
}

for the curious, you can build this with gcc file.c -lcurses

How do I workaround this? I can use vim in full-screen mode mode, and tmux mouse interactions also work. These both depend on ncurses, so it must be fixed somehow. I tried reading their source for hours and attempting samples of what I thought would work. I've also tried several printf() terminal modes, but none seem to enable this mode. How can I get my mouse event to hold more than 8 bits, and thus let the columns field hold values larger than 232?


问:
How to use UI Bootstrap Pagination for a table, generated using ng-repeat
I am trying to keep pagination in my Angular application using uib-pagination. I am unable to get proper way to do this.

HTML

```<code><table id="mytable" class="table table-striped">
  <thead>
    <tr class="table-head">
      <th>Name</th>
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat="person in aCandidates">
      <th>
        <div>{{person}}</div>
      </th>
    </tr>
  </tbody>
</table>
</code>```

Controller

```<code>$scope.totalItems = $scope.aCandidates.length;
$scope.currentPage = 1;
$scope.itemsPerPage = 10;
</code>```

I am able to see the pagination bar but no action is performed with that and the entire table data is rendered even after giving total-items as 10.

How exactly uib-pagination works and how is the data (in this case aCandidates) is linked to pagination.

答:
For newer versions, change to the following code:

```

The <uib-pagination> tag is no longer supported. It has to be given as an attribute.

Body:
I am trying to keep pagination in my Angular application using uib-pagination. I am unable to get proper way to do this.

HTML

      Name

{{person}}

Controller

$scope.totalItems = $scope.aCandidates.length;
$scope.currentPage = 1;
$scope.itemsPerPage = 10;

I am able to see the pagination bar but no action is performed with that and the entire table data is rendered even after giving total-items as 10.

How exactly uib-pagination works and how is the data (in this case aCandidates) is linked to pagination.

Body:
For newer versions, change to the following code:

 <ul uib-pagination total-items="totalItems" ng-model="currentPage" items-per-page="itemsPerPage"></ul>

The <uib-pagination> tag is no longer supported. It has to be given as an attribute.


答: You can call the function from Activity as hideKeyboard(MainActivity.this) and from Fragment as hideKeyboard((Activity)getActivity())

Title: Call function from activity to close the soft keyboard android


问:
unable to hide div in angular js using ng-if
unable to hide div on loading page.
I want to show the div if the value of array is empty.</p>

```<code>    <div ng-hide="loading"  ng-if="users== null || users.length === 0" >
        <h3>No Result Found</h3>
    </div>
</code>```

答:
This may help you - use && or || as per your case here -

```<code><div ng-hide="loading && users.length == 0">
    <h3>No Result Found</h3>
</div>
</code>```

Body:
unable to hide div on loading page.
I want to show the div if the value of array is empty.

No Result Found

Body:
This may help you - use && or || as per your case here -

<div ng-hide="loading && users.length == 0">
    <h3>No Result Found</h3>
</div>


问:
SQL query to find top 2 customers done max amount of transaction( oracle db)
I want to get TOP  2 customers done maximum amount transaction from below the table.I am working on oracle db.

my table transactions:

```<code> tranID       PROD_ID       QTY      PRICE        CID
      1       100            5         10000      1000
      2       103            16        5000       1001
      3       102            8         5000       1003
      4       200            10        9000       1002
      5       204            8        9000         1002
      6       207            4         8000        1002
</code>```

CUSTOMERS

```<code>CID CNAME
1001  X
1002  Y
1003  Z
</code>```

答:
This can be done using the following query. First, you compute sums, then you order it and then you select the first two rows.</p>

```<code>SELECT t.*
FROM
(
  SELECT t.CID, c.name, sum(t.PRICE * t.qty) tsum
  FROM transaction t
  JOIN customer c ON t.CID = c.CID
  GROUP BY t.CID , c.name
  ORDER BY tsum DESC
) t
WHERE rownum < 3
</code>```

Body:
I want to get TOP  2 customers done maximum amount transaction from below the table.I am working on oracle db.

my table transactions:

 tranID       PROD_ID       QTY      PRICE        CID
      1       100            5         10000      1000
      2       103            16        5000       1001
      3       102            8         5000       1003
      4       200            10        9000       1002
      5       204            8        9000         1002
      6       207            4         8000        1002

CUSTOMERS

CID CNAME
1001  X
1002  Y
1003  Z

Body:
This can be done using the following query. First, you compute sums, then you order it and then you select the first two rows.

SELECT t.*
FROM
(
  SELECT t.CID, c.name, sum(t.PRICE * t.qty) tsum
  FROM transaction t
  JOIN customer c ON t.CID = c.CID
  GROUP BY t.CID , c.name
  ORDER BY tsum DESC
) t
WHERE rownum < 3


问:
How to set path to public in Rails 2.2.3 Application
I am trying to get a local instance up of an existing rails application.  It is built on Rails 2.2.3.  I keep getting errors that seem to me like I need to set the path to the public directory.  When I run "scripts/server" and request pages, I get these errors:

ActionController::RoutingError (No route matches "/favicon.ico" with {:method=>:get}):
...

ActionController::RoutingError (No route matches "/stylesheets/cache/xxx.css" with {:method=>:get}):

ActionController::RoutingError (No route matches "/javascripts/cache/xxx.js" with {:method=>:get}):

How do I set the path to public?  Could this have something to do with setting "RAILS_ROOT"?

Thanks

答:
Check that in config/environments/{development,test,production}.rb, serve_static_assets is set to true.  Otherwise, Rails will not serve the assets in /public.

Note that in production, you should likely have Apache or whatever web server you use serve those assets.  Running it through Rails proper is an unnecessary slow down.


问:
In place insertion into list (or array)
I'm running a script in Python, where I need to insert new numbers into an array  (or list) at certain index locations. The problem is that obviously as I insert new numbers, the index locations are invalidated. Is there a clever way to insert the new values at the index locations all at once? Or is the only solution to increment the index number (first value of the pair) as I add?

Sample test code snippets:

```<code>original_list = [0, 1, 2, 3, 4, 5, 6, 7]
insertion_indices = [1, 4, 5]
new_numbers = [8, 9, 10]
pairs = [(insertion_indices[i], new_numbers[i]) for i in range(len(insertion_indices))]

for pair in pairs:
    original_list.insert(pair[0], pair[1])
</code>```

Results in:

```<code>[0, 8, 1, 2, 9, 10, 3, 4, 5, 6, 7]
</code>```

whereas I want:

```<code>[0, 8, 1, 2, 3, 9, 4, 10, 5, 6, 7]
</code>```

答:
Increment the required index by 1 after every insert

```<code>original_list = [0, 1, 2, 3, 4, 5, 6, 7]
insertion_indices = [1, 4, 5]
new_numbers = [8, 9, 10]

for i in range(len(insertion_indices)):
    original_list.insert(insertion_indices[i]+i,new_numbers[i])

print(original_list)
</code>```

Output

```<code>[0, 8, 1, 2, 3, 9, 4, 10, 5, 6, 7]

#Required list
[0, 8, 1, 2, 3, 9, 4, 10, 5, 6, 7]
</code>```

Title: In place insertion into list (or array)

Body:
I'm running a script in Python, where I need to insert new numbers into an array  (or list) at certain index locations. The problem is that obviously as I insert new numbers, the index locations are invalidated. Is there a clever way to insert the new values at the index locations all at once? Or is the only solution to increment the index number (first value of the pair) as I add?

Sample test code snippets:

original_list = [0, 1, 2, 3, 4, 5, 6, 7]
insertion_indices = [1, 4, 5]
new_numbers = [8, 9, 10]
pairs = [(insertion_indices[i], new_numbers[i]) for i in range(len(insertion_indices))]

for pair in pairs:
    original_list.insert(pair[0], pair[1])

Results in:

[0, 8, 1, 2, 9, 10, 3, 4, 5, 6, 7]

whereas I want:

[0, 8, 1, 2, 3, 9, 4, 10, 5, 6, 7]

Body:
Increment the required index by 1 after every insert

original_list = [0, 1, 2, 3, 4, 5, 6, 7]
insertion_indices = [1, 4, 5]
new_numbers = [8, 9, 10]

for i in range(len(insertion_indices)):
    original_list.insert(insertion_indices[i]+i,new_numbers[i])

print(original_list)

Output

[0, 8, 1, 2, 3, 9, 4, 10, 5, 6, 7]

#Required list
[0, 8, 1, 2, 3, 9, 4, 10, 5, 6, 7]


问:
Calculate Percentage Values
My Rapidminer process results are published as follows

```<code>Row No. Count
1   9.0
2   11.0
3   32.0
</code>```

If I want to calculate:
    (9/32)*100 and
    (11/32)*100
from this result set, how would I do it?

答:
the solution is not quite straight forward, as RapidMiner normally treats Examples (rows) as independent of each other.

What you can do is to extract the value needed as a macro and use it in the Generate Attributes Operator.

See the attached sample process for a solution to your particular problem. Just copy and paste the XML below to your process window in RapidMiner.

Also feel free to ask further, or re-post, questions in the RapidMiner community forum.

```<code><?xml version="1.0" encoding="UTF-8"?><process version="7.6.001">
<context>
<input/>
<output/>
<macros/>
</context>
<operator activated="true" class="process" compatibility="7.6.001" expanded="true" name="Process">
<process expanded="true">
  <operator activated="true" class="generate_data_user_specification" compatibility="7.6.001" expanded="true" height="68" name="Generate Data by User Specification" width="90" x="112" y="85">
    <list key="attribute_values">
      <parameter key="Count" value="9"/>
    </list>
    <list key="set_additional_roles"/>
  </operator>
  <operator activated="true" class="generate_data_user_specification" compatibility="7.6.001" expanded="true" height="68" name="Generate Data by User Specification (2)" width="90" x="112" y="187">
    <list key="attribute_values">
      <parameter key="Count" value="11"/>
    </list>
    <list key="set_additional_roles"/>
  </operator>
  <operator activated="true" class="generate_data_user_specification" compatibility="7.6.001" expanded="true" height="68" name="Generate Data by User Specification (3)" width="90" x="112" y="340">
    <list key="attribute_values">
      <parameter key="Count" value="32"/>
    </list>
    <list key="set_additional_roles"/>
  </operator>
  <operator activated="true" class="append" compatibility="7.6.001" expanded="true" height="124" name="Append" width="90" x="380" y="187"/>
  <operator activated="true" class="extract_macro" compatibility="7.6.001" expanded="true" height="68" name="Extract Macro" width="90" x="581" y="187">
    <parameter key="macro" value="divisor"/>
    <parameter key="macro_type" value="data_value"/>
    <parameter key="attribute_name" value="Count"/>
    <parameter key="example_index" value="3"/>
    <list key="additional_macros"/>
    <description align="center" color="green" colored="true" width="126">Extracting the third value as a macro. It can be the called using the %{macro_name} syntax</description>
  </operator>
  <operator activated="true" class="generate_attributes" compatibility="7.6.001" expanded="true" height="82" name="Generate Attributes" width="90" x="782" y="187">
    <list key="function_descriptions">
      <parameter key="Percentage" value="5"/>
    </list>
    <description align="center" color="green" colored="true" width="126">Creating a new Attribute (column) with the desired calculation<br><br>Check the final paragraph of the help text for the &quot;Generate Attribute&quot; Operator for a description of how to work with macros</description>
  </operator>
  <connect from_op="Generate Data by User Specification" from_port="output" to_op="Append" to_port="example set 1"/>
  <connect from_op="Generate Data by User Specification (2)" from_port="output" to_op="Append" to_port="example set 2"/>
  <connect from_op="Generate Data by User Specification (3)" from_port="output" to_op="Append" to_port="example set 3"/>
  <connect from_op="Append" from_port="merged set" to_op="Extract Macro" to_port="example set"/>
  <connect from_op="Extract Macro" from_port="example set" to_op="Generate Attributes" to_port="example set input"/>
  <connect from_op="Generate Attributes" from_port="example set output" to_port="result 1"/>
  <portSpacing port="source_input 1" spacing="0"/>
  <portSpacing port="sink_result 1" spacing="0"/>
  <portSpacing port="sink_result 2" spacing="0"/>
  <description align="center" color="yellow" colored="false" height="581" resized="true" width="444" x="56" y="18">Generating sample data to fit the original problem</description>
</process>
</operator>
</process>
</code>```

Title: Calculate Percentage Values

Body:
My Rapidminer process results are published as follows

Row No. Count
1   9.0
2   11.0
3   32.0

If I want to calculate:
    (9/32)*100 and
    (11/32)*100
from this result set, how would I do it?

Body:
the solution is not quite straight forward, as RapidMiner normally treats Examples (rows) as independent of each other.

What you can do is to extract the value needed as a macro and use it in the Generate Attributes Operator.

See the attached sample process for a solution to your particular problem. Just copy and paste the XML below to your process window in RapidMiner.

Also feel free to ask further, or re-post, questions in the RapidMiner community forum.

<?xml version="1.0" encoding="UTF-8"?><process version="7.6.001">
<context>
<input/>
<output/>
<macros/>
</context>
<operator activated="true" class="process" compatibility="7.6.001" expanded="true" name="Process">
<process expanded="true">
  <operator activated="true" class="generate_data_user_specification" compatibility="7.6.001" expanded="true" height="68" name="Generate Data by User Specification" width="90" x="112" y="85">
    <list key="attribute_values">
      <parameter key="Count" value="9"/>
    </list>
    <list key="set_additional_roles"/>
  </operator>
  <operator activated="true" class="generate_data_user_specification" compatibility="7.6.001" expanded="true" height="68" name="Generate Data by User Specification (2)" width="90" x="112" y="187">
    <list key="attribute_values">
      <parameter key="Count" value="11"/>
    </list>
    <list key="set_additional_roles"/>
  </operator>
  <operator activated="true" class="generate_data_user_specification" compatibility="7.6.001" expanded="true" height="68" name="Generate Data by User Specification (3)" width="90" x="112" y="340">
    <list key="attribute_values">
      <parameter key="Count" value="32"/>
    </list>
    <list key="set_additional_roles"/>
  </operator>
  <operator activated="true" class="append" compatibility="7.6.001" expanded="true" height="124" name="Append" width="90" x="380" y="187"/>
  <operator activated="true" class="extract_macro" compatibility="7.6.001" expanded="true" height="68" name="Extract Macro" width="90" x="581" y="187">
    <parameter key="macro" value="divisor"/>
    <parameter key="macro_type" value="data_value"/>
    <parameter key="attribute_name" value="Count"/>
    <parameter key="example_index" value="3"/>
    <list key="additional_macros"/>
    <description align="center" color="green" colored="true" width="126">Extracting the third value as a macro. It can be the called using the %{macro_name} syntax</description>
  </operator>
  <operator activated="true" class="generate_attributes" compatibility="7.6.001" expanded="true" height="82" name="Generate Attributes" width="90" x="782" y="187">
    <list key="function_descriptions">
      <parameter key="Percentage" value="5"/>
    </list>
    <description align="center" color="green" colored="true" width="126">Creating a new Attribute (column) with the desired calculation&lt;br&gt;&lt;br&gt;Check the final paragraph of the help text for the &amp;quot;Generate Attribute&amp;quot; Operator for a description of how to work with macros</description>
  </operator>
  <connect from_op="Generate Data by User Specification" from_port="output" to_op="Append" to_port="example set 1"/>
  <connect from_op="Generate Data by User Specification (2)" from_port="output" to_op="Append" to_port="example set 2"/>
  <connect from_op="Generate Data by User Specification (3)" from_port="output" to_op="Append" to_port="example set 3"/>
  <connect from_op="Append" from_port="merged set" to_op="Extract Macro" to_port="example set"/>
  <connect from_op="Extract Macro" from_port="example set" to_op="Generate Attributes" to_port="example set input"/>
  <connect from_op="Generate Attributes" from_port="example set output" to_port="result 1"/>
  <portSpacing port="source_input 1" spacing="0"/>
  <portSpacing port="sink_result 1" spacing="0"/>
  <portSpacing port="sink_result 2" spacing="0"/>
  <description align="center" color="yellow" colored="false" height="581" resized="true" width="444" x="56" y="18">Generating sample data to fit the original problem</description>
</process>
</operator>
</process>