问:
QML: Custom draggable point delegate for ChartView series
Is it possible to use custom delegates for draggable points (i.e. Items, icons, Rectangles, etc) in Qt Charts or other 3rd party libraries like it is easily possible in Qt Location for MapItemView, MapQuickItem and their delegate property? Or it is possible to use some combinations of PathView and ChartView for such purpose? PathView inside ChartView could be a solution, however probably will need to convert chart coordinates to screen coordinates there: also not sure ChartView has methods for this. Need to make some mockup to check this. Had not found any documentation or samples about. Should be obvious and simple like it was implemented in Qt Location however it is not implemented for Qt Charts for some reasons.

Ideal way could be Map element using from Qt Location where I have all I need: MapItemView, MapQuickItem and MapPolygon or MapPolyline for graphics as I have cartographic information to draw. But again 2 questions:

how to draw axis: X - distance km, Y - altitude

how to draw chart grid

how to draw custom 2D BarSeries imitating terrain elevation (could be MapPolygon however).

Is it possible to dynamically draw some custom map here? Any ideas?

答:
Found simple and elegant solution with ChartView with Repeater inside and ChartView mapping functions: mapToPosition and mapToValue to map chart<->screen coordinates easily.

Mockup:

```<code>import QtQuick 2.12
import QtCharts 2.3

Item {
    visible: true
    width: 640
    height: 480

    ChartView {
        id: chart
        anchors.fill: parent
        antialiasing: true

        ValueAxis {
            id: xAxis
            min: 0
            max: 1100
            tickCount: 12
            labelFormat: "%.0f"
        }

        ValueAxis {
            id: yAxis
            min: -50
            max: 200
            tickInterval: 50
            labelFormat: "%.0f"
        }

        ListModel {
            id: lineModel
            ListElement { x: 50; y: 155; }
            ListElement { x: 138; y: 175 }
            ListElement { x: 193; y: 50 }
            ListElement { x: 271; y: 90 }
            ListElement { x: 295; y: 90 }
            ListElement { x: 383; y: 150 }
            ListElement { x: 529; y: 100 }
            ListElement { x: 665; y: 150 }
            ListElement { x: 768; y: 90 }
            ListElement { x: 794; y: 90 }
            ListElement { x: 851; y: 50 }
            ListElement { x: 875; y: 50 }
            ListElement { x: 925; y: 175 }
            ListElement { x: 1060; y: 125 }
        }

        ListModel {
            id: areaModel
            ListElement { x: 0; y: 100 }
            ListElement { x: 138; y: 125 }
            ListElement { x: 193; y: 0 }
            ListElement { x: 271; y: 40 }
            ListElement { x: 295; y: 40 }
            ListElement { x: 383; y: 100 }
            ListElement { x: 529; y: 50 }
            ListElement { x: 665; y: 100 }
            ListElement { x: 768; y: 40 }
            ListElement { x: 794; y: 40 }
            ListElement { x: 851; y: 0 }
            ListElement { x: 875; y: 0 }
            ListElement { x: 925; y: 125 }
            ListElement { x: 1060; y: 75 }
            ListElement { x: 1100; y: 60 }
        }

        AreaSeries {
            name: "Terrain"
            axisX: xAxis
            axisY: yAxis
            borderColor: color
            upperSeries: LineSeries {
                id: areaSeries
            }
        }

        LineSeries {
            id: lineSeries
            name: "Flying path"
            axisX: xAxis
            axisY: yAxis
        }

        function adjustPosition(item, index) {
            let point = Qt.point(lineModel.get(index).x, lineModel.get(index).y)
            let position = chart.mapToPosition(point, lineSeries)
            item.x = position.x - item.width / 2
            item.y = position.y - item.height / 2
        }

        function adjustValue(item, index) {
            let position = Qt.point(item.x + item.width / 2, item.y + item.height / 2)
            let point = chart.mapToValue(position, lineSeries)
            lineModel.setProperty(index, "y", point.y)  // Change only Y-coordinate
            lineSeries.replace(lineSeries.at(index).x, lineSeries.at(index).y, // old
                               lineSeries.at(index).x, point.y)                // new
        }

        Repeater {
            model: lineModel

            Rectangle {
                id: indicator
                radius: 100
                width: radius / 2
                height: width
                color: "red"

                property real parentWidth: chart.width
                property real parentHeight: chart.height

                onParentWidthChanged: chart.adjustPosition(this, index)
                onParentHeightChanged: chart.adjustPosition(this, index)

                onYChanged: {
                    if(mouseArea.drag.active) {
                        chart.adjustValue(this, index)
                    }
                }

                Image {
                    id: waypoint
                    anchors.centerIn: parent
                    source: index ? "qrc:/waypoint.svg" : "qrc:/home.svg"
                }

                MouseArea {
                    id: mouseArea
                    anchors.fill: parent
                    drag.target: indicator
                    drag.axis: Drag.YAxis
                    preventStealing: true
                }
            }
        }

        Component.onCompleted: {
            lineSeries.clear()
            areaSeries.clear()
            for(let i = 0; i < lineModel.count; i++) {
                lineSeries.append(lineModel.get(i).x, lineModel.get(i).y)
            }

            for(let j = 0; j < areaModel.count; j++) {
                areaSeries.append(areaModel.get(j).x, areaModel.get(j).y)
            }
        }
    }
}
</code>```

Any improvements, optimizations and suggestion like model binding via HXYModelMapper/VXYModelMapper instead of JS model filling are welcome. Will fix the answer.

Result screenshot:

Body:
Found simple and elegant solution with ChartView with Repeater inside and ChartView mapping functions: mapToPosition and mapToValue to map chart<->screen coordinates easily.

Mockup:

import QtQuick 2.12
import QtCharts 2.3

Item {
    visible: true
    width: 640
    height: 480

    ChartView {
        id: chart
        anchors.fill: parent
        antialiasing: true

        ValueAxis {
            id: xAxis
            min: 0
            max: 1100
            tickCount: 12
            labelFormat: "%.0f"
        }

        ValueAxis {
            id: yAxis
            min: -50
            max: 200
            tickInterval: 50
            labelFormat: "%.0f"
        }

        ListModel {
            id: lineModel
            ListElement { x: 50; y: 155; }
            ListElement { x: 138; y: 175 }
            ListElement { x: 193; y: 50 }
            ListElement { x: 271; y: 90 }
            ListElement { x: 295; y: 90 }
            ListElement { x: 383; y: 150 }
            ListElement { x: 529; y: 100 }
            ListElement { x: 665; y: 150 }
            ListElement { x: 768; y: 90 }
            ListElement { x: 794; y: 90 }
            ListElement { x: 851; y: 50 }
            ListElement { x: 875; y: 50 }
            ListElement { x: 925; y: 175 }
            ListElement { x: 1060; y: 125 }
        }

        ListModel {
            id: areaModel
            ListElement { x: 0; y: 100 }
            ListElement { x: 138; y: 125 }
            ListElement { x: 193; y: 0 }
            ListElement { x: 271; y: 40 }
            ListElement { x: 295; y: 40 }
            ListElement { x: 383; y: 100 }
            ListElement { x: 529; y: 50 }
            ListElement { x: 665; y: 100 }
            ListElement { x: 768; y: 40 }
            ListElement { x: 794; y: 40 }
            ListElement { x: 851; y: 0 }
            ListElement { x: 875; y: 0 }
            ListElement { x: 925; y: 125 }
            ListElement { x: 1060; y: 75 }
            ListElement { x: 1100; y: 60 }
        }

        AreaSeries {
            name: "Terrain"
            axisX: xAxis
            axisY: yAxis
            borderColor: color
            upperSeries: LineSeries {
                id: areaSeries
            }
        }

        LineSeries {
            id: lineSeries
            name: "Flying path"
            axisX: xAxis
            axisY: yAxis
        }

        function adjustPosition(item, index) {
            let point = Qt.point(lineModel.get(index).x, lineModel.get(index).y)
            let position = chart.mapToPosition(point, lineSeries)
            item.x = position.x - item.width / 2
            item.y = position.y - item.height / 2
        }

        function adjustValue(item, index) {
            let position = Qt.point(item.x + item.width / 2, item.y + item.height / 2)
            let point = chart.mapToValue(position, lineSeries)
            lineModel.setProperty(index, "y", point.y)  // Change only Y-coordinate
            lineSeries.replace(lineSeries.at(index).x, lineSeries.at(index).y, // old
                               lineSeries.at(index).x, point.y)                // new
        }

        Repeater {
            model: lineModel

            Rectangle {
                id: indicator
                radius: 100
                width: radius / 2
                height: width
                color: "red"

                property real parentWidth: chart.width
                property real parentHeight: chart.height

                onParentWidthChanged: chart.adjustPosition(this, index)
                onParentHeightChanged: chart.adjustPosition(this, index)

                onYChanged: {
                    if(mouseArea.drag.active) {
                        chart.adjustValue(this, index)
                    }
                }

                Image {
                    id: waypoint
                    anchors.centerIn: parent
                    source: index ? "qrc:/waypoint.svg" : "qrc:/home.svg"
                }

                MouseArea {
                    id: mouseArea
                    anchors.fill: parent
                    drag.target: indicator
                    drag.axis: Drag.YAxis
                    preventStealing: true
                }
            }
        }

        Component.onCompleted: {
            lineSeries.clear()
            areaSeries.clear()
            for(let i = 0; i < lineModel.count; i++) {
                lineSeries.append(lineModel.get(i).x, lineModel.get(i).y)
            }

            for(let j = 0; j < areaModel.count; j++) {
                areaSeries.append(areaModel.get(j).x, areaModel.get(j).y)
            }
        }
    }
}

Any improvements, optimizations and suggestion like model binding via HXYModelMapper/VXYModelMapper instead of JS model filling are welcome. Will fix the answer.

Result screenshot:


来源: stackexchange

问:
How do I remove the vertical line that arises from plotting discontinuous data?
I have spent a tiresome amount of time trying to figure out, how to remove the vertical line arising when plotting discontinuous data. In my case I'm trying to plot some data, which diverges towards infinity at a given point. I'm using Python 3.6 with matplotlib's pyplot package.

This code produces the same unpleasant flaw:

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

x = np.arange(100) * 0.09
y = 1 / (x - 5)

plt.figure(1)
plt.plot(x,y)
plt.show
</code>```

Is there anything I can do to remove that line? What is it, I'm not seeing?

Right now, it feels like I've exhausted my options. I've examined the documentation for matplotlib.pyplot.plot and matplotlib.pyplot.scatter and I am unable to fix this problem, even though it feels like this should be an insanely simple operation (I remember once dealing with this in Maple or MatLab or something similar - there you simply set the argument discont=True to accomplish this).

Any help would be very much appreciated.

答:
Your data is not discontinuous. You have created a single vector (y) and are asking to plot the entire vector. You can plot individual portions of any vector as long as the size of that vector matches the size of the (x) vector, or create separate vectors.

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

x = np.arange(100) * 0.09
y = 1 / (x - 5)

plt.figure(1)
plt.plot(x[:50],y[:50])
plt.plot(x[60:],y[60:])
plt.show()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have spent a tiresome amount of time trying to figure out, how to remove the vertical line arising when plotting discontinuous data. In my case I'm trying to plot some data, which diverges towards infinity at a given point. I'm using Python 3.6 with matplotlib's pyplot package.

This code produces the same unpleasant flaw:

import matplotlib.pyplot as plt

x = np.arange(100) * 0.09
y = 1 / (x - 5)

plt.figure(1)
plt.plot(x,y)
plt.show

Is there anything I can do to remove that line? What is it, I'm not seeing?

Right now, it feels like I've exhausted my options. I've examined the documentation for matplotlib.pyplot.plot and matplotlib.pyplot.scatter and I am unable to fix this problem, even though it feels like this should be an insanely simple operation (I remember once dealing with this in Maple or MatLab or something similar - there you simply set the argument discont=True to accomplish this).

Any help would be very much appreciated.

Body:
Your data is not discontinuous. You have created a single vector (y) and are asking to plot the entire vector. You can plot individual portions of any vector as long as the size of that vector matches the size of the (x) vector, or create separate vectors.

import matplotlib.pyplot as plt

x = np.arange(100) * 0.09
y = 1 / (x - 5)

plt.figure(1)
plt.plot(x[:50],y[:50])
plt.plot(x[60:],y[60:])
plt.show()


问:
Parsing Time from text using SAS
I have a maximum of 200 characters length of text for thousands of records which has date and time in it. I am trying to parse out the time

Here is the example of the text that I have

```<code> Your account your account your account on  Jan 10, 2020 at 8.30 AM ET your account
 Your account your account your account on  Jan 3, 2020 6.30PM ET your account
 Your account your account your account on  Jan 11, 2020 at 6.30PM ET your account
</code>```

Desired output

```<code>   8.30 AM
   6.30PM
   6.30PM
</code>```

In all the content ET is common and I am using index and substr function to parse out the time.

```<code>   Time=substr(Text,index(Text,' on ')+19,6);
</code>```

For the second line, I am also getting extra characters since there is no at and no space between time and PM

Is there any efficient way to parse the time?

Thanks

答:
SAS can locate a text excerpt using a Perl regular expression that has a capture buffer.

```<code>data want(keep=parsed_timestring);
length parsed_timestring $8;
input;

  /* Pattern:
   *   On a word boundary     \b
   *   Capture start          (
   *     1 or 2 digits        \d{1,2}
   *     A period             \.
   *     1 or 2 digits        \d{1,2}
   *     0 or 1 spaces        \s?
   *     letter A or P        (A|P)
   *     letter M             M
   *   Capture end            )
   */

  prx = prxparse('/\b(\d{1,2}\.\d{1,2}\s?(A|P)M)/x');

  if prxmatch (prx, _infile_) then
    parsed_timestring = prxposn(prx,1,_infile_);

datalines;
Your account your account your account on  Jan 10, 2020 at 8.30 AM ET your account
 Your account your account your account on  Jan 3, 2020 6.30PM ET your account
 Your account your account your account on  Jan 11, 2020 at 6.30PM ET your account
 Your account your account your account on  Jan 11, 2020 at 6666.30PM ET your account
;

proc print;
run;
</code>```

In the last row parsed_timestring is blank because 6666.30PM starts with more than two digits on a word boundary and thus would not match the pattern and thus the line would not have a proper time string.

Title: Parsing Time from text using SAS

Body:
I have a maximum of 200 characters length of text for thousands of records which has date and time in it. I am trying to parse out the time

Here is the example of the text that I have

 Your account your account your account on  Jan 10, 2020 at 8.30 AM ET your account
 Your account your account your account on  Jan 3, 2020 6.30PM ET your account
 Your account your account your account on  Jan 11, 2020 at 6.30PM ET your account

Desired output

   8.30 AM
   6.30PM
   6.30PM

In all the content ET is common and I am using index and substr function to parse out the time.

   Time=substr(Text,index(Text,' on ')+19,6);

For the second line, I am also getting extra characters since there is no at and no space between time and PM

Is there any efficient way to parse the time?

Thanks

Body:
SAS can locate a text excerpt using a Perl regular expression that has a capture buffer.

data want(keep=parsed_timestring);
length parsed_timestring $8;
input;

  /* Pattern:
   *   On a word boundary     \b
   *   Capture start          (
   *     1 or 2 digits        \d{1,2}
   *     A period             \.
   *     1 or 2 digits        \d{1,2}
   *     0 or 1 spaces        \s?
   *     letter A or P        (A|P)
   *     letter M             M
   *   Capture end            )
   */

  prx = prxparse('/\b(\d{1,2}\.\d{1,2}\s?(A|P)M)/x');

  if prxmatch (prx, _infile_) then
    parsed_timestring = prxposn(prx,1,_infile_);

datalines;
Your account your account your account on  Jan 10, 2020 at 8.30 AM ET your account
 Your account your account your account on  Jan 3, 2020 6.30PM ET your account
 Your account your account your account on  Jan 11, 2020 at 6.30PM ET your account
 Your account your account your account on  Jan 11, 2020 at 6666.30PM ET your account
;

proc print;
run;

In the last row parsed_timestring is blank because 6666.30PM starts with more than two digits on a word boundary and thus would not match the pattern and thus the line would not have a proper time string.


问:
How to limit the return angle from atan2() to [-pi/4,pi/4]?
I am using atan2() to find the angle between x,y values. I understand atan2 method returns a numeric value between –pi and pi. How do I map that value to [-pi/4, pi/4]. The question is related to this Limiting atan2 to specific angle ranges but I couldn't understand it well.</p>

```<code>if (a > pi/4):
  a -= 2 * pi/4
  return a
elif(a <= -pi/4):
  a += 2 * pi/4
return a
</code>```

答:
If you want to scale the angle down, just divide it:

```<code>return a/4
</code>```

If you want to limit it to a certain range, use min and max

```<code>return max(-pi/4, min(pi/4, a))
</code>```

Body:
I am using atan2() to find the angle between x,y values. I understand atan2 method returns a numeric value between –pi and pi. How do I map that value to [-pi/4, pi/4]. The question is related to this Limiting atan2 to specific angle ranges but I couldn't understand it well.

if (a > pi/4):
  a -= 2 * pi/4
  return a
elif(a <= -pi/4):
  a += 2 * pi/4
return a

Body:
If you want to scale the angle down, just divide it:

return a/4

If you want to limit it to a certain range, use min and max

return max(-pi/4, min(pi/4, a))


问:
understanding parts of this Sudoku solver
I have a question about the following code snippet.  This is from a sudoku solver I found on youtube.  It uses a recursive backtracking algorithm to solve.  I'm just trying to learn from this, but I'm stuck on some parts.
The following snippet is a boolean to check if a number is in a 3x3 box, this is used later in the solve() method.

```<code>// we check if a possible number is in its 3x3 box
private boolean isInBox(int row, int col, int number) {
    int r = row - row % 3;
    int c = col - col % 3;

    for (int i = r; i < r + 3; i++)
        for (int j = c; j < c + 3; j++)
            if (board[i][j] == number)
                return true;

    return false;
}
</code>```

I just don't understand how this works.  What does row - row % 3 do?  And then in the for loop i < r + 3 confuses me too.  I understand the rows and column checkers, those are easy, but the logic here is escaping me.

答:
row and col can be any value from 0 to 8. They define a location within the 9x9 sudoku game.

The loops need to check the specific 3x3 box that the location row,col is contained within.

int r = row - row % 3; finds the index of the first row in that same 3x3 box.

int c = col - col % 3; finds the index of the first column in that same 3x3 box.

Both convert the input value to output as:

```<code>0 -> 0
1 -> 0
2 -> 0
3 -> 3
4 -> 3
5 -> 3
6 -> 6
7 -> 6
8 -> 6
</code>```

The loop then checks every location from r,c up to r+2,c+2 (inclusive), looking for the specified value number.

Body:
I have a question about the following code snippet.  This is from a sudoku solver I found on youtube.  It uses a recursive backtracking algorithm to solve.  I'm just trying to learn from this, but I'm stuck on some parts.
The following snippet is a boolean to check if a number is in a 3x3 box, this is used later in the solve() method.

// we check if a possible number is in its 3x3 box
private boolean isInBox(int row, int col, int number) {
    int r = row - row % 3;
    int c = col - col % 3;

    for (int i = r; i < r + 3; i++)
        for (int j = c; j < c + 3; j++)
            if (board[i][j] == number)
                return true;

    return false;
}

I just don't understand how this works.  What does row - row % 3 do?  And then in the for loop i < r + 3 confuses me too.  I understand the rows and column checkers, those are easy, but the logic here is escaping me.

Body:
row and col can be any value from 0 to 8. They define a location within the 9x9 sudoku game.

The loops need to check the specific 3x3 box that the location row,col is contained within.

int r = row - row % 3; finds the index of the first row in that same 3x3 box.

int c = col - col % 3; finds the index of the first column in that same 3x3 box.

Both convert the input value to output as:

0 -> 0
1 -> 0
2 -> 0
3 -> 3
4 -> 3
5 -> 3
6 -> 6
7 -> 6
8 -> 6

The loop then checks every location from r,c up to r+2,c+2 (inclusive), looking for the specified value number.


问:
How to make django reload server without change any code after few hours?
I have develop a django apps, and i start the server by using python manage.py runserver. without stop the server and without edit any code I wish it reload the server after 24 hoursy, any ideas on this?</p>

答:
You can use Cron for this.

From Wikipedia:

```<code># ┌───────────── minute (0 - 59)
# │ ┌───────────── hour (0 - 23)
# │ │ ┌───────────── day of the month (1 - 31)
# │ │ │ ┌───────────── month (1 - 12)
# │ │ │ │ ┌───────────── day of the week (0 - 6) (Sunday to Saturday;
# │ │ │ │ │                                   7 is also Sunday on some systems)
# │ │ │ │ │
# │ │ │ │ │
# * * * * * command to execute
</code>```

Body:
You can use Cron for this.

From Wikipedia:

# ┌───────────── minute (0 - 59)
# │ ┌───────────── hour (0 - 23)
# │ │ ┌───────────── day of the month (1 - 31)
# │ │ │ ┌───────────── month (1 - 12)
# │ │ │ │ ┌───────────── day of the week (0 - 6) (Sunday to Saturday;
# │ │ │ │ │                                   7 is also Sunday on some systems)
# │ │ │ │ │
# │ │ │ │ │
# * * * * * command to execute


问:
Replace multiple strings in a column of a data frame
I've been trying to replace multiple strings in a column of a data frame in R using str_replace_all.

Currently I've written up something simple for now (below)

```<code>mydata$Final_Result <- str_replace_all(mydata$Final_Result, 'Absent', 'A')
mydata$Final_Result <- str_replace_all(mydata$Final_Result, 'Present', 'P')
</code>```

I have other strings to replace in the same column. So I am looking for a more elegant way to write this code in a single line.

Would appreciate if anyone could advise on how this can be done.

答:
You could use case_when from the dplyr package:

```<code>mydata$Final_Result <- case_when(
    mydata$Final_Result == "Absent" ~ "A",
    mydata$Final_Result == "Present" ~ "P",
    TRUE ~ NA
)
</code>```

case_when has one potential advantage over str_replace_all in that it allows for a default catch all replacement.

Body:
I've been trying to replace multiple strings in a column of a data frame in R using str_replace_all.

Currently I've written up something simple for now (below)

mydata$Final_Result <- str_replace_all(mydata$Final_Result, 'Absent', 'A')
mydata$Final_Result <- str_replace_all(mydata$Final_Result, 'Present', 'P')

I have other strings to replace in the same column. So I am looking for a more elegant way to write this code in a single line.

Would appreciate if anyone could advise on how this can be done.

Body:
You could use case_when from the dplyr package:

mydata$Final_Result <- case_when(
    mydata$Final_Result == "Absent" ~ "A",
    mydata$Final_Result == "Present" ~ "P",
    TRUE ~ NA
)

case_when has one potential advantage over str_replace_all in that it allows for a default catch all replacement.


问:
How do I format my output in Java for this specific instance to add spaces?
Here is what I'm trying to accomplish. When you enter numbers in this format

```<code>1 2 2 3 3 4 4 5 6
</code>```

you get

```<code>1 1 2 2 3 2 4 2 5 1 6 1
</code>```

In other words it tells you how many of each string you have. The problem is I can't figure out how to get there to be spaces in between the output. This is the code:

import java.util.Scanner;

public class RunLengthEncoding {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter a sequence of integers separated by spaces:");
        String input = scan.nextLine();
        System.out.println("Input: " + input);
        String c = " ";

        char ch = 0;
        int count = 1;

        for (int x = 0; x < input.length(); x++)
            if (input.charAt(x) != ' ') {
                if (ch == input.charAt(x)) {
                    count = count + 1;

                } else {
                    c = c + ch;
                    if (count != 1) {
                        c = c + count;
                    }

                    ch = input.charAt(x);
                    count = 1;
                }
            }

        c = c + ch;

        if (count != 1) {
            c = c + count;
        }

        System.out.println("encoder output:");
        System.out.println(c);
        System.out.println("\t");
    }
}
```

答:
I am using StringBuilder to build my output.  I am also using another variable to keep track of the last iteration's char to determine if I should keep counting or if I should move on to displaying counts.

This is my take on it:

import java.util.Scanner;

public class RunLengthEncoding  {
    private final static String BLANK_SPACE = " ";

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter a sequence of integers separated by spaces:");
        String input = scan.nextLine();
        System.out.println("Input: " + input);
        StringBuilder outputString = new StringBuilder();

        char ch = 0;
        int count = 1;
        char lastChar = 0;

        for (int x = 0; x < input.length(); x++) {
            // get first input in array
            ch = input.charAt(x);

            // if this is the first item we have fetched, there is no count yet - move on to the next input
            if( x == 0 ){
                lastChar = ch;
                continue;
            }

            if (ch != ' ') {
                if (ch == lastChar) {
                    count++;

                } else {
                    outputString.append(lastChar);
                    outputString.append(RunLengthEncoding.BLANK_SPACE);
                    outputString.append(count);
                    outputString.append(RunLengthEncoding.BLANK_SPACE);
                    count = 1;
                }
                lastChar = ch;
            }
        }
        outputString.append(lastChar);
        outputString.append(RunLengthEncoding.BLANK_SPACE);
        outputString.append(count);

        System.out.print("Encoder output: ");
        System.out.println(outputString);
    }
}
```

It produces this output:

Enter a sequence of integers separated by spaces:1  2 2 3 3 4 5 5 6 6
  6 7

Input: 1  2 2 3 3 4 5 5 6 6 6 7

Encoder output: 1 1 2 2 3 2 4 1 5
  2 6 3 7 1

Body:
Here is what I'm trying to accomplish. When you enter numbers in this format

1 2 2 3 3 4 4 5 6

you get

1 1 2 2 3 2 4 2 5 1 6 1

In other words it tells you how many of each string you have. The problem is I can't figure out how to get there to be spaces in between the output. This is the code:

import java.util.Scanner;

public class RunLengthEncoding {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter a sequence of integers separated by spaces:");
        String input = scan.nextLine();
        System.out.println("Input: " + input);
        String c = " ";

        char ch = 0;
        int count = 1;

        for (int x = 0; x < input.length(); x++)
            if (input.charAt(x) != ' ') {
                if (ch == input.charAt(x)) {
                    count = count + 1;

                } else {
                    c = c + ch;
                    if (count != 1) {
                        c = c + count;
                    }

                    ch = input.charAt(x);
                    count = 1;
                }
            }

        c = c + ch;

        if (count != 1) {
            c = c + count;
        }

        System.out.println("encoder output:");
        System.out.println(c);
        System.out.println("\t");
    }
}

Body:
I am using StringBuilder to build my output.  I am also using another variable to keep track of the last iteration's char to determine if I should keep counting or if I should move on to displaying counts.

This is my take on it:

import java.util.Scanner;

public class RunLengthEncoding  {
    private final static String BLANK_SPACE = " ";

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter a sequence of integers separated by spaces:");
        String input = scan.nextLine();
        System.out.println("Input: " + input);
        StringBuilder outputString = new StringBuilder();

        char ch = 0;
        int count = 1;
        char lastChar = 0;

        for (int x = 0; x < input.length(); x++) {
            // get first input in array
            ch = input.charAt(x);

            // if this is the first item we have fetched, there is no count yet - move on to the next input
            if( x == 0 ){
                lastChar = ch;
                continue;
            }

            if (ch != ' ') {
                if (ch == lastChar) {
                    count++;

                } else {
                    outputString.append(lastChar);
                    outputString.append(RunLengthEncoding.BLANK_SPACE);
                    outputString.append(count);
                    outputString.append(RunLengthEncoding.BLANK_SPACE);
                    count = 1;
                }
                lastChar = ch;
            }
        }
        outputString.append(lastChar);
        outputString.append(RunLengthEncoding.BLANK_SPACE);
        outputString.append(count);

        System.out.print("Encoder output: ");
        System.out.println(outputString);
    }
}

It produces this output:

Enter a sequence of integers separated by spaces:1  2 2 3 3 4 5 5 6 6
  6 7

Input: 1  2 2 3 3 4 5 5 6 6 6 7

Encoder output: 1 1 2 2 3 2 4 1 5
  2 6 3 7 1


问:
fatal error C1083: Cannot open include file: 'CL/cl.h'
I read all the solutions provided in this website in order to solve this problem, but it still exits.
When I run this command in cmd in windows 10 C:\pyopencl-2016.2.1>setup.py install, this error will be shown:

```<code>c:\pyopencl-2016.2.1\src\c_wrapper\clinfo_ext.h(10) : fatal error C1083:

Cannot open include file: 'CL/cl.h': No such file or directory
error: command 'C:\\Users\\Neda\\AppData\\Local\\Programs\\Common\\Microsoft\\Visual C++ for Python\\9.0\\VC\\Bin\\amd64\\cl.exe' failed with exit status 2
</code>```

Also, there is no cl.exe and CL/ in the paths mentioned above.
I would really appreciate your attention.

EDITED:
I also ran this command in cmd Command "pip install --global-option=build_ext --global-option="-DHAVE_GL=1" pyopencl and the problem was the same:

```<code>c:\users\neda\appdata\local\temp\pip-build-ugbqq9\pyopencl\src\c_wrapper\clinfo_ext.h(10) : fatal error C1083: Cannot open include file: 'CL/cl.h': No such file or directory
error: command '

C:\\Users\\Neda\\AppData\\Local\\Programs\\Common\\Microsoft\\Visual C++ for Python\\9.0\\VC\\Bin\\amd64\\cl.exe' failed with exit status 2

    ----------------------------------------
Command "c:\users\neda\appdata\local\enthought\canopy\user\python.exe -u -c "import setuptools, tokenize;__file__='c:\\users\\neda\\appdata\\local\\temp\\pip-build-ugbqq9\\pyopencl\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" build_ext -DHAVE_GL=1 install --record c:\users\neda\appdata\local\temp\pip-l6bnzf-record\install-record.txt --single-version-externally-managed --compile --install-headers c:\users\neda\appdata\local\enthought\canopy\user\include\site\python2.7\pyopencl" failed with error code 1 in c:\users\neda\appdata\local\temp\pip-build-ugbqq9\pyopencl\
</code>```

答:
I have successfully installed pyopencl on a Windows 10 AMD machine.
For other Windows AMD users, read on.

The AMD APP SDK is now discontinued by AMD, however the last release version you can find on Github. I recommend you install it from here.

Next, you will need to specify a few command line flags to pass onto the compiler when building. I used:

```<code>pip3 install --global-option=build_ext --global-option="-Ic:\Program Files (x86)\OCL_SDK_Light\include" --global-option="-Lc:\Program Files (x86)\OCL_SDK_Light\lib\x86_64" pyopencl
</code>```

This worked for me, you may have to adjust your -I and -L arguments according to where the OCL SDK installed to.

ContentLicense: CC BY-SA 3.0

Body:
I read all the solutions provided in this website in order to solve this problem, but it still exits.
When I run this command in cmd in windows 10 C:\pyopencl-2016.2.1>setup.py install, this error will be shown:

c:\pyopencl-2016.2.1\src\c_wrapper\clinfo_ext.h(10) : fatal error C1083:

Cannot open include file: 'CL/cl.h': No such file or directory
error: command 'C:\\Users\\Neda\\AppData\\Local\\Programs\\Common\\Microsoft\\Visual C++ for Python\\9.0\\VC\\Bin\\amd64\\cl.exe' failed with exit status 2

Also, there is no cl.exe and CL/ in the paths mentioned above.
I would really appreciate your attention.

EDITED:
I also ran this command in cmd Command "pip install --global-option=build_ext --global-option="-DHAVE_GL=1" pyopencl and the problem was the same:

c:\users\neda\appdata\local\temp\pip-build-ugbqq9\pyopencl\src\c_wrapper\clinfo_ext.h(10) : fatal error C1083: Cannot open include file: 'CL/cl.h': No such file or directory
error: command '

C:\\Users\\Neda\\AppData\\Local\\Programs\\Common\\Microsoft\\Visual C++ for Python\\9.0\\VC\\Bin\\amd64\\cl.exe' failed with exit status 2

    ----------------------------------------
Command "c:\users\neda\appdata\local\enthought\canopy\user\python.exe -u -c "import setuptools, tokenize;__file__='c:\\users\\neda\\appdata\\local\\temp\\pip-build-ugbqq9\\pyopencl\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" build_ext -DHAVE_GL=1 install --record c:\users\neda\appdata\local\temp\pip-l6bnzf-record\install-record.txt --single-version-externally-managed --compile --install-headers c:\users\neda\appdata\local\enthought\canopy\user\include\site\python2.7\pyopencl" failed with error code 1 in c:\users\neda\appdata\local\temp\pip-build-ugbqq9\pyopencl\

Body:
I have successfully installed pyopencl on a Windows 10 AMD machine.
For other Windows AMD users, read on.

The AMD APP SDK is now discontinued by AMD, however the last release version you can find on Github. I recommend you install it from here.

Next, you will need to specify a few command line flags to pass onto the compiler when building. I used:

pip3 install --global-option=build_ext --global-option="-Ic:\Program Files (x86)\OCL_SDK_Light\include" --global-option="-Lc:\Program Files (x86)\OCL_SDK_Light\lib\x86_64" pyopencl

This worked for me, you may have to adjust your -I and -L arguments according to where the OCL SDK installed to.


问:
Output parsed JSON to template in lift
Using Lift's json parser, how can I output parsed json objects into a template?

The datatypes that net.liftweb.json.JsonParser provides are not
standard lists.

```<code>package rem.lift_client
package snippet
import net.liftweb._

import util._
import Helpers._
import net.liftweb.json.JsonParser._

class SearchResults {

  def render() = {
    val json_raw = "[ {\"userName\":\"John\"}, {\"userName\":\"Michael\"} ]"
    val json_parsed = parse(input)
    "li *" #> json_parsed.toString <---- NOT CORRECT
   }
 }
</code>```

In the above example, I wanted to output a list of users as:

John

Michael

How do I interpret the parsed object? Any ideas are welcome, thanks.

NOTE: In addition to the accepted answer, lift-json has an excellent documentation on this subject.

答:
One way is to extract the data with case classes.</p>

```<code>implicit val formats = DefaultFormats
case class User(userName: String)
json_parsed.extract[List[User]]
</code>```

Title: Output parsed JSON to template in lift

Body:
Using Lift's json parser, how can I output parsed json objects into a template?

The datatypes that net.liftweb.json.JsonParser provides are not
standard lists.

package rem.lift_client
package snippet
import net.liftweb._

import util._
import Helpers._
import net.liftweb.json.JsonParser._

class SearchResults {

  def render() = {
    val json_raw = "[ {\"userName\":\"John\"}, {\"userName\":\"Michael\"} ]"
    val json_parsed = parse(input)
    "li *" #> json_parsed.toString <---- NOT CORRECT
   }
 }

In the above example, I wanted to output a list of users as:

John

Michael

How do I interpret the parsed object? Any ideas are welcome, thanks.

NOTE: In addition to the accepted answer, lift-json has an excellent documentation on this subject.

Body:
One way is to extract the data with case classes.

implicit val formats = DefaultFormats
case class User(userName: String)
json_parsed.extract[List[User]]


问:
How to replace createAppContainer with NavigationContainer? (using compatibility layer module)
I am trying to migrate from v4 to v5, and they've removed createAppContainer and are saying to use NavigationContainer in its place.

I'm using the createCompatNavigatorFactory stuff from the compatibility layer docs.

Before, I'd pass my main navigator to createAppContainer, and then use that component to wrap my entire app.

Now the docs say to simply use NavigationContainer, but they don't say anything about how to apply this to people using the compatibility layer.

It's confusing. My code use to look like this:

```<code>const MainNavigator = createStackNavigator(...)
const AppNavigator = createAppNavigator(MainNavigator)
</code>```

and in App.js

```<code>render() {
   <View>
    <AppNavigator ref={navigationRef} />
  </View>
}
</code>```

Now I've switched to the following:

```<code> const MainNavigator = createCompatNavigatorFactory(createStackNavigator)(...)
</code>```

and in App.js

```<code>render() {
   <View>
    <NavigationContainer ref={navigationRef} />
  </View>
}
</code>```

I'm wondering how you connect the navigationContainer to the stuff made by the compat navigator factory function. I'm wondering why there's nothing about this in the docs...

答:
render() {
  return (
    <NavigationContainer ref={navigationRef}>
      <MainNavigator />
    </NavigationContainer>
  );
}
```

https://reactnavigation.org/docs/en/getting-started.html

Body:
I am trying to migrate from v4 to v5, and they've removed createAppContainer and are saying to use NavigationContainer in its place.

I'm using the createCompatNavigatorFactory stuff from the compatibility layer docs.

Before, I'd pass my main navigator to createAppContainer, and then use that component to wrap my entire app.

Now the docs say to simply use NavigationContainer, but they don't say anything about how to apply this to people using the compatibility layer.

It's confusing. My code use to look like this:

const MainNavigator = createStackNavigator(...)
const AppNavigator = createAppNavigator(MainNavigator)

and in App.js

render() {
   <View>
    <AppNavigator ref={navigationRef} />
  </View>
}

Now I've switched to the following:

 const MainNavigator = createCompatNavigatorFactory(createStackNavigator)(...)

and in App.js

render() {
   <View>
    <NavigationContainer ref={navigationRef} />
  </View>
}

I'm wondering how you connect the navigationContainer to the stuff made by the compat navigator factory function. I'm wondering why there's nothing about this in the docs...

Body:
render() {
  return (
    <NavigationContainer ref={navigationRef}>
      <MainNavigator />
    </NavigationContainer>
  );
}

https://reactnavigation.org/docs/en/getting-started.html


问:
The python used by Jupyter and local machine are in different place
I am new to Jupyter, and I found I can not import module on it. I found the answer said because the Python my Jupyter using is different from the Python my local machine using.
This is the output when I run sys.executable on Jupyter:

```<code>import sys
sys.executable
'/usr/local/Cellar/jupyterlab/1.2.4/libexec/bin/python3.7'
</code>```

This is the output on my local machine's terminal

```<code>import sys
>>> sys.executable
'/System/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python'
</code>```

I have no idea how to fix it, I want to use Jupyter. Any advice may be helpful.

Thank you.

答:
I fixed this issue by install Anaconda on my machine, and open the Anaconda app, launch Jupyter. At this time the environment is

```<code>'/Users/saber/opt/anaconda3/bin/python'
</code>```

I think maybe there are 3 versions of Python in my laptop, but I have no idea how to delete them, just keep all of them (hope they do not kill my poor storage 128G).

Reference: Anaconda tutorial
Install Anaconda on Mac

Body:
I am new to Jupyter, and I found I can not import module on it. I found the answer said because the Python my Jupyter using is different from the Python my local machine using.
This is the output when I run sys.executable on Jupyter:

import sys
sys.executable
'/usr/local/Cellar/jupyterlab/1.2.4/libexec/bin/python3.7'

This is the output on my local machine's terminal

import sys
>>> sys.executable
'/System/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python'

I have no idea how to fix it, I want to use Jupyter. Any advice may be helpful.

Thank you.

Body:
I fixed this issue by install Anaconda on my machine, and open the Anaconda app, launch Jupyter. At this time the environment is

'/Users/saber/opt/anaconda3/bin/python'

I think maybe there are 3 versions of Python in my laptop, but I have no idea how to delete them, just keep all of them (hope they do not kill my poor storage 128G).

Reference: Anaconda tutorial
Install Anaconda on Mac


问:
My embed code doesn't work on some sites (Failed to load resource: net::ERR_CONNECTION_REFUSED)
I am using the following embed code below an infographic on my site (to allow people to easily share the image):

```
</div>
</div>
</p>

<p>I have got 15 <code>embeds</code> to that image till now and I see that 4 of the sites which are using the <code>code</code> aren't able to show the image on their sites. It just appears broken.</p>

<p>At first, I thought that it might be the issue of <code>hotlink</code> protection, but that should mean that the <code>embed</code> code shouldn't work on all the 15 sites and the infographic shouldn't load on all.</p>

<p>I had a look at the console of those particular sites and I found this error codes marked near my embed code:</p>

```Failed to load resource: net::ERR_CONNECTION_REFUSED
```

I did my homework and tried searching online for a solution but the responses were not exactly helping me. I request you guys to help me with this and I really appreciate your time and effort.

I am using Google Chrome, if that matters.

Regards.

答:
Working on SSL.

```<code><iframe width="250" height="260" frameborder="0" marginwidth="0" marginheight="0"src="/redirect.php?url=https://dns/files.aspx" scrolling="auto">[Your browser does not support frames or is currently configured not to display frames. Please use an up-to-date browser that is capable of displaying frames.]</iframe>enter code here
</code>```

redirect.php

```<code><?php
$homepage = file_get_contents('https://dns/files.aspx');
echo $homepage;
?>
</code>```

Body:
I am using the following embed code below an infographic on my site (to allow people to easily share the image):

I have got 15 embeds to that image till now and I see that 4 of the sites which are using the code aren't able to show the image on their sites. It just appears broken.

At first, I thought that it might be the issue of hotlink protection, but that should mean that the embed code shouldn't work on all the 15 sites and the infographic shouldn't load on all.

I had a look at the console of those particular sites and I found this error codes marked near my embed code:

Failed to load resource: net::ERR_CONNECTION_REFUSED

I did my homework and tried searching online for a solution but the responses were not exactly helping me. I request you guys to help me with this and I really appreciate your time and effort.

I am using Google Chrome, if that matters.

Regards.

Body:
Working on SSL.

<iframe width="250" height="260" frameborder="0" marginwidth="0" marginheight="0"src="/redirect.php?url=https://dns/files.aspx" scrolling="auto">[Your browser does not support frames or is currently configured not to display frames. Please use an up-to-date browser that is capable of displaying frames.]</iframe>enter code here

redirect.php

<?php
$homepage = file_get_contents('https://dns/files.aspx');
echo $homepage;
?>


问:
In python, headings not in the same row
I extracted three columns from a larger data frame (recent_grads) as follows...

```<code>df = recent_grads.groupby('Major_category')['Men', 'Women'].sum()
</code>```

However, when I print df, it comes up as follows...

```<code>                                         Men    Women
Major_category
Agriculture & Natural Resources      40357.0    35263.0
Arts                                134390.0    222740.0
Biology & Life Science              184919.0    268943.0
Business                            667852.0    634524.0
Communications & Journalism         131921.0    260680.0
Computers & Mathematics             208725.0    90283.0
Education                           103526.0    455603.0
Engineering                         408307.0    129276.0
Health                               75517.0    387713.0
Humanities & Liberal Arts           272846.0    440622.0
Industrial Arts & Consumer Services 103781.0    126011.0
Interdisciplinary                     2817.0    9479.0
Law & Public Policy                  91129.0    87978.0
Physical Sciences                    95390.0    90089.0
Psychology & Social Work             98115.0    382892.0
Social Science                       256834.0   273132.0
</code>```

How do I get Major_category heading in the same row as Men and Women headings? I tried to put the three columns in a new data frame as follows...

```<code>df1 = df[['Major_category', 'Men', 'Women']].copy()
</code>```

This gives me an error (Major_category not in index)

答:
Hi man you should try reset_index https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.reset_index.html:</p>

```<code>df = df.groupby('Major_category')['Men', 'Women'].sum()
# Print the output.
md = df.reset_index()
print(md)
</code>```

Title: In python, headings not in the same row

Body:
I extracted three columns from a larger data frame (recent_grads) as follows...

df = recent_grads.groupby('Major_category')['Men', 'Women'].sum()

However, when I print df, it comes up as follows...

                                         Men    Women
Major_category
Agriculture & Natural Resources      40357.0    35263.0
Arts                                134390.0    222740.0
Biology & Life Science              184919.0    268943.0
Business                            667852.0    634524.0
Communications & Journalism         131921.0    260680.0
Computers & Mathematics             208725.0    90283.0
Education                           103526.0    455603.0
Engineering                         408307.0    129276.0
Health                               75517.0    387713.0
Humanities & Liberal Arts           272846.0    440622.0
Industrial Arts & Consumer Services 103781.0    126011.0
Interdisciplinary                     2817.0    9479.0
Law & Public Policy                  91129.0    87978.0
Physical Sciences                    95390.0    90089.0
Psychology & Social Work             98115.0    382892.0
Social Science                       256834.0   273132.0

How do I get Major_category heading in the same row as Men and Women headings? I tried to put the three columns in a new data frame as follows...

df1 = df[['Major_category', 'Men', 'Women']].copy()

This gives me an error (Major_category not in index)

Body:
Hi man you should try reset_index https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.reset_index.html:

df = df.groupby('Major_category')['Men', 'Women'].sum()
# Print the output.
md = df.reset_index()
print(md)


问:
Redis backend in online using django
I have create chat app, in offline it works fine, but when i deploy it online i receive this error

note: i have already install the redis without issue, this is my settings.py
this is production.py which is my another settings.py

```<code>CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "channels_redis.core.RedisChannelLayer",
        "CONFIG": {
            "hosts": [os.environ.get('REDIS_URL', 'redis://localhost:6379')],
        },
        # "symmetric_encryption_keys": [SECRET_KEY],
    },
}
</code>```

and this my settings.py

```<code>CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "channels_redis.core.RedisChannelLayer",
        "CONFIG": {
            "hosts": [("127.0.0.1", 6379)],
        },
    },
}
</code>```

note my site is live

this is my referrence https://github.com/codingforentrepreneurs/ChatXChannels

UPDATE

when i run to ubuntu

$ redis-server

$ ps aux | grep redis-server

i still get this error

答:
it sounds like your pre-existing Django server is handing your request rather than channels accepting the request.

I think your issue is in how you are running your server in production.

when running channels in production you have 2 choices.

1) Run all requests through Channels (even those being handled by your normal Django views)

2) Run both your normal server instance and your channels server instance (on different local ports) with some path based reverse proxy in-front of them (such as Nginx) that routs requests to the respective local port.

Regardless of the option you select you should be running channels in production using this Guide https://channels.readthedocs.io/en/latest/deploying.html#run-protocol-servers (not python manager.py).

if you select option 1) then remember that when you run this you need it to run on the same port configuration as your old Django server used to run.

if you go with option 2) you should ensure that all of your traffic is first hitting your reverse proxy (Nginx) server. Then you can run Daphne on a different port and set up the routing in Nginx to proxy pass to the respective server instance depending on the path.

Title: Redis backend in online using django

Body:
I have create chat app, in offline it works fine, but when i deploy it online i receive this error

note: i have already install the redis without issue, this is my settings.py
this is production.py which is my another settings.py

CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "channels_redis.core.RedisChannelLayer",
        "CONFIG": {
            "hosts": [os.environ.get('REDIS_URL', 'redis://localhost:6379')],
        },
        # "symmetric_encryption_keys": [SECRET_KEY],
    },
}

and this my settings.py

CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "channels_redis.core.RedisChannelLayer",
        "CONFIG": {
            "hosts": [("127.0.0.1", 6379)],
        },
    },
}

note my site is live

this is my referrence https://github.com/codingforentrepreneurs/ChatXChannels

UPDATE

when i run to ubuntu

$ redis-server

$ ps aux | grep redis-server

i still get this error


问:
R: locating files that their names contain a specific string from a directory and match to my list of wanted files
It's me the newbie again with another messy file and folder situation(thanks to us biologiests): I got this directory containing a huge amount of .txt files (~900,000+), all the files have been previously handed with inconsistent naming format :(

For example, messy files in directory look like these:

```<code>ctrl_S978765_uns_dummy_00_none.txt
ctrl_S978765_3S_Cookie_00_none.txt
S59607_3S_goody_3M_V10.txt
ctrlnuc30-100_S3245678_DMSO_00_none.txt
ctrlRAP_S0846567_3S_Dex_none.txt
S6498432_2S_Fulra_30mM_V100.txt
.....
</code>```

As you see the naming has no reliable consistency. What's important for me is the ID code embedded in them, such as S978765. Now I have got a list (100 ID codes) of these ID codes that I want.

The CSV file containing the list as below, mind you the list does have repetitive ID codes in the row due to different CLnumber value in the second columns:

```<code>ID code  CLnumber
S978765  1
S978765  2
S306223  1
S897458  1
S514486  2
....
</code>```

So I want to achieve below task: find all the messy named files using the code IDs by matching to my list. And copy them into a new directory.

I have thought of use list.files() to get all the .txt files and their names, then I got stuck at the next step at matching the code ID names, I know how to do it with one string, say "S978765", but if I do it one by one, this is almost just like manual digging the folder.

How could I feed the ID code names in column1 as a list and compare/match them with the messy file title names in the directory and then copy them into a new folder?

Many thanks,
ML

答:
You could use regex to extract the ID codes from the file name.

Here, I have used the pattern "S" followed by 5 or more numbers. Once we extract the ID_codes, we can compare them with the ones which we have in csv.

Assuming the csv is called df and the column name is ID_Codes we can use %in% to filter them.

We can then use file.copy to move files from one folder to another folder.

```<code>all_files <- list.files(path = '/Path/To/Folder', full.names = TRUE)
selected_files <- all_files[sub('.*(S\\d{5,}).*', '\\1', basename(all_files))
                                 %in% unique(df$ID_Codes)]
file.copy(selected_files, 'new_path/for/files')
</code>```

Body:
It's me the newbie again with another messy file and folder situation(thanks to us biologiests): I got this directory containing a huge amount of .txt files (~900,000+), all the files have been previously handed with inconsistent naming format :(

For example, messy files in directory look like these:

ctrl_S978765_uns_dummy_00_none.txt
ctrl_S978765_3S_Cookie_00_none.txt
S59607_3S_goody_3M_V10.txt
ctrlnuc30-100_S3245678_DMSO_00_none.txt
ctrlRAP_S0846567_3S_Dex_none.txt
S6498432_2S_Fulra_30mM_V100.txt
.....

As you see the naming has no reliable consistency. What's important for me is the ID code embedded in them, such as S978765. Now I have got a list (100 ID codes) of these ID codes that I want.

The CSV file containing the list as below, mind you the list does have repetitive ID codes in the row due to different CLnumber value in the second columns:

ID code  CLnumber
S978765  1
S978765  2
S306223  1
S897458  1
S514486  2
....

So I want to achieve below task: find all the messy named files using the code IDs by matching to my list. And copy them into a new directory.

I have thought of use list.files() to get all the .txt files and their names, then I got stuck at the next step at matching the code ID names, I know how to do it with one string, say "S978765", but if I do it one by one, this is almost just like manual digging the folder.

How could I feed the ID code names in column1 as a list and compare/match them with the messy file title names in the directory and then copy them into a new folder?

Many thanks,
ML

Body:
You could use regex to extract the ID codes from the file name.

Here, I have used the pattern "S" followed by 5 or more numbers. Once we extract the ID_codes, we can compare them with the ones which we have in csv.

Assuming the csv is called df and the column name is ID_Codes we can use %in% to filter them.

We can then use file.copy to move files from one folder to another folder.

all_files <- list.files(path = '/Path/To/Folder', full.names = TRUE)
selected_files <- all_files[sub('.*(S\\d{5,}).*', '\\1', basename(all_files))
                                 %in% unique(df$ID_Codes)]
file.copy(selected_files, 'new_path/for/files')


问:
Control other app over gui from my program
I would like to write a simple C++ program for Linux (Ubuntu) to control other GUI programs. For example, to be able to read text labels and put text into entry boxes of other programs written using gtkmm. I have looked at X11 but I don't seem to find any relevant information or examples.

Thank you very much for any information.

答: There is a Java Robot class that was designed for this purpose. It can generate mouse & keyboard events etcetera. There is a good documentation and a lot of examples. For example - Introduction to the Java Robot class in Java. Unfortunately, it is Java. You can use X11 API directly, but that is usually too hard.</p>


答:
You can do the following to add as many pattern-replacement pairs as you want in one line. </p>

```<code>library(stringr)

vec <- c("Absent", "Absent", "Present", "Present", "XX", "YY", "ZZ")

str_replace_all(vec, c("Absent" = "A", "Present" = "P"))
# [1] "A"  "A"  "P"  "P"  "XX" "YY" "ZZ"
</code>```

Title: Replace multiple strings in a column of a data frame

Body:
I've been trying to replace multiple strings in a column of a data frame in R using str_replace_all.

Currently I've written up something simple for now (below)

mydata$Final_Result <- str_replace_all(mydata$Final_Result, 'Absent', 'A')
mydata$Final_Result <- str_replace_all(mydata$Final_Result, 'Present', 'P')

I have other strings to replace in the same column. So I am looking for a more elegant way to write this code in a single line.

Would appreciate if anyone could advise on how this can be done.

Body:
You can do the following to add as many pattern-replacement pairs as you want in one line.

library(stringr)

vec <- c("Absent", "Absent", "Present", "Present", "XX", "YY", "ZZ")

str_replace_all(vec, c("Absent" = "A", "Present" = "P"))
# [1] "A"  "A"  "P"  "P"  "XX" "YY" "ZZ"


问:
Angular - Prevent click event on disabled buttons
I'm trying to prevent click event on disabled buttons, in other words, prevent some user who removes the disabled attribute to call some action.

For now, I have the following code to do this:

<button [disabled]="someCondition" (click)="executeAction()">Execute action</button>
```

```executeAction(): void {
  if (this.someCondition) return;

  // ...
}
```

<p>Works, but it isn't a good solution as I have to do it for ALL buttons in my app (and believe me, it's easy to forgot to do this and even a <em>Linter</em> can't help me here).</p>

<p>Looking for a more robust solution, I thought that <code>directive</code> could help me:</p>

```import { Directive, HostListener, Input, Renderer2, ElementRef } from '@angular/core';

@Directive({
  selector: 'button'
})
export class ButtonDirective {
  @Input() set disabled(value: boolean) {
    this._disabled = value != null;
    this.renderer2.setAttribute(this.elementRef.nativeElement, 'disabled', `${this._disabled}`);
  }

  private _disabled: boolean;

  constructor(
    private readonly elementRef: ElementRef,
    private readonly renderer2: Renderer2
  ) { }

  @HostListener('click', ['$event'])
  onClick(mouseEvent: MouseEvent) {
    // nothing here does what I'm expecting
    if (this._disabled) {
      mouseEvent.preventDefault();
      mouseEvent.stopImmediatePropagation();
      mouseEvent.stopPropagation();

      return false; // just for test
    }
  }
}
```

<pre class="lang-html prettyprint-override"><code><button [disabled]="someCondition" (click)="executeAction()">Execute action</button>
</code>```

```<code>executeAction(): void {
  console.log('still being called');
}
</code>```

...however it does absolutely nothing. It doesn't prevent the click event. Is there any solution that I don't have to control the action itself in its call?

STACKBLITZ

答:
Prevent click event on disabled buttons

If the disabled attribute is there the click will not happen.

When user decides to use devtools

However if the user edits the HTML and removes the disabled attribute manually, then click will happen. You can try and do the check as you have suggested, but the browser is an unsafe environment. The user will still be able to execute any code on the webpages behalf irrespective of any frontend checks you might put in.

Body:
I'm trying to prevent click event on disabled buttons, in other words, prevent some user who removes the disabled attribute to call some action.

For now, I have the following code to do this:

<button [disabled]="someCondition" (click)="executeAction()">Execute action</button>

executeAction(): void {
  if (this.someCondition) return;

  // ...
}

Works, but it isn't a good solution as I have to do it for ALL buttons in my app (and believe me, it's easy to forgot to do this and even a Linter can't help me here).

Looking for a more robust solution, I thought that directive could help me:

import { Directive, HostListener, Input, Renderer2, ElementRef } from '@angular/core';

@Directive({
  selector: 'button'
})
export class ButtonDirective {
  @Input() set disabled(value: boolean) {
    this._disabled = value != null;
    this.renderer2.setAttribute(this.elementRef.nativeElement, 'disabled', `${this._disabled}`);
  }

  private _disabled: boolean;

  constructor(
    private readonly elementRef: ElementRef,
    private readonly renderer2: Renderer2
  ) { }

  @HostListener('click', ['$event'])
  onClick(mouseEvent: MouseEvent) {
    // nothing here does what I'm expecting
    if (this._disabled) {
      mouseEvent.preventDefault();
      mouseEvent.stopImmediatePropagation();
      mouseEvent.stopPropagation();

      return false; // just for test
    }
  }
}

<button [disabled]="someCondition" (click)="executeAction()">Execute action</button>

executeAction(): void {
  console.log('still being called');
}

...however it does absolutely nothing. It doesn't prevent the click event. Is there any solution that I don't have to control the action itself in its call?

STACKBLITZ


问:
Can one form a view into diagonal of ndarray in numpy
Simple slices form views into the parent array. The strides of the view is generically the multiple of the strides of the parent array.

Given 2d parent array with strides (s0, s1), the 1D array with strides (s0+s1) gives the view in the diagonal of the parent array.

Is there a way to create such a view in top-level Python/numpy? Thank you in advance.

答:
For a version that works on more than 2 dimensions:

import numpy as np

def diagonal_view(array, axis1=0, axis2=1):
    """Return a view of the array diagonal."""
    assert array.ndim >= 2
    axis1, axis2 = min([axis1, axis2]), max([axis1, axis2])
    shape = list(array.shape)
    new = min([shape[axis1], shape[axis2]])
    shape.pop(axis1)
    shape.pop(axis2 - 1)
    shape.append(new)
    strides = list(array.strides)
    new = strides[axis1] + strides[axis2]
    strides.pop(axis1)
    strides.pop(axis2 - 1)
    strides.append(new)
    diag = np.lib.stride_tricks.as_strided(array, shape=shape, strides=strides)
    return diag

def test_diagonal_view():
    # test correspondence with np.diagonal
    for array in [
            np.random.randn(10, 4),
            np.random.randn(10, 4).T,
            np.random.randn(10, 4, 8),
            np.random.randn(10, 4, 8).T,
            np.random.randn(10, 4, 8).swapaxes(0, 1),
            np.random.randn(3, 4, 8, 5),
            np.random.randn(3, 4, 8, 5).swapaxes(0, 2),
    ]:
        for axis1 in range(array.ndim):
            for axis2 in range(array.ndim):
                if axis1 != axis2:
                    result = diagonal_view(array, axis1=axis1, axis2=axis2)
                    # compare with np.diagonal
                    reference = np.diagonal(array, axis1=axis1, axis2=axis2)
                    np.testing.assert_array_equal(result, reference)
                    # test that this is a modifiable view
                    result += 1
                    reference = np.diagonal(array, axis1=axis1, axis2=axis2)
                    np.testing.assert_array_equal(result, reference)

test_diagonal_view()
```


问:
D3 -- Nested piechart not displaying all wedges
I've been having a bunch of trouble with a pie chart I've been trying to make. I finally have the outer ring working, but the inner ring only displays a few of the pieces (out ring has 3, inner ring has 6 but displays 3).

Does anyone know what might be wrong with this code? Both systems work fine on their own, but for whatever reason they don't work when I put them together.

The wedges for 20, 10 and 5 are the ones that don't display, and it happens that way every single time.

The name of the class ("arc") doesn't seem to matter, either.

```<code>function makeDonut(svg) {
  var boundingBox = d3.select(svg).node().getBoundingClientRect();
  var h = boundingBox.height;
  var w = boundingBox.width;

  /*****   donut chart  *****/

  var data = [25, 40, 55];
  // arbitrary data

  var outerRadius = w/3;
  var innerRadius = 3*(outerRadius/4);
  var arc = d3.arc()
    .innerRadius(innerRadius)
    .outerRadius(outerRadius);

  var pie = d3.pie();

  // order: gold, silver, bronze
  var color = d3.scaleOrdinal()
    .range(['#e5ce0c', '#e5e4e0', '#a4610a']);

  var arcs = d3.select(svg).selectAll("g.arc")
    .data(pie(data))
    .enter()
    .append("g")
    .attr("class", "arc")
    .attr("transform", "translate(" + (w/2) + "," + ((h-25)/2) + ")");

  arcs.append("path")
  .attr("fill", function(d, i) {
    return color(i);
  })
  .attr("d", arc)
  .attr("stroke", "white")
  .style("stroke-width", "0.5px")
  .on('mouseover', function(d) {
    d3.select(this).attr('opacity', .7);

  })
  .on('mouseleave', function(d) {
    d3.select(this).attr('opacity', 1);
  });

  arcs.append("text")
    .attr("transform", function(d) {
      return "translate(" + arc.centroid(d) + ")";
    })
    .attr("text-anchor", "middle")
    .text(function(d) {
      return d.value;
    });

    /************ piechart ************/

    var dataset = [ 5, 10, 20, 45, 6, 25 ];
    // arbitrary dataset

    var outerRadius2 = 0.75 * (w/3);
    var innerRadius2 = 0;

    var arc2 = d3.arc()
      .innerRadius(innerRadius2)
      .outerRadius(outerRadius2);

    var pie2 = d3.pie();

    var color2 = d3.scaleOrdinal(d3.schemeCategory10);

    var arcs2 = d3.select(svg).selectAll("g.arc")
      .data(pie2(dataset))
      .enter()
      .append("g")
      .attr("class", "arc")
      .attr("transform", "translate(" + (w/2) + "," + ((h-25)/2) + ")");

    //Draw arc paths
    arcs2.append("path")
      .attr("fill", function(d, i) {
        return color2(i);
      })
      .attr("d", arc2);

    arcs2.append("text")
      .attr("transform", function(d) {
        return "translate(" + arc2.centroid(d) + ")";
      })
      .attr("text-anchor", "middle")
      .text(function(d) {
        return d.value;
      });
}
</code>```

答:
The D3 enter method creates elements in the DOM where needed so that for every item in the data array there is an appropriate element in the DOM.

For your donut chart, which you draw first, you selectAll("g.arc") - there are no g elements with the class arc, you have an empty selection. So when you use the enter method, D3 creates one element for every item in the data array. Everything chained to .enter(), without a .merge() method, only affects these entered elements.

For your pie chart, which you draw second, you selectAll("g.arc") - however, now there are three g elements with the class arc. So when you use the enter method here, the enter selection does not included elements for the first three items in the data array: they already exist. Instead these first three elements are included in the update selection.

This functionality is core to the D3 enter/update/exit cycle.

If you want to enter everything, and aren't updating or exiting data points, then you can simply use .selectAll(null) which will create an empty selection, for which an enter selection will create an element for every item in the data array.

If you wanted to modify these wedges/arcs later, you could differentiate the two, either by entering them in different g elements (eg: g1.selectAll("g.arc") and g2.selectAll("g.arc"). Alternatively, you could give them different class names based on whether pie or donut, as below:

var svg = d3.select("svg");
  var boundingBox = svg.node().getBoundingClientRect();
  var h = boundingBox.height;
  var w = boundingBox.width;

  /*****   donut chart  *****/

  var data = [25, 40, 55];
  // arbitrary data

  var outerRadius = w/3;
  var innerRadius = 3*(outerRadius/4);
  var arc = d3.arc()
    .innerRadius(innerRadius)
    .outerRadius(outerRadius);

  var pie = d3.pie();

  // order: gold, silver, bronze
  var color = d3.scaleOrdinal()
    .range(['#e5ce0c', '#e5e4e0', '#a4610a']);

  var arcs = svg.selectAll("donut")
    .data(pie(data))
    .enter()
    .append("g")
    .attr("class", "donut")
    .attr("transform", "translate(" + (w/2) + "," + ((h-25)/2) + ")");

  arcs.append("path")
  .attr("fill", function(d, i) {
    return color(i);
  })
  .attr("d", arc)
  .attr("stroke", "white")
  .style("stroke-width", "0.5px")
  .on('mouseover', function(d) {
    d3.select(this).attr('opacity', .7);

  })
  .on('mouseleave', function(d) {
    d3.select(this).attr('opacity', 1);
  });

  arcs.append("text")
    .attr("transform", function(d) {
      return "translate(" + arc.centroid(d) + ")";
    })
    .attr("text-anchor", "middle")
    .text(function(d) {
      return d.value;
    });

    /************ piechart ************/

    var dataset = [ 5, 10, 20, 45, 6, 25 ];
    // arbitrary dataset

    var outerRadius2 = 0.75 * (w/3);
    var innerRadius2 = 0;

    var arc2 = d3.arc()
      .innerRadius(innerRadius2)
      .outerRadius(outerRadius2);

    var pie2 = d3.pie();

    var color2 = d3.scaleOrdinal(d3.schemeCategory10);

    var arcs2 = svg.selectAll(".pie")
      .data(pie2(dataset))
      .enter()
      .append("g")
      .attr("class", "pie")
      .attr("transform", "translate(" + (w/2) + "," + ((h-25)/2) + ")");

    //Draw arc paths
    arcs2.append("path")
      .attr("fill", function(d, i) {
        return color2(i);
      })
      .attr("d", arc2);

    arcs2.append("text")
      .attr("transform", function(d) {
        return "translate(" + arc2.centroid(d) + ")";
      })
      .attr("text-anchor", "middle")
      .text(function(d) {
        return d.value;
      });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg width=500 height=400></svg></code>```

Body:
I've been having a bunch of trouble with a pie chart I've been trying to make. I finally have the outer ring working, but the inner ring only displays a few of the pieces (out ring has 3, inner ring has 6 but displays 3).

Does anyone know what might be wrong with this code? Both systems work fine on their own, but for whatever reason they don't work when I put them together.

The wedges for 20, 10 and 5 are the ones that don't display, and it happens that way every single time.

The name of the class ("arc") doesn't seem to matter, either.

function makeDonut(svg) {
  var boundingBox = d3.select(svg).node().getBoundingClientRect();
  var h = boundingBox.height;
  var w = boundingBox.width;

  /*****   donut chart  *****/

  var data = [25, 40, 55];
  // arbitrary data

  var outerRadius = w/3;
  var innerRadius = 3*(outerRadius/4);
  var arc = d3.arc()
    .innerRadius(innerRadius)
    .outerRadius(outerRadius);

  var pie = d3.pie();

  // order: gold, silver, bronze
  var color = d3.scaleOrdinal()
    .range(['#e5ce0c', '#e5e4e0', '#a4610a']);

  var arcs = d3.select(svg).selectAll("g.arc")
    .data(pie(data))
    .enter()
    .append("g")
    .attr("class", "arc")
    .attr("transform", "translate(" + (w/2) + "," + ((h-25)/2) + ")");

  arcs.append("path")
  .attr("fill", function(d, i) {
    return color(i);
  })
  .attr("d", arc)
  .attr("stroke", "white")
  .style("stroke-width", "0.5px")
  .on('mouseover', function(d) {
    d3.select(this).attr('opacity', .7);

  })
  .on('mouseleave', function(d) {
    d3.select(this).attr('opacity', 1);
  });

  arcs.append("text")
    .attr("transform", function(d) {
      return "translate(" + arc.centroid(d) + ")";
    })
    .attr("text-anchor", "middle")
    .text(function(d) {
      return d.value;
    });

    /************ piechart ************/

    var dataset = [ 5, 10, 20, 45, 6, 25 ];
    // arbitrary dataset

    var outerRadius2 = 0.75 * (w/3);
    var innerRadius2 = 0;

    var arc2 = d3.arc()
      .innerRadius(innerRadius2)
      .outerRadius(outerRadius2);

    var pie2 = d3.pie();

    var color2 = d3.scaleOrdinal(d3.schemeCategory10);

    var arcs2 = d3.select(svg).selectAll("g.arc")
      .data(pie2(dataset))
      .enter()
      .append("g")
      .attr("class", "arc")
      .attr("transform", "translate(" + (w/2) + "," + ((h-25)/2) + ")");

    //Draw arc paths
    arcs2.append("path")
      .attr("fill", function(d, i) {
        return color2(i);
      })
      .attr("d", arc2);

    arcs2.append("text")
      .attr("transform", function(d) {
        return "translate(" + arc2.centroid(d) + ")";
      })
      .attr("text-anchor", "middle")
      .text(function(d) {
        return d.value;
      });
}

Body:
The D3 enter method creates elements in the DOM where needed so that for every item in the data array there is an appropriate element in the DOM.

For your donut chart, which you draw first, you selectAll("g.arc") - there are no g elements with the class arc, you have an empty selection. So when you use the enter method, D3 creates one element for every item in the data array. Everything chained to .enter(), without a .merge() method, only affects these entered elements.

For your pie chart, which you draw second, you selectAll("g.arc") - however, now there are three g elements with the class arc. So when you use the enter method here, the enter selection does not included elements for the first three items in the data array: they already exist. Instead these first three elements are included in the update selection.

This functionality is core to the D3 enter/update/exit cycle.

If you want to enter everything, and aren't updating or exiting data points, then you can simply use .selectAll(null) which will create an empty selection, for which an enter selection will create an element for every item in the data array.

If you wanted to modify these wedges/arcs later, you could differentiate the two, either by entering them in different g elements (eg: g1.selectAll("g.arc") and g2.selectAll("g.arc"). Alternatively, you could give them different class names based on whether pie or donut, as below:

var svg = d3.select("svg");
  var boundingBox = svg.node().getBoundingClientRect();
  var h = boundingBox.height;
  var w = boundingBox.width;

  /*****   donut chart  *****/

  var data = [25, 40, 55];
  // arbitrary data

  var outerRadius = w/3;
  var innerRadius = 3*(outerRadius/4);
  var arc = d3.arc()
    .innerRadius(innerRadius)
    .outerRadius(outerRadius);

  var pie = d3.pie();

  // order: gold, silver, bronze
  var color = d3.scaleOrdinal()
    .range(['#e5ce0c', '#e5e4e0', '#a4610a']);

  var arcs = svg.selectAll("donut")
    .data(pie(data))
    .enter()
    .append("g")
    .attr("class", "donut")
    .attr("transform", "translate(" + (w/2) + "," + ((h-25)/2) + ")");

  arcs.append("path")
  .attr("fill", function(d, i) {
    return color(i);
  })
  .attr("d", arc)
  .attr("stroke", "white")
  .style("stroke-width", "0.5px")
  .on('mouseover', function(d) {
    d3.select(this).attr('opacity', .7);

  })
  .on('mouseleave', function(d) {
    d3.select(this).attr('opacity', 1);
  });

  arcs.append("text")
    .attr("transform", function(d) {
      return "translate(" + arc.centroid(d) + ")";
    })
    .attr("text-anchor", "middle")
    .text(function(d) {
      return d.value;
    });

    /************ piechart ************/

    var dataset = [ 5, 10, 20, 45, 6, 25 ];
    // arbitrary dataset

    var outerRadius2 = 0.75 * (w/3);
    var innerRadius2 = 0;

    var arc2 = d3.arc()
      .innerRadius(innerRadius2)
      .outerRadius(outerRadius2);

    var pie2 = d3.pie();

    var color2 = d3.scaleOrdinal(d3.schemeCategory10);

    var arcs2 = svg.selectAll(".pie")
      .data(pie2(dataset))
      .enter()
      .append("g")
      .attr("class", "pie")
      .attr("transform", "translate(" + (w/2) + "," + ((h-25)/2) + ")");

    //Draw arc paths
    arcs2.append("path")
      .attr("fill", function(d, i) {
        return color2(i);
      })
      .attr("d", arc2);

    arcs2.append("text")
      .attr("transform", function(d) {
        return "translate(" + arc2.centroid(d) + ")";
      })
      .attr("text-anchor", "middle")
      .text(function(d) {
        return d.value;
      });

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg width=500 height=400></svg>


问:
What is the relation between stateful and stateless widgets in Flutter?
A stateful widget is defined as any widget which changes its state within its lifetime. But it is a very common practice for a StatelessWidget to have a StatefulWidget as one of its children. Doesn't StatelessWidget become stateful if it has StatefulWidget as one of its children?

I tried looking into the documentation as part of the code of StatelessWidget, but couldn't figure out how a StatelessWidget can have Statefulwidget as its children and still remain StatelessWidget.

What is the relation and difference between stateful and stateless widgets in Flutter?

答:
I can think of a very simple analogy. You have some piece of furniture with books, decorations, and a TV. The furniture is stateless, it does nothing doesn't move. In the TV, on the other side, you can turn it on, off, change channel, play a movie if it has some DVD attached, etc. The TV has a internal state which affects the way it behaves. In the furniture you have no state. The presence of the TV in the furniture is not adding a state to it.
Hope this helps.</p>


问:
What's the best way to detect a 'touch screen' device using JavaScript?
I've written a jQuery plug-in that's for use on both desktop and mobile devices. I wondered if there is a way with JavaScript to detect if the device has touch screen capability. I'm using jquery-mobile.js to detect the touch screen events and it works on iOS, Android etc., but I'd also like to write conditional statements based on whether the user's device has a touch screen.

Is that possible?

答:
Actually, I researched this question and consider all situations. because it is a big issue on my project too. So I reach the below function, it works for all versions of all browsers on all devices:

```<code>const isTouchDevice = () => {
  const prefixes = ['', '-webkit-', '-moz-', '-o-', '-ms-', ''];
  const mq = query => window.matchMedia(query).matches;

  if (
    'ontouchstart' in window ||
    (window.DocumentTouch && document instanceof DocumentTouch)
  ) {
    return true;
  }
  return mq(['(', prefixes.join('touch-enabled),('), 'heartz', ')'].join(''));
};
</code>```

Hint: Definitely, the isTouchDevice just returns boolean values.

Body:
Actually, I researched this question and consider all situations. because it is a big issue on my project too. So I reach the below function, it works for all versions of all browsers on all devices:

const isTouchDevice = () => {
  const prefixes = ['', '-webkit-', '-moz-', '-o-', '-ms-', ''];
  const mq = query => window.matchMedia(query).matches;

  if (
    'ontouchstart' in window ||
    (window.DocumentTouch && document instanceof DocumentTouch)
  ) {
    return true;
  }
  return mq(['(', prefixes.join('touch-enabled),('), 'heartz', ')'].join(''));
};

Hint: Definitely, the isTouchDevice just returns boolean values.


问:
How to set JAVA_HOME when I use the method "Runtime.getRuntime().exec" in Intellij Idea?
I want to use "jdeps" command to analyze some jar files' dependencies. My OS is Windows10. The core code is

```<code>String command = String.format("jdeps \"%s\"", path.toAbsolutePath().toString());
String format = String.format("cmd.exe /c %s", command);
process = Runtime.getRuntime().exec(format);
</code>```

There are 2 JDK version in my computer, JDK11 and JDK8. I want to use JDK11 and I set environment variable JAVA_HOME to JDK11's path. When I use cmd windows to execute the code, it works as I want, but If I run it in Intellij Idea, the JDK is changed to JDK8.

I'm sure that I have set the Project Settings--Project--Project SDK to JDK11. Project language level is SDK default(11-Local variable syntax for lambda parameters). Modules--Sources--Language level is "11-Local variable syntax for lambda parameters". The Java Compiler of Intellij Idea is also set to 11. There is nothing about JDK8 in my Intellij Idea.

But If I run my code in Intellij Idea, the JDK is still changed to JDK8. That makes me crazy. Is it a bug? What can I do to set JDK11?

By the way, I exec the "setx JAVA_HOME" command to set JAVA_HOME to JDK11 in my code, but it does not work.

答:
Intellij Idea use the PATH in environment variables if I did not set anything.
I run echo %PATH% in my code. The result is different with system environment variables. I had tried to restart my Intellij Idea, but it dose not work. Finally, I restart my computer and it works.</p>

Body:
I want to use "jdeps" command to analyze some jar files' dependencies. My OS is Windows10. The core code is

String command = String.format("jdeps \"%s\"", path.toAbsolutePath().toString());
String format = String.format("cmd.exe /c %s", command);
process = Runtime.getRuntime().exec(format);

There are 2 JDK version in my computer, JDK11 and JDK8. I want to use JDK11 and I set environment variable JAVA_HOME to JDK11's path. When I use cmd windows to execute the code, it works as I want, but If I run it in Intellij Idea, the JDK is changed to JDK8.

I'm sure that I have set the Project Settings--Project--Project SDK to JDK11. Project language level is SDK default(11-Local variable syntax for lambda parameters). Modules--Sources--Language level is "11-Local variable syntax for lambda parameters". The Java Compiler of Intellij Idea is also set to 11. There is nothing about JDK8 in my Intellij Idea.

But If I run my code in Intellij Idea, the JDK is still changed to JDK8. That makes me crazy. Is it a bug? What can I do to set JDK11?

By the way, I exec the "setx JAVA_HOME" command to set JAVA_HOME to JDK11 in my code, but it does not work.


问:
Python parser combinator for capturing text inside delimiters
I'm taking a look at some parser combinator libraries in Python (Parsy to be more precise) and I'm currently faced with the following problem, simplified with a minimally working example below:

text = '''
AAAAAAAAAA AAAAAAAA AAAAAAAAAAAAAA
BBBBBBB START THE TEXT HERE SHOULD
BE CAPTURED STOP CCCCCCCCCC CCCCCC
'''

start, stop = r"STARTS?", r"STOPS?"
s = section(text, start, stop)

print(s)
```

<p>which should output:</p>

``` THE TEXT HERE SHOULD
BE CAPTURED
```

<p>The current solution I'm working is by doing a regex lookahead, it works fine, but my original problem involves combining many of these little regexes, which can get messy and a problem for others to maintain later. </p>

<pre class="lang-py prettyprint-override"><code>from typing import Pattern, TypeVar
import re

# A Generic type declaration.
T = TypeVar("T")

def first(text: str, pattern: str, default: T, flags=0) -> T:
    """
    Given a `text`, a regex `pattern` and a `default` value, return the first match
    in `text`. Otherwise return a `default` value if no match is found.
    """
    match = re.findall(pattern, text, flags=flags)
    return match[0] if len(match) > 0 else default

def section(text: str, begin: str, end: str) -> str:
    """
    Given a `text` and two `start` and `stop` regexes, return the captured group
    found in the interval. Otherwise, return an empty string if no match is found.
    """
    return first(text, fr"{begin}([\s\S]*?)(?={end})", default="")
</code>```

Parser Combinators seem to be perfect for situations like these, but I'm unable to reproduce the same behavior as the working solution, any hints would be welcome:

```<code># A Simpler example with hardcoded stuff
from parsy import regex, seq, string

text = '''
AAAAAAAAAA AAAAAAAA AAAAAAAAAAAAAA
BBBBBBB START THE TEXT HERE SHOULD
BE CAPTURED STOP CCCCCCCCCC CCCCCC
'''

start = regex(r"STARTS?")
middle = regex(r"[\s\S]*").optional()
stop = regex(r"STOPS?")

eol = string("\n")

# Work fine
start.parse("START")
middle.parse("")
stop.parse("STOP")

section = seq(
    start,
    middle,
    stop
)
# Simpler case, breaks
section.parse("START AAA STOP")

</code>```

Gives:

```<code>---------------------------------------------------------------------------
ParseError                                Traceback (most recent call last)
<ipython-input-260-fdec112e1648> in <module>
     24 )
     25 # Simpler case, breaks
---> 26 section.parse("START AAA STOP")

~/.venv/lib/python3.8/site-packages/parsy/__init__.py in parse(self, stream)
     88     def parse(self, stream):
     89         """Parse a string or list of tokens and return the result or raise a ParseError."""
---> 90         (result, _) = (self << eof).parse_partial(stream)
     91         return result
     92

~/.venv/lib/python3.8/site-packages/parsy/__init__.py in parse_partial(self, stream)
    102             return (result.value, stream[result.index:])
    103         else:
--> 104             raise ParseError(result.expected, stream, result.furthest)
    105
    106     def bind(self, bind_fn):

ParseError: expected 'STOPS?' at 0:14

</code>```

答:
Did you try using split?

From my understanding of the requirements of your project. This is how I would do it:

```<code>text = '''
AAAAAAAAAA AAAAAAAA AAAAAAAAAAAAAA
BBBBBBB START THE TEXT HERE SHOULD
BE CAPTURED STOP CCCCCCCCCC CCCCCC
'''
# split text at START and take the second part of the text
# Then split the result by STOP and take the first part of the text
s = text.split('START')[1].split('STOP')[0]
print (s)
</code>```

Body:
I'm taking a look at some parser combinator libraries in Python (Parsy to be more precise) and I'm currently faced with the following problem, simplified with a minimally working example below:

text = '''
AAAAAAAAAA AAAAAAAA AAAAAAAAAAAAAA
BBBBBBB START THE TEXT HERE SHOULD
BE CAPTURED STOP CCCCCCCCCC CCCCCC
'''

start, stop = r"STARTS?", r"STOPS?"
s = section(text, start, stop)

print(s)

which should output:

 THE TEXT HERE SHOULD
BE CAPTURED

The current solution I'm working is by doing a regex lookahead, it works fine, but my original problem involves combining many of these little regexes, which can get messy and a problem for others to maintain later.

from typing import Pattern, TypeVar
import re

# A Generic type declaration.
T = TypeVar("T")

def first(text: str, pattern: str, default: T, flags=0) -> T:
    """
    Given a `text`, a regex `pattern` and a `default` value, return the first match
    in `text`. Otherwise return a `default` value if no match is found.
    """
    match = re.findall(pattern, text, flags=flags)
    return match[0] if len(match) > 0 else default

def section(text: str, begin: str, end: str) -> str:
    """
    Given a `text` and two `start` and `stop` regexes, return the captured group
    found in the interval. Otherwise, return an empty string if no match is found.
    """
    return first(text, fr"{begin}([\s\S]*?)(?={end})", default="")

Parser Combinators seem to be perfect for situations like these, but I'm unable to reproduce the same behavior as the working solution, any hints would be welcome:

# A Simpler example with hardcoded stuff
from parsy import regex, seq, string

text = '''
AAAAAAAAAA AAAAAAAA AAAAAAAAAAAAAA
BBBBBBB START THE TEXT HERE SHOULD
BE CAPTURED STOP CCCCCCCCCC CCCCCC
'''

start = regex(r"STARTS?")
middle = regex(r"[\s\S]*").optional()
stop = regex(r"STOPS?")

eol = string("\n")

# Work fine
start.parse("START")
middle.parse("")
stop.parse("STOP")

section = seq(
    start,
    middle,
    stop
)
# Simpler case, breaks
section.parse("START AAA STOP")

Gives:

---------------------------------------------------------------------------
ParseError                                Traceback (most recent call last)
<ipython-input-260-fdec112e1648> in <module>
     24 )
     25 # Simpler case, breaks
---> 26 section.parse("START AAA STOP")

~/.venv/lib/python3.8/site-packages/parsy/__init__.py in parse(self, stream)
     88     def parse(self, stream):
     89         """Parse a string or list of tokens and return the result or raise a ParseError."""
---> 90         (result, _) = (self << eof).parse_partial(stream)
     91         return result
     92

~/.venv/lib/python3.8/site-packages/parsy/__init__.py in parse_partial(self, stream)
    102             return (result.value, stream[result.index:])
    103         else:
--> 104             raise ParseError(result.expected, stream, result.furthest)
    105
    106     def bind(self, bind_fn):

ParseError: expected 'STOPS?' at 0:14

Body:
Did you try using split?

From my understanding of the requirements of your project. This is how I would do it:

text = '''
AAAAAAAAAA AAAAAAAA AAAAAAAAAAAAAA
BBBBBBB START THE TEXT HERE SHOULD
BE CAPTURED STOP CCCCCCCCCC CCCCCC
'''
# split text at START and take the second part of the text
# Then split the result by STOP and take the first part of the text
s = text.split('START')[1].split('STOP')[0]
print (s)


问:
How are some apps able to simply unzip and run on Windows PCs without SxS problems?
It's a common complaint from certain groups that installing on Windows spreads stuff all over the filesystem and registry, and some apps provide the option to simply unzip the files so you can 'uninstall' just be deleting. But how do they avoid all the ugliness of Visual C++ Redist, Side-by-Side (SxS), etc?

I have a little utility and really I'd prefer to distribute just a single .EXE which is run - no installer at all or even unzipping since it is small. Is this feasible?

edit:
As suggested, I tried building with static dependency on run-times (/MT instead of /MD). I got the following (middle part truncated for clarity):

```<code>1>Linking...
1>MSVCRT.lib(MSVCR90.dll) : error LNK2005: _free already defined in LIBCMT.lib(free.obj)
1>MSVCRT.lib(MSVCR90.dll) : error LNK2005: _malloc already defined in LIBCMT.lib(malloc.obj)
1>MSVCRT.lib(MSVCR90.dll) : error LNK2005: __mbschr already defined in LIBCMT.lib(mbschr.obj)
1>MSVCRT.lib(MSVCR90.dll) : error LNK2005: _realloc already defined in LIBCMT.lib(realloc.obj)
1>MSVCRT.lib(MSVCR90.dll) : error LNK2005: __strdup already defined in LIBCMT.lib(strdup.obj)
1>MSVCRT.lib(MSVCR90.dll) : error LNK2005: _abort already defined in LIBCMT.lib(abort.obj)
1>MSVCRT.lib(MSVCR90.dll) : error LNK2005: __stricmp already defined in LIBCMT.lib(stricmp.obj)
1>MSVCRT.lib(MSVCR90.dll) : error LNK2005: _setlocale already defined in LIBCMT.lib(setlocal.obj)
1>MSVCRT.lib(ti_inst.obj) : error LNK2005: "private: __thiscall type_info::type_info(class type_info const &)" (??0type_info@@AAE@ABV0@@Z) already defined in LIBCMT.lib(typinfo.obj)
1>MSVCRT.lib(ti_inst.obj) : error LNK2005: "private: class type_info & __thiscall type_info::operator=(class type_info const &)" (??4type_info@@AAEAAV0@ABV0@@Z) already defined in LIBCMT.lib(typinfo.obj)
1>LINK : warning LNK4098: defaultlib 'MSVCRT' conflicts with use of other libs; use /NODEFAULTLIB:library
</code>```

答:
You can distribute a single EXE if you statically link to the VC runtime - on the project's Property Page -> Configuration Properties -> C/C++ -> Code Generation and set "Runtime Library" to a "non-dll" option.

Depending on your target audience, distributing as a .exe may be problematic as .exe files are sometimes blocked from downloading in corporate environments, so providing a .zip file as well is advisable.

Body:
It's a common complaint from certain groups that installing on Windows spreads stuff all over the filesystem and registry, and some apps provide the option to simply unzip the files so you can 'uninstall' just be deleting. But how do they avoid all the ugliness of Visual C++ Redist, Side-by-Side (SxS), etc?

I have a little utility and really I'd prefer to distribute just a single .EXE which is run - no installer at all or even unzipping since it is small. Is this feasible?

edit:
As suggested, I tried building with static dependency on run-times (/MT instead of /MD). I got the following (middle part truncated for clarity):

1>Linking...
1>MSVCRT.lib(MSVCR90.dll) : error LNK2005: _free already defined in LIBCMT.lib(free.obj)
1>MSVCRT.lib(MSVCR90.dll) : error LNK2005: _malloc already defined in LIBCMT.lib(malloc.obj)
1>MSVCRT.lib(MSVCR90.dll) : error LNK2005: __mbschr already defined in LIBCMT.lib(mbschr.obj)
1>MSVCRT.lib(MSVCR90.dll) : error LNK2005: _realloc already defined in LIBCMT.lib(realloc.obj)
1>MSVCRT.lib(MSVCR90.dll) : error LNK2005: __strdup already defined in LIBCMT.lib(strdup.obj)
1>MSVCRT.lib(MSVCR90.dll) : error LNK2005: _abort already defined in LIBCMT.lib(abort.obj)
1>MSVCRT.lib(MSVCR90.dll) : error LNK2005: __stricmp already defined in LIBCMT.lib(stricmp.obj)
1>MSVCRT.lib(MSVCR90.dll) : error LNK2005: _setlocale already defined in LIBCMT.lib(setlocal.obj)
1>MSVCRT.lib(ti_inst.obj) : error LNK2005: "private: __thiscall type_info::type_info(class type_info const &)" (??0type_info@@AAE@ABV0@@Z) already defined in LIBCMT.lib(typinfo.obj)
1>MSVCRT.lib(ti_inst.obj) : error LNK2005: "private: class type_info & __thiscall type_info::operator=(class type_info const &)" (??4type_info@@AAEAAV0@ABV0@@Z) already defined in LIBCMT.lib(typinfo.obj)
1>LINK : warning LNK4098: defaultlib 'MSVCRT' conflicts with use of other libs; use /NODEFAULTLIB:library


问:
how to manage variable inside of json value string?
I have variable cardholder in my karate-config file.

I assigned it to the new entrID variable.

The main thing that i am building JSON as a String..

```<code> * def entrID = cardholder
 * def requestContactHistoryAdd =
   """
   {
   "RequestBody": "{ \"ENTR_ID\" : \"entrID\", \"BHVR_ID\" : \"VRU\", }"
   }
   """
</code>```

Now how can i provide it inside of my json RequestBody?

答:
EDIT: since you seem to have a very badly designed API where the JSON has an embedded string (which looks like JSON).

Please note I am using a string type below: https://github.com/intuit/karate#type-conversion

You can do this:

```<code>* def entrID = 'foo'
* string temp = { "ENTR_ID" : "#(entrID)", "BHVR_ID" : "VRU" }
# note that you could have done this:
# def temp = '{ "ENTR_ID" : "' + entrID + '", "BHVR_ID" : "VRU" }'
* def body = { RequestBody: '#(temp)' }
* print body
</code>```

Which gives you:

```<code>08:17:25.671 [main] INFO  com.intuit.karate - [print] {
  "RequestBody": "{\"ENTR_ID\":\"foo\",\"BHVR_ID\":\"VRU\"}"
}
</code>```

Body:
I have variable cardholder in my karate-config file.

I assigned it to the new entrID variable.

The main thing that i am building JSON as a String..

 * def entrID = cardholder
 * def requestContactHistoryAdd =
   """
   {
   "RequestBody": "{ \"ENTR_ID\" : \"entrID\", \"BHVR_ID\" : \"VRU\", }"
   }
   """

Now how can i provide it inside of my json RequestBody?

Body:
EDIT: since you seem to have a very badly designed API where the JSON has an embedded string (which looks like JSON).

Please note I am using a string type below: https://github.com/intuit/karate#type-conversion

You can do this:

* def entrID = 'foo'
* string temp = { "ENTR_ID" : "#(entrID)", "BHVR_ID" : "VRU" }
# note that you could have done this:
# def temp = '{ "ENTR_ID" : "' + entrID + '", "BHVR_ID" : "VRU" }'
* def body = { RequestBody: '#(temp)' }
* print body

Which gives you:

08:17:25.671 [main] INFO  com.intuit.karate - [print] {
  "RequestBody": "{\"ENTR_ID\":\"foo\",\"BHVR_ID\":\"VRU\"}"
}


问:
referencing desired overloaded generic method
given

```<code>public Class Example
{

public static void Foo< T>(int ID){}

public static void Foo< T,U>(int ID){}

}
</code>```

Questions:

Is it correct to call this an "overloaded generic method"?

How can either method be specified in creation of a MethodInfo object?

```<code>Type exampleType = Type.GetType("fullyqualifiednameOfExample, namespaceOfExample");
MethodInfo mi = exampleType.GetMethod("Foo", BindingFlags.Public|BindingFlags.Static, null, new Type[] {typeof(Type), typeof(Type) }, null);
</code>```

argument 4 causes the compiler much displeasure

答:
Another one liner to find the MethodInfo you want is to create a delegate;

var methodInfo = new Action<int>(Example.Foo<object,object>).Method.GetGenericMethodDefinition();
```

OwnerDisplayName: sympatric greg

Body:
given

public Class Example
{

public static void Foo< T>(int ID){}

public static void Foo< T,U>(int ID){}

}

Questions:

Is it correct to call this an "overloaded generic method"?

How can either method be specified in creation of a MethodInfo object?

Type exampleType = Type.GetType("fullyqualifiednameOfExample, namespaceOfExample");
MethodInfo mi = exampleType.GetMethod("Foo", BindingFlags.Public|BindingFlags.Static, null, new Type[] {typeof(Type), typeof(Type) }, null);

argument 4 causes the compiler much displeasure

LastEditorDisplayName: sympatric greg