答:
If you are getting your string in the same format as you mentioned in your question, you can break the string into an array and collect the last two elements as you required values.

Let me show you.

```<code>$myString = "1 rue Maryse Bastie 69500 BRON";
$breakUP = explode(" ", $myString);
$totalElement = count($breakUP);
$city = $breakUP[$totalElement - 1]; // Last element
$zip = $breakUP[$totalElement - 2]; // Second Last element
</code>```

Hope this helps you :)

Title: Extract some data from string php

Body:
Quick question to easily cut a string. I know the substr but I can not use it in my case.

I have for example this thong: "1 rue Maryse Bastie 69500 BRON"
I'd like to say "Get all the end before the numbers" in this case "BRON" and get the numbers. I want the city and the postalcode in difference variable.

The API I'm using returns the complete address but I'd like to cut out to save the city and postal code in a different table.

I think this subject can help me : Extracting a zip code from an address string but not to get the city.

For exemple, if i have 1 rue Maryse Bastie 69500 BRON
I want $city = "BRON" and $pc = "69500"

If i have 13 rue Hohwald 67000 Strasbourg
I want $city = "Strasbourg" and $pc = "67000"

Thanks

Body:
If you are getting your string in the same format as you mentioned in your question, you can break the string into an array and collect the last two elements as you required values.

Let me show you.

$myString = "1 rue Maryse Bastie 69500 BRON";
$breakUP = explode(" ", $myString);
$totalElement = count($breakUP);
$city = $breakUP[$totalElement - 1]; // Last element
$zip = $breakUP[$totalElement - 2]; // Second Last element

Hope this helps you :)


来源: stackexchange

问:
How can I turn this jquery into a function?
I would like to turn the below jquery code into a function so i could add links to the list and not have to touch the jquery. I'm assuming I will have to put the image name into the href> tag somewhere.

html code

```<code><img id="storyimg" src="1.png" alt="img" />
<ul class="sb_menu">
    <li><a href="linkpage.htm" class="newslink1">Link 1</a></li>
    <li><a href="linkpage.htm" class="newslink2">Link 2</a></li>
    <li><a href="linkpage.htm" class="newslink3">Link 3</a></li>
</ul>
</code>```

jquery

```<code>$('a.newslink1').bind('mouseover', function() {
    $('img#storyimg').attr("src", "1.png");
});
$('a.newslink2').bind('mouseover', function() {
    $('img#storyimg').attr("src", "2.png");
});
$('a.newslink3').bind('mouseover', function() {
    $('img#storyimg').attr("src", "3.png");
});
</code>```

答:
```<code><img id="storyimg" src="1.png" alt="img" />
<ul class="sb_menu">
    <li><a href="#" class="newslink" title="1.jpg">Link 1</a></li>
    <li><a href="#" class="newslink" title="2.jpg">Link 2</a></li>
    <li><a href="#" class="newslink" title="3.jpg">Link 3</a></li>
</ul>

$('a.newslink').hover(function(){
    $('img#storyimg').attr("src", $(this).attr('title'));
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I would like to turn the below jquery code into a function so i could add links to the list and not have to touch the jquery. I'm assuming I will have to put the image name into the  tag somewhere.

html code

Link 1

Link 2

Link 3

jquery

$('a.newslink1').bind('mouseover', function() {
    $('img#storyimg').attr("src", "1.png");
});
$('a.newslink2').bind('mouseover', function() {
    $('img#storyimg').attr("src", "2.png");
});
$('a.newslink3').bind('mouseover', function() {
    $('img#storyimg').attr("src", "3.png");
});


问:
Android Xamarin: how to grant BindTelecomConnectionService permission?
I have an issue making phone calls from the foreground service and this is my question about that.

As suggested in the comments of the question - I started testing the ConnectionService. I added BIND_TELECOM_CONNECTION_SERVICE permission to the manifest file.

Declared MyConnectionService class:

```<code>[Service(Permission= Manifest.Permission.BindTelecomConnectionService)]
public class MyConnectionService : ConnectionService
{

}
</code>```

And then I run this code:

```<code>var telecomManager = (TelecomManager)GetSystemService(Context.TelecomService);
var phoneAccountHandle = new PhoneAccountHandle(
    new ComponentName(this.PackageName, nameof(MyConnectionService)), "MyApp");
var builder = new PhoneAccount.Builder(phoneAccountHandle, "CustomAccount");
var phoneAccount = builder.Build();
telecomManager.RegisterPhoneAccount(phoneAccount);
</code>```

The telecomManager.RegisterPhoneAccount(phoneAccount); gives me an exception:

```<code>Java.Lang.SecurityException: 'PhoneAccount connection service requires BIND_TELECOM_CONNECTION_SERVICE permission.'
</code>```

Ok - it seems the permission is not granted. Testing it with ActivityCompat.CheckSelfPermission() - yes, it is not granted.

Making a permission request with ActivityCompat.RequestPermissions() - it is executed and that's it.
No permission request on the screen, not way to grant on the application permission page.

My question is - how to grant this kind of permission?

Environmet:

Android API Level 28

Testing on Google Pixel 2 XL phone running Android 10

答:
Comments by SushiHangover helped a lot and pointed to the right direction. In order to make the solution work and avoid the exception, the ConnectionService should have proper name (fully qualified Java class name) and permission declaration. These values can be added either in the manifest file or by declaring the ServiceAttribute in the code:

```<code> [Service(
      Name = "com.sample.MyApp.MyConnectionService",
      Permission = Manifest.Permission.BindTelecomConnectionService,
      Enabled = true)]
 public class MyConnectionService : ConnectionService
 {
 }
</code>```

Secondly, the name of the service must be exact when creating ComponentName instance:

```<code>var telecomManager = (TelecomManager)GetSystemService(Context.TelecomService);
var phoneAccountHandle = new PhoneAccountHandle(
    new ComponentName(this.PackageName, "com.sample.MyApp.MyConnectionService"),
    "GateOpener");
var builder = new PhoneAccount.Builder(phoneAccountHandle, "CustomAccount");
var phoneAccount = builder.Build();
telecomManager.RegisterPhoneAccount(phoneAccount);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have an issue making phone calls from the foreground service and this is my question about that.

As suggested in the comments of the question - I started testing the ConnectionService. I added BIND_TELECOM_CONNECTION_SERVICE permission to the manifest file.

Declared MyConnectionService class:

[Service(Permission= Manifest.Permission.BindTelecomConnectionService)]
public class MyConnectionService : ConnectionService
{

}

And then I run this code:

var telecomManager = (TelecomManager)GetSystemService(Context.TelecomService);
var phoneAccountHandle = new PhoneAccountHandle(
    new ComponentName(this.PackageName, nameof(MyConnectionService)), "MyApp");
var builder = new PhoneAccount.Builder(phoneAccountHandle, "CustomAccount");
var phoneAccount = builder.Build();
telecomManager.RegisterPhoneAccount(phoneAccount);

The telecomManager.RegisterPhoneAccount(phoneAccount); gives me an exception:

Java.Lang.SecurityException: 'PhoneAccount connection service requires BIND_TELECOM_CONNECTION_SERVICE permission.'

Ok - it seems the permission is not granted. Testing it with ActivityCompat.CheckSelfPermission() - yes, it is not granted.

Making a permission request with ActivityCompat.RequestPermissions() - it is executed and that's it.
No permission request on the screen, not way to grant on the application permission page.

My question is - how to grant this kind of permission?

Environmet:

Android API Level 28

Testing on Google Pixel 2 XL phone running Android 10

Body:
Comments by SushiHangover helped a lot and pointed to the right direction. In order to make the solution work and avoid the exception, the ConnectionService should have proper name (fully qualified Java class name) and permission declaration. These values can be added either in the manifest file or by declaring the ServiceAttribute in the code:

 [Service(
      Name = "com.sample.MyApp.MyConnectionService",
      Permission = Manifest.Permission.BindTelecomConnectionService,
      Enabled = true)]
 public class MyConnectionService : ConnectionService
 {
 }

Secondly, the name of the service must be exact when creating ComponentName instance:

var telecomManager = (TelecomManager)GetSystemService(Context.TelecomService);
var phoneAccountHandle = new PhoneAccountHandle(
    new ComponentName(this.PackageName, "com.sample.MyApp.MyConnectionService"),
    "GateOpener");
var builder = new PhoneAccount.Builder(phoneAccountHandle, "CustomAccount");
var phoneAccount = builder.Build();
telecomManager.RegisterPhoneAccount(phoneAccount);


问:
Apache PDFBox cannot find class 'Loader'. Why?
I'm using either pdfbox-app-2.0.18.jar or pdfbox-app-2.0.17.jar.

From the example here, I have this code below :

```<code>try (FileOutputStream fos = new FileOutputStream(signedFile);
     PDDocument doc = Loader.loadPDF(inputFile)) {

     // code

}
</code>```

After executing this code, I'm getting this error given below :

```<code>org.apache.pdfbox.Loader is not found
</code>```

How to resolve this issue ?

答:
Loader class is never introduced in version 2.x or lower. So, you can't use it.

Alternatively, you can use load() method from PDDocument class to load PDF files.

Modify to this :

```<code>try (FileOutputStream fos = new FileOutputStream(signedFile);
     PDDocument document = PDDocument.load(inputFile)) {

        // code

}
</code>```

Read this :- https://pdfbox.apache.org/2.0/migration.html

Body:
I'm using either pdfbox-app-2.0.18.jar or pdfbox-app-2.0.17.jar.

From the example here, I have this code below :

try (FileOutputStream fos = new FileOutputStream(signedFile);
     PDDocument doc = Loader.loadPDF(inputFile)) {

     // code

}

After executing this code, I'm getting this error given below :

org.apache.pdfbox.Loader is not found

How to resolve this issue ?

Body:
Loader class is never introduced in version 2.x or lower. So, you can't use it.

Alternatively, you can use load() method from PDDocument class to load PDF files.

Modify to this :

try (FileOutputStream fos = new FileOutputStream(signedFile);
     PDDocument document = PDDocument.load(inputFile)) {

        // code

}

Read this :- https://pdfbox.apache.org/2.0/migration.html


问:
How can I document the number of lines of code I have edited or written when using Vim?
I know it is basically meaningless to measure productivity by the number of lines of code, but I am curious.
I use Vim, my goal is :

have a number_of_lines_code.txt file automatically update itself when I am coding, it records the number of line of code so that I can check out how much I have written within a week, month, year.

答:
As someone else has mentioned in the comments, keeping track of edited locs is not the editor's job (you should use git, or other vcs). An obvious weakness of trying to use the editor for this task, imho, is that the editor is generally not aware of preceding or following sessions of the same editor.

However, one manual, naif way to do what you want could be the following

save the file

undo all the changes (this can be very easy to do, if you use the Gundo plugin, but I bet there are other ways to do the same)

save the file with another name

quit vim

diff the two files and/or do whatever you need to transform the diff in a number


问:
How to fetch data for chart js Pie Chart from State in React js?
As I am new to react i have been struggling to pass data from my state to the chartjs dynamically...what I need is when ever user updates the Textbox and asks for the Output, the Pie chart should update itself automatically according to the output...i have stored the output values in the state but Pie chart is not allowing me to Pass state as data...

Here's a Link to the Code Sandbox
https://codesandbox.io/s/autumn-mountain-sv1qk?fontsize=14&hidenavigation=1&theme=dark

```<code> class Buyer extends Component {

        constructor(props) {
            super(props);
            this.state = {
                income: 100000,
                percent: 13,
                totalTax: '',
                grossPrice: '',
                otherValues: '',
            }
        }

PieChart = (Gross,totalTax) => {
    let GrossPrice = Gross  ;
    let TotalTax = totalTax ;
    let data = [GrossPrice,TotalTax]
    let Pie = {
            labels: ['Total Tax', 'Gross Price'],
            datasets: [{
                data: data,
                backgroundColor: [
                    '#1ca5b6',
                    '#89ba2b',
                ],

            }]

        }

    }

handleIncome = (event) => {
    let income = event.target.value
    this.handleData(income, this.state.percent)
    console.log(this.state)

}

handlePercent = (event) => {
    let Percent = event.target.value
    this.handleSliderData(this.state.income, Percent)

}

// From Slider
sliderIncome = (event) => {
    this.setState({ income: event })
    this.handleSliderData(event, this.state.percent)
    // console.log(this.state)

}

sliderPercent = (event) => {
    this.setState({ percent: event })
    this.handleSliderData(this.state.income, event)

}

handleData = (income, Percent) => {
    this.setState({
        income: income,
        percent: Percent,
        totalTax: //some Calculations
        grossPrice: //some Calculations
        otherValues: //some Calculations

    })

    console.log(this.state)
}

handleSliderData = (income, Percent) => {
    this.setState({
        income: income,
        percent: Percent,
        totalTax: //some Calculations
        grossPrice://some Calculations
        otherValues://some Calculations
    })
    this.PieChart(this.state.grossPrice,this.state.totalTax)
    // console.log(this.state)

}

render() {
            return (
              <div>
                    <div >
                        <Card s>
                            <PieChart data={this.PieChart} width={600} height={300} />
                        </Card>
                    </div>
                </Col>

              )
     }
</code>```

I have tried creating a function for the pie chart but was not able to get through...any help would be appreciated..thanks!!

答:
I think there are a few problems with the code.
this.PieChart function doesn't return anything now. From giving the code a quick glance, I can see that you are trying to pass the props needed for the PieChart component from this.PieChart function. Return whatever you need as prop for the component and also call the function inside the JSX using parenthesis, passing the needed parameters into the function.

```<code>PieChart = (Gross,totalTax) => {
let GrossPrice = Gross  ;
let TotalTax = totalTax ;
let data = [GrossPrice,TotalTax]
let Pie = {
        labels: ['Total Tax', 'Gross Price'],
        datasets: [{
            data: data,
            backgroundColor: [
                '#1ca5b6',
                '#89ba2b',
            ],

        }]

    }

}
return Pie; //or whatever data you need for the component
</code>```

Also,

```<code> <PieChart data={this.PieChart(this.state.grossPrice, this.state.totalTax)} width={600} height={300} />
</code>```

Also, keep in mind to use proper naming conventions. Functions should be in camel case( this.PieChart should be named this.pieChart ). Try using different names for the component and function. This shall solve a lot of problems you might run into

Update: I have updated the sandbox you have shared. Hope this helps.
https://codesandbox.io/s/friendly-mahavira-79n2s

Body:
As I am new to react i have been struggling to pass data from my state to the chartjs dynamically...what I need is when ever user updates the Textbox and asks for the Output, the Pie chart should update itself automatically according to the output...i have stored the output values in the state but Pie chart is not allowing me to Pass state as data...

Here's a Link to the Code Sandbox
https://codesandbox.io/s/autumn-mountain-sv1qk?fontsize=14&hidenavigation=1&theme=dark

 class Buyer extends Component {

        constructor(props) {
            super(props);
            this.state = {
                income: 100000,
                percent: 13,
                totalTax: '',
                grossPrice: '',
                otherValues: '',
            }
        }

PieChart = (Gross,totalTax) => {
    let GrossPrice = Gross  ;
    let TotalTax = totalTax ;
    let data = [GrossPrice,TotalTax]
    let Pie = {
            labels: ['Total Tax', 'Gross Price'],
            datasets: [{
                data: data,
                backgroundColor: [
                    '#1ca5b6',
                    '#89ba2b',
                ],

            }]

        }

    }

handleIncome = (event) => {
    let income = event.target.value
    this.handleData(income, this.state.percent)
    console.log(this.state)

}

handlePercent = (event) => {
    let Percent = event.target.value
    this.handleSliderData(this.state.income, Percent)

}

// From Slider
sliderIncome = (event) => {
    this.setState({ income: event })
    this.handleSliderData(event, this.state.percent)
    // console.log(this.state)

}

sliderPercent = (event) => {
    this.setState({ percent: event })
    this.handleSliderData(this.state.income, event)

}

handleData = (income, Percent) => {
    this.setState({
        income: income,
        percent: Percent,
        totalTax: //some Calculations
        grossPrice: //some Calculations
        otherValues: //some Calculations

    })

    console.log(this.state)
}

handleSliderData = (income, Percent) => {
    this.setState({
        income: income,
        percent: Percent,
        totalTax: //some Calculations
        grossPrice://some Calculations
        otherValues://some Calculations
    })
    this.PieChart(this.state.grossPrice,this.state.totalTax)
    // console.log(this.state)

}

render() {
            return (

                        <Card s>
                            <PieChart data={this.PieChart} width={600} height={300} />
                        </Card>

                </Col>

              )
     }

I have tried creating a function for the pie chart but was not able to get through...any help would be appreciated..thanks!!

Body:
I think there are a few problems with the code.
this.PieChart function doesn't return anything now. From giving the code a quick glance, I can see that you are trying to pass the props needed for the PieChart component from this.PieChart function. Return whatever you need as prop for the component and also call the function inside the JSX using parenthesis, passing the needed parameters into the function.

PieChart = (Gross,totalTax) => {
let GrossPrice = Gross  ;
let TotalTax = totalTax ;
let data = [GrossPrice,TotalTax]
let Pie = {
        labels: ['Total Tax', 'Gross Price'],
        datasets: [{
            data: data,
            backgroundColor: [
                '#1ca5b6',
                '#89ba2b',
            ],

        }]

    }

}
return Pie; //or whatever data you need for the component

Also,

 <PieChart data={this.PieChart(this.state.grossPrice, this.state.totalTax)} width={600} height={300} />

Also, keep in mind to use proper naming conventions. Functions should be in camel case( this.PieChart should be named this.pieChart ). Try using different names for the component and function. This shall solve a lot of problems you might run into

Update: I have updated the sandbox you have shared. Hope this helps.
https://codesandbox.io/s/friendly-mahavira-79n2s


问:
How to encode the result of a mathematical operation in JSON from Python?
I'm trying to save the result of an addition in JSON format. I want as output something like that:

```<code>Result_0=[add,1,1,2]

</code>```

but instead I have this result:

```<code>{Result_0=["add",1,1,null]}
</code>```

I don't get why it read the result of the operation as null value. This is my code:

```<code>from Exercise_0 import *
import json

if __name__=="__main__":
    c= Calculator('Casio')
    d={}
    a=1
    b=1
    result=c.add(a,b)
    key="Result_0"
    d[key]=["add",1,1,result]
    print(json.dumps(d))

</code>```

Exercise_0:

```<code>class Calculator():
    def __init__(self, name):
        self.name=name

    def add(self, number_1, number_2):
        print(f"{number_1}+{number_2}={number_1+number_2}")

    def sub(self, number_1,number_2):
        print(f"{number_1}-{number_2}={number_1-number_2}")

    def mul(self, number_1,number_2):
        print(f"{number_1}*{number_2}={number_1*number_2}")

    def div(self, number_1,number_2):
        print(f"{number_1}/{number_2}={number_1/number_2}")
</code>```

答:
Change add() into:

```<code>def add(self, number_1, number_2):
        return number_1+number_2
</code>```

And you will get:

{"Result_0": ["add", 1, 1, 2]}

You should do the same for other functions as sub, mul... as well, so the result is returned back to the result variable which is later on used with the value of the function result. Something like:

```<code>import json

class Calculator():
    def __init__(self, name):
        self.name=name

    def add(self, number_1, number_2):
        return number_1+number_2

    def sub(self, number_1, number_2):
        return number_1-number_2

    def mul(self, number_1, number_2):
        return number_1*number_2

    def div(self, number_1, number_2):
        return number_1/number_2

if __name__=="__main__":
    c= Calculator('Casio')
    d={}
    a=3
    b=2

    key="Result_0"
    result=c.add(a,b)
    d[key]=["add",3,2,result]
    print(json.dumps(d))

    result=c.sub(a,b)
    d[key]=["sub",3,2,result]
    print(json.dumps(d))

    result=c.mul(a,b)
    d[key]=["mul",3,2,result]
    print(json.dumps(d))

    result=c.div(a,b)
    d[key]=["div",3,2,result]
    print(json.dumps(d))
</code>```

Resulting in:

```<code>{"Result_0": ["add", 3, 2, 5]}
{"Result_0": ["sub", 3, 2, 1]}
{"Result_0": ["mul", 3, 2, 6]}
{"Result_0": ["div", 3, 2, 1.5]}
</code>```

Body:
I'm trying to save the result of an addition in JSON format. I want as output something like that:

Result_0=[add,1,1,2]

but instead I have this result:

{Result_0=["add",1,1,null]}

I don't get why it read the result of the operation as null value. This is my code:

from Exercise_0 import *
import json

if __name__=="__main__":
    c= Calculator('Casio')
    d={}
    a=1
    b=1
    result=c.add(a,b)
    key="Result_0"
    d[key]=["add",1,1,result]
    print(json.dumps(d))

Exercise_0:

class Calculator():
    def __init__(self, name):
        self.name=name

    def add(self, number_1, number_2):
        print(f"{number_1}+{number_2}={number_1+number_2}")

    def sub(self, number_1,number_2):
        print(f"{number_1}-{number_2}={number_1-number_2}")

    def mul(self, number_1,number_2):
        print(f"{number_1}*{number_2}={number_1*number_2}")

    def div(self, number_1,number_2):
        print(f"{number_1}/{number_2}={number_1/number_2}")

Body:
Change add() into:

def add(self, number_1, number_2):
        return number_1+number_2

And you will get:

{"Result_0": ["add", 1, 1, 2]}

You should do the same for other functions as sub, mul... as well, so the result is returned back to the result variable which is later on used with the value of the function result. Something like:

import json

class Calculator():
    def __init__(self, name):
        self.name=name

    def add(self, number_1, number_2):
        return number_1+number_2

    def sub(self, number_1, number_2):
        return number_1-number_2

    def mul(self, number_1, number_2):
        return number_1*number_2

    def div(self, number_1, number_2):
        return number_1/number_2

if __name__=="__main__":
    c= Calculator('Casio')
    d={}
    a=3
    b=2

    key="Result_0"
    result=c.add(a,b)
    d[key]=["add",3,2,result]
    print(json.dumps(d))

    result=c.sub(a,b)
    d[key]=["sub",3,2,result]
    print(json.dumps(d))

    result=c.mul(a,b)
    d[key]=["mul",3,2,result]
    print(json.dumps(d))

    result=c.div(a,b)
    d[key]=["div",3,2,result]
    print(json.dumps(d))

Resulting in:

{"Result_0": ["add", 3, 2, 5]}
{"Result_0": ["sub", 3, 2, 1]}
{"Result_0": ["mul", 3, 2, 6]}
{"Result_0": ["div", 3, 2, 1.5]}


问:
Java: How do I call a method that implements another method in an interface?
```<code>public interface Directory {

    public void insertEntry(Entry entry, String surname);
</code>```

Let's say I have this method which is part of the Directory interface.

```<code>public void insertEntry(Entry entry, String surname) {
}
</code>```

Then I create a separate class called arrayDirectory which implements the same method in Directory.
How do I then call this method in the arrayDirectory class? Because I tried to call it in main but the method has to be static in order to do this and it can't be static because then it won't implement the method from the interface, and I'm not allowed to change the method signature for the methods in the interface. Please help, I don't know what to do.

答:
implements

Define your class as implementing that interface. Use the keyword implements.

Also, in Java conventions, class names start with an uppercase letter. So name your class ArrayDirectory, not arrayDirectory.

```<code>public class ArrayDirectory implements Directory
{
    public void insertEntry(Entry entry, String surname)
    {
        System.out.println( "Doing insertEntry work." ) ;
        …
    }
}
</code>```

Polymorphism

Now use that class, by instantiating an object via new. Refer to that object as the interface rather than the concrete class, if you will be calling only methods defined on the interface.

```<code>Directory directory = new ArrayDirectory() ;
</code>```

This technique is known as polymorphism (“many shapes”). A Dog object might be referred to as the more general Animal. A Circle object and a Rectangle might both be referred to as a Shape. An InternationalShippingLabel and a DomesticShippingLabel might both be referred to as a ShippingLabel. The PreferredCustomer and StandardCustomer classes can both implement the Customer interface.

Dynamic dispatch

Then call the method on that object.

```<code>directory.insertEntry( … , … ) ;
</code>```

Through the magic of dynamic dispatch, at runtime the JVM locates the necessary code on the ArrayDirectory class to be executed.

By the way, notice the naming conventions at work here. Class names start with an uppercase letter, while objects (actually, reference variables) start with a lowercase letter. And, FYI, Java naming uses the full range of Unicode characters (French accents, Japanese, etc), not just English ASCII characters.

Abstract class

If the various classes have some duplicate code, make their shared interface an abstract class instead. Then you can move that duplicated code into the abstract class. This way when you later are doing reviews or doing maintenance work, you have only only place to find, study, and fix that code.

Body:
public interface Directory {

    public void insertEntry(Entry entry, String surname);

Let's say I have this method which is part of the Directory interface.

public void insertEntry(Entry entry, String surname) {
}

Then I create a separate class called arrayDirectory which implements the same method in Directory.
How do I then call this method in the arrayDirectory class? Because I tried to call it in main but the method has to be static in order to do this and it can't be static because then it won't implement the method from the interface, and I'm not allowed to change the method signature for the methods in the interface. Please help, I don't know what to do.

Body:
implements

Define your class as implementing that interface. Use the keyword implements.

Also, in Java conventions, class names start with an uppercase letter. So name your class ArrayDirectory, not arrayDirectory.

public class ArrayDirectory implements Directory
{
    public void insertEntry(Entry entry, String surname)
    {
        System.out.println( "Doing insertEntry work." ) ;
        …
    }
}

Polymorphism

Now use that class, by instantiating an object via new. Refer to that object as the interface rather than the concrete class, if you will be calling only methods defined on the interface.

Directory directory = new ArrayDirectory() ;

This technique is known as polymorphism (“many shapes”). A Dog object might be referred to as the more general Animal. A Circle object and a Rectangle might both be referred to as a Shape. An InternationalShippingLabel and a DomesticShippingLabel might both be referred to as a ShippingLabel. The PreferredCustomer and StandardCustomer classes can both implement the Customer interface.

Dynamic dispatch

Then call the method on that object.

directory.insertEntry( … , … ) ;

Through the magic of dynamic dispatch, at runtime the JVM locates the necessary code on the ArrayDirectory class to be executed.

By the way, notice the naming conventions at work here. Class names start with an uppercase letter, while objects (actually, reference variables) start with a lowercase letter. And, FYI, Java naming uses the full range of Unicode characters (French accents, Japanese, etc), not just English ASCII characters.

Abstract class

If the various classes have some duplicate code, make their shared interface an abstract class instead. Then you can move that duplicated code into the abstract class. This way when you later are doing reviews or doing maintenance work, you have only only place to find, study, and fix that code.


问:
How can I get the current season using .NET? (Summer, Winter, etc...)
Is there a way to, given a date, retrieve the season of the year?  For any place on the globe?

Is this based on time zone as well as hemisphere?

Note that, In the southern hemisphere that summer is still during the warm months.

EDIT:

To clarify, I am talking about the astronomical seasons.

答:
Asp.net has PersianCalendar  in System.Globalization  built-in, you can use it to obtain the seasons easily.

In persian calendar :

Months 1 to 3 = Spring

Months 4 to 6 = Summer

Months 7 to 9 = Autumn

Months 10 to 12 = Winter

```<code>enum Season
{
    Sprint = 1,
    Summer = 2,
    Autumn = 3,
    Winter = 4
};

var persianMonth = new PersianCalendar().GetMonth( DateTime.Now );

var season = (Season) Math.Ceiling( persianMonth / 3.0 )
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Asp.net has PersianCalendar  in System.Globalization  built-in, you can use it to obtain the seasons easily.

In persian calendar :

Months 1 to 3 = Spring

Months 4 to 6 = Summer

Months 7 to 9 = Autumn

Months 10 to 12 = Winter

enum Season
{
    Sprint = 1,
    Summer = 2,
    Autumn = 3,
    Winter = 4
};

var persianMonth = new PersianCalendar().GetMonth( DateTime.Now );

var season = (Season) Math.Ceiling( persianMonth / 3.0 )


问:
Deprecated: Function ereg()

Possible Duplicate:

  Function ereg() is deprecated

I understand that in the new version of PHP ereg is deprecated:

Deprecated: Function ereg() is deprecated

The code below worked fine in the old PHP. So I replaced ereg with preg_match and I am now getting the following error:

Warning: preg_match() [function.preg-match]: Unknown modifier '{' in

Here is my code...

```<code>if (!empty($searchval))
{
    if(ereg("[0-9]{5}", $searchval)) {
        $zip = $searchval;
    }
    else {
        $city = $searchval;
    }
} else
{
    $error .= "<div id='Error'>Please enter zip</div>";
    $zip = false;
}
</code>```

答:
preg_*() need a delimiter for the regex.

In most cases, / is used, but you may use anything, so long as they match. ~ and @ are common, because they are unlikely to appear in most regexes.

Title: Deprecated: Function ereg()

Body:
Possible Duplicate:

  Function ereg() is deprecated

I understand that in the new version of PHP ereg is deprecated:

Deprecated: Function ereg() is deprecated

The code below worked fine in the old PHP. So I replaced ereg with preg_match and I am now getting the following error:

Warning: preg_match() [function.preg-match]: Unknown modifier '{' in

Here is my code...

if (!empty($searchval))
{
    if(ereg("[0-9]{5}", $searchval)) {
        $zip = $searchval;
    }
    else {
        $city = $searchval;
    }
} else
{
    $error .= "
Please enter zip
";
    $zip = false;
}


问:
How do i revert an image back after using np.copy?
```<code>def boxing(original_img,predictions)
  newImage = np.copy(original_img)
  for result in predictions:
    .
    .
    .
    return newImage

_, ax = plt.subplots(figsize=(20, 10))
ax.imshow(boxing(imgcv, result))
</code>```

Hey! I passed a np.copy(image) into the boxing function and returned a newImage. Above is the gist of my code and the ... part is just drawing bounding boxes and overwritting the NewImage. How do i convert the resultant newImage back to it's original form after the function?

```<code>_, ax = plt.subplots(figsize=(20, 10))
new_im = Image.fromarray(boxing(imgcv, result))
ax.imshow(new_im)
</code>```

From what i understand, i am supposed to use Image.fromarray to convert it back but I had no success. I understand this may be a silly question but I appreciate the suggestions!

答:
I found the solution. The issue is that the image is in BGR.

```<code>new_im = cv2.cvtColor(boxing(imgcv, result), cv2.COLOR_BGR2RGB)
</code>```

This essentially converts the image back to RGB. Hope it helps!

Body:
def boxing(original_img,predictions)
  newImage = np.copy(original_img)
  for result in predictions:
    .
    .
    .
    return newImage

_, ax = plt.subplots(figsize=(20, 10))
ax.imshow(boxing(imgcv, result))

Hey! I passed a np.copy(image) into the boxing function and returned a newImage. Above is the gist of my code and the ... part is just drawing bounding boxes and overwritting the NewImage. How do i convert the resultant newImage back to it's original form after the function?

_, ax = plt.subplots(figsize=(20, 10))
new_im = Image.fromarray(boxing(imgcv, result))
ax.imshow(new_im)

From what i understand, i am supposed to use Image.fromarray to convert it back but I had no success. I understand this may be a silly question but I appreciate the suggestions!

Body:
I found the solution. The issue is that the image is in BGR.

new_im = cv2.cvtColor(boxing(imgcv, result), cv2.COLOR_BGR2RGB)

This essentially converts the image back to RGB. Hope it helps!


问:
Intersection of two List in JAVA
I am trying to get the intersection between Two List in JAVA, Please find the List below

LIST 1:

List<EligViewEventSubject> list1=  new ArrayList<>();

list1=   [EligViewEventSubject [event=EOD, subjectTypeCd=HOLDINGS, region=IA], EligViewEventSubject [event=EOD, subjectTypeCd=ASSETS, region=IA]]
```

<p>LIST 2:</p>

<pre class="lang-java prettyprint-override"><code>List<EligViewEventSubject> list2=  new ArrayList<>();

list2 = [EligViewEventSubject [event=EOD, subjectTypeCd=ASSETS, region=IA]]
</code>```

The Result for the above should be Like below

List<EligViewEventSubject> resultList =  new ArrayList<>();

resultList = [EligViewEventSubject [event=EOD, subjectTypeCd=ASSETS, region=IA]]
```

<p>In short i want the Matching ones alone(intersection)</p>

<p>I have tried the below:</p>

<pre class="lang-java prettyprint-override"><code>List<EligViewEventSubject> unionList = new ArrayList<>(list1);
        unionList.addAll(list2);

List<EligViewEventSubject> intersectionList = new ArrayList<>(list1);
        intersectionList.retainAll(list2);
</code>```

Union List I get as:

[EligViewEventSubject [event=EOD, subjectTypeCd=HOLDINGS, region=IA], EligViewEventSubject [event=EOD, subjectTypeCd=ASSETS, region=IA], EligViewEventSubject [event=EOD, subjectTypeCd=ASSETS, region=IA]]
```

Intersection  is []

Please share your thoughts on this.

答:
Please reference this question, as this has already been answered. Intersection and union of ArrayLists in Java

To summarize, you can get the intersection of two arraylists in java as such:

```<code>public <T> List<T> intersection(List<T> list1, List<T> list2) {
    List<T> list = new ArrayList<T>();

    for (T t : list1){
       if(list2.contains(t)){
           list.add(t);
       }
    }

   return list;
}
</code>```

Title: Intersection of two List in JAVA

Body:
I am trying to get the intersection between Two List in JAVA, Please find the List below

LIST 1:

List<EligViewEventSubject> list1=  new ArrayList<>();

list1=   [EligViewEventSubject [event=EOD, subjectTypeCd=HOLDINGS, region=IA], EligViewEventSubject [event=EOD, subjectTypeCd=ASSETS, region=IA]]

LIST 2:

List<EligViewEventSubject> list2=  new ArrayList<>();

list2 = [EligViewEventSubject [event=EOD, subjectTypeCd=ASSETS, region=IA]]

The Result for the above should be Like below

List<EligViewEventSubject> resultList =  new ArrayList<>();

resultList = [EligViewEventSubject [event=EOD, subjectTypeCd=ASSETS, region=IA]]

In short i want the Matching ones alone(intersection)

I have tried the below:

List<EligViewEventSubject> unionList = new ArrayList<>(list1);
        unionList.addAll(list2);

List<EligViewEventSubject> intersectionList = new ArrayList<>(list1);
        intersectionList.retainAll(list2);

Union List I get as:

[EligViewEventSubject [event=EOD, subjectTypeCd=HOLDINGS, region=IA], EligViewEventSubject [event=EOD, subjectTypeCd=ASSETS, region=IA], EligViewEventSubject [event=EOD, subjectTypeCd=ASSETS, region=IA]]

Intersection  is []

Please share your thoughts on this.

Body:
Please reference this question, as this has already been answered. Intersection and union of ArrayLists in Java

To summarize, you can get the intersection of two arraylists in java as such:

public <T> List<T> intersection(List<T> list1, List<T> list2) {
    List<T> list = new ArrayList<T>();

    for (T t : list1){
       if(list2.contains(t)){
           list.add(t);
       }
    }

   return list;
}


问:
How do I stop VueJS S3 Deploy from re-uploading static files?
I'm making a new VueJS app using Vue' CLI tool, and adding a few images and fonts to the "assets" folder inside "src", however every time I do a vue-cli-service s3-deploy, it uploads everything again instead of skipping static assets.

What do I need to do in order to achieve this?

答:
It turned out being the dist folder itself that gets re-generated entirely when building, and that confuses AWS SYNC functionality, making it upload everything again.

I ended up splitting the deploy process into 2 different NPM tasks, one of them uploading the assets folder and the other uploading the rest. Here are the final commands:

1) Deploy fonts an images

aws s3 sync --acl public-read dist/fonts s3://bucket/fonts
aws s3 sync --acl public-read dist/img s3://bucket/img
```

<p>2) Deploy the rest of the project except my assets</p>

<pre class="lang-sh prettyprint-override"><code>aws s3 sync --acl public-read --exclude 'fonts/*' --exclude 'img/*' dist s3://bucket
</code>```

It's worth noting that both "img" and "fonts" folders are generated by Vue CLI itself and contain all of the project images and fonts respectively.

Body:
It turned out being the dist folder itself that gets re-generated entirely when building, and that confuses AWS SYNC functionality, making it upload everything again.

I ended up splitting the deploy process into 2 different NPM tasks, one of them uploading the assets folder and the other uploading the rest. Here are the final commands:

1) Deploy fonts an images

aws s3 sync --acl public-read dist/fonts s3://bucket/fonts
aws s3 sync --acl public-read dist/img s3://bucket/img

2) Deploy the rest of the project except my assets

aws s3 sync --acl public-read --exclude 'fonts/*' --exclude 'img/*' dist s3://bucket

It's worth noting that both "img" and "fonts" folders are generated by Vue CLI itself and contain all of the project images and fonts respectively.


问:
PHP reading a cookie file
Are there any helper libs to read a cookie file in php. I have a cookie file on my local disk and I would like a better way of reading it. I am currently just reading to file like by line and parsing out the values.</p>

答:
This is pretty simple if you aim to read Netscape's format (e.g. curl saves cookies in COOKIEJAR in this format).

First an example (pipes and line numbers are added here and do not occur in real file):

```<code>01 | # Netscape HTTP Cookie File
02 | # http://curl.haxx.se/rfc/cookie_spec.html
03 | # This file was generated by libcurl! Edit at your own risk.
04 |
05 | .google.com    TRUE    /   FALSE   1305843382  cookiename  the value
06 | .yahoo.com TRUE    /   FALSE   1305843382  another_cookie  it's value
07 |
</code>```

As you can see:

We might have comment lines denoted with # as the first character.

We might have blank lines

And then, the beefy lines each have 7 tokens separated with a tab character (\t).
These are defined here:

domain - The domain that created AND that can read the variable.

flag - A TRUE/FALSE value indicating if all machines within a given domain can access the variable. This value is set automatically by the browser, depending on the value you set for domain.

path - The path within the domain that the variable is valid for.

secure - A TRUE/FALSE value indicating if a secure connection with the domain is needed to access the variable.

expiration - The UNIX time that the variable will expire on. UNIX time is defined as the number of seconds since Jan 1, 1970 00:00:00 GMT.

name - The name of the variable.

value - The value of the variable.

So, now let's make our cookie-file parser.

```<code>// read the file
$lines = file('path/to/cookies.txt');

// var to hold output
$trows = '';

// iterate over lines
foreach($lines as $line) {

  // we only care for valid cookie def lines
  if($line[0] != '#' && substr_count($line, "\t") == 6) {

    // get tokens in an array
    $tokens = explode("\t", $line);

    // trim the tokens
    $tokens = array_map('trim', $tokens);

    // let's convert the expiration to something readable
    $tokens[4] = date('Y-m-d h:i:s', $tokens[4]);

    // we can do different things with the tokens, here we build a table row
    $trows .= '<tr></td>' . implode('</td><td>', $tokens) . '</td></tr>' . PHP_EOL;

    // another option, make arrays to do things with later,
    // we'd have to define the arrays beforehand to use this
    // $domains[] = $tokens[0];
    // flags[] = $tokens[1];
    // and so on, and so forth

  }

}

// complete table and send output
// not very useful as it is almost like the original data, but then ...
echo '<table>'.PHP_EOL.'<tbody>'.PHP_EOL.$trows.'</tbody>'.PHP_EOL.'</table>';
</code>```

Finally, here is a demo.

OwnerDisplayName: pborg

LastEditorDisplayName: TravisO

Title: PHP reading a cookie file

Body:
This is pretty simple if you aim to read Netscape's format (e.g. curl saves cookies in COOKIEJAR in this format).

First an example (pipes and line numbers are added here and do not occur in real file):

01 | # Netscape HTTP Cookie File
02 | # http://curl.haxx.se/rfc/cookie_spec.html
03 | # This file was generated by libcurl! Edit at your own risk.
04 |
05 | .google.com    TRUE    /   FALSE   1305843382  cookiename  the value
06 | .yahoo.com TRUE    /   FALSE   1305843382  another_cookie  it's value
07 |

As you can see:

We might have comment lines denoted with # as the first character.

We might have blank lines

And then, the beefy lines each have 7 tokens separated with a tab character (\t).
These are defined here:

domain - The domain that created AND that can read the variable.

flag - A TRUE/FALSE value indicating if all machines within a given domain can access the variable. This value is set automatically by the browser, depending on the value you set for domain.

path - The path within the domain that the variable is valid for.

secure - A TRUE/FALSE value indicating if a secure connection with the domain is needed to access the variable.

expiration - The UNIX time that the variable will expire on. UNIX time is defined as the number of seconds since Jan 1, 1970 00:00:00 GMT.

name - The name of the variable.

value - The value of the variable.

So, now let's make our cookie-file parser.

// read the file
$lines = file('path/to/cookies.txt');

// var to hold output
$trows = '';

// iterate over lines
foreach($lines as $line) {

  // we only care for valid cookie def lines
  if($line[0] != '#' && substr_count($line, "\t") == 6) {

    // get tokens in an array
    $tokens = explode("\t", $line);

    // trim the tokens
    $tokens = array_map('trim', $tokens);

    // let's convert the expiration to something readable
    $tokens[4] = date('Y-m-d h:i:s', $tokens[4]);

    // we can do different things with the tokens, here we build a table row
    $trows .= '<tr></td>' . implode('</td><td>', $tokens) . '</td></tr>' . PHP_EOL;

    // another option, make arrays to do things with later,
    // we'd have to define the arrays beforehand to use this
    // $domains[] = $tokens[0];
    // flags[] = $tokens[1];
    // and so on, and so forth

  }

}

// complete table and send output
// not very useful as it is almost like the original data, but then ...
echo '<table>'.PHP_EOL.'<tbody>'.PHP_EOL.$trows.'</tbody>'.PHP_EOL.'</table>';

Finally, here is a demo.


问:
PrimeFaces Tree component, setting selected node from managed bean
I'm running Primefaces 3.2 and JSF 2.0 on Glassfish 3.

I've tried a lot, to programatically set the selected node from a managed bean. That includes setting the selected node like this:

```<code>public void setSelectedTreeNode(String name) {
TreeNode root = treeBean.getRoot();
List<TreeNode> tree = root.getChildren();
for(TreeNode node:tree) {
  if(node.getData().toString().contains(name)) {
    System.out.println("found the node to select");
    treeBean.setSelectedNode(node);
    break;
  }
}
RequestContext context = RequestContext.getCurrentInstance();
context.update(":navForm:treeSingle");
}
</code>```

The "found the node to select" gets printed in the terminal, but the node is not selected in the Tree in the web page..

The tree is like this:

```<code><h:form id="navForm">
<p:tree id="treeSingle" value="#{treeBean.root}" var="node"
       selectionMode="single" styleClass="treeStyle"
       selection="#{treeBean.selectedNode}"
       cache="false"
       >
   <p:ajax event="select" listener="#{treeBean.onNodeSelect}" update=":mainForm" />
   <p:treeNode>
       <h:outputText value="#{node}" escape="false" />
   </p:treeNode>
</code>```

Edit: TreeBean is built like this:

```<code>@ManagedBean
@SessionScoped
public class TreeBean implements Serializable {

private TreeNode root;

private TreeNode selectedNode;

public TreeBean() {
    root = new DefaultTreeNode("Root", null);
    TreeNode node0 = new DefaultTreeNode("Node 0", root);
    TreeNode node1 = new DefaultTreeNode("Node 1", root);
    TreeNode node2 = new DefaultTreeNode("Node 2", root);

    TreeNode node00 = new DefaultTreeNode("Node 0.0", node0);
    TreeNode node01 = new DefaultTreeNode("Node 0.1", node0);

    TreeNode node10 = new DefaultTreeNode("Node 1.0", node1);
    TreeNode node11 = new DefaultTreeNode("Node 1.1", node1);

    TreeNode node000 = new DefaultTreeNode("Node 0.0.0", node00);
    TreeNode node001 = new DefaultTreeNode("Node 0.0.1", node00);
    TreeNode node010 = new DefaultTreeNode("Node 0.1.0", node01);

    TreeNode node100 = new DefaultTreeNode("Node 1.0.0", node10);
}

public TreeNode getRoot() {
    return root;
}

public TreeNode getSelectedNode() {
    return selectedNode;
}

public void setSelectedNode(TreeNode selectedNode) {
    this.selectedNode = selectedNode;
}
}
</code>```

Does anyone have any idea on how to do this?

答:
for me none of the above worked.
because from what I see in the console, the child nodes don't have any ids let alone any row key number
so I used jQuery advanced class selector with the help of the rowKey attribute
so I had to use </p>

```<code>String script = "PF('treeSingleWidget').selectNode($(\"td[data-rowkey='" + selectedNode.getRowKey() + "']\"))";
Primefaces.current().executeScript(script);
</code>```

Body:
I'm running Primefaces 3.2 and JSF 2.0 on Glassfish 3.

I've tried a lot, to programatically set the selected node from a managed bean. That includes setting the selected node like this:

public void setSelectedTreeNode(String name) {
TreeNode root = treeBean.getRoot();
List<TreeNode> tree = root.getChildren();
for(TreeNode node:tree) {
  if(node.getData().toString().contains(name)) {
    System.out.println("found the node to select");
    treeBean.setSelectedNode(node);
    break;
  }
}
RequestContext context = RequestContext.getCurrentInstance();
context.update(":navForm:treeSingle");
}

The "found the node to select" gets printed in the terminal, but the node is not selected in the Tree in the web page..

The tree is like this:

<h:form id="navForm">

       <h:outputText value="#{node}" escape="false" />

Edit: TreeBean is built like this:

@ManagedBean
@SessionScoped
public class TreeBean implements Serializable {

private TreeNode root;

private TreeNode selectedNode;

public TreeBean() {
    root = new DefaultTreeNode("Root", null);
    TreeNode node0 = new DefaultTreeNode("Node 0", root);
    TreeNode node1 = new DefaultTreeNode("Node 1", root);
    TreeNode node2 = new DefaultTreeNode("Node 2", root);

    TreeNode node00 = new DefaultTreeNode("Node 0.0", node0);
    TreeNode node01 = new DefaultTreeNode("Node 0.1", node0);

    TreeNode node10 = new DefaultTreeNode("Node 1.0", node1);
    TreeNode node11 = new DefaultTreeNode("Node 1.1", node1);

    TreeNode node000 = new DefaultTreeNode("Node 0.0.0", node00);
    TreeNode node001 = new DefaultTreeNode("Node 0.0.1", node00);
    TreeNode node010 = new DefaultTreeNode("Node 0.1.0", node01);

    TreeNode node100 = new DefaultTreeNode("Node 1.0.0", node10);
}

public TreeNode getRoot() {
    return root;
}

public TreeNode getSelectedNode() {
    return selectedNode;
}

public void setSelectedNode(TreeNode selectedNode) {
    this.selectedNode = selectedNode;
}
}

Does anyone have any idea on how to do this?

Body:
for me none of the above worked.
because from what I see in the console, the child nodes don't have any ids let alone any row key number
so I used jQuery advanced class selector with the help of the rowKey attribute
so I had to use

String script = "PF('treeSingleWidget').selectNode($(\"td[data-rowkey='" + selectedNode.getRowKey() + "']\"))";
Primefaces.current().executeScript(script);


问:
The type or namespace name 'Caching' does not exist in the namespace 'System.Runtime'
I know there is usually a simple solution to this which is reference the dll in add references. But I have added the reference and system.runtime.caching appears in my references list but the error still displays.

The error displays in the browser in runtime so it does compile.

I have removed and re added the reference but still no luck.
I have restarted VS 2012 and restarted.

Visual Studio 2012
.net framework 4.5

Screen shot:

答:
Go  to Solution Explorer, right-click on References and "Add Reference."
Select "Assemblies", if it's not already highlighted, and start searching for "System.Runtime.Cashing".
Before you finish typing you should see it listed.

Check the box to the left and click ok.


问:
regex with 'Named Capture Group' to catch a pattern or an alternate one
I try to catch with one unique regex

```<code>either: ' PIC S9(17).'            # with 'S9(17)'      in Named Capture Group pic
either: ' PIC S9(13)V9(2).'       # with 'S9(13)V9(2)' in Named Capture Group pic
either: ' PIC S9(9)V9(2) COMP-3.' # with 'S9(9)V9(2)'  in Named Capture Group pic
either: ' PIC X(16).'             # with 'X(16)'       in Named Capture Group pic
</code>```

with r'\s*PIC\s+(?P<pic>\S+)'
  I catch all but ' PIC S9(9)V9(2) COMP-3.'

with r'\s*PIC\s+(?P<pic>\S+) COMP-3'
  I catch only ' PIC S9(9)V9(2) COMP-3.'

This is my Python code:

```<code>import re
def get_pics(data, pic):
    base = r'^(?P<level>\d{2})\s+(?P<name>\S+)'
    end = r'\.$'
    pformat = "({})?"
    pattern = re.compile(base + pformat.format(pic) + end)

    for row in data.strip().split('\n'):
        re_match = pattern.match(row.strip())
        if not re_match:
            print(' => NOP:\n    ', row)
        else:
            match = re_match.groupdict()
            print('ok:', match)

data = """
   12 M-AR03-MONTANT-RDJ                 PIC S9(17).
   12 M-AR03-COMPTE-RDJ                  PIC X(8).
  09 M-N014-INC-CHARG-AMT-FSOL           PIC S9(9)V9(2) COMP-3.
  09 M-N014-CHARGE-TYPE-FSOL             PIC X(5).
"""
</code>```

So we get:

```<code>>>> get_pics(data, r'\s*PIC\s+(?P<pic>\S+)')
ok: {'level': '12', 'name': 'M-AR03-MONTANT-RDJ', 'pic': 'S9(17)'}
ok: {'level': '12', 'name': 'M-AR03-COMPTE-RDJ', 'pic': 'X(8)'}
 => NOP:
       09 M-N014-INC-CHARG-AMT-FSOL  PIC S9(9)V9(2) COMP-3.
ok: {'level': '09', 'name': 'M-N014-CHARGE-TYPE-FSOL', 'pic': 'X(5)'}
>>>
</code>```

or

```<code>>>> get_pics(data, r'\s*PIC\s+(?P<pic>\S+) COMP-3')
 => NOP:
     12 M-AR03-MONTANT-RDJ         PIC S9(17).
 => NOP:
        12 M-AR03-COMPTE-RDJ       PIC X(8).
ok: {'level': '09', 'name': 'M-N014-INC-CHARG-AMT-FSOL', 'pic': 'S9(9)V9(2)'}
 => NOP:
       09 M-N014-CHARGE-TYPE-FSOL  PIC X(5).
>>>
</code>```

What is strange is that in https://regex101.com/ the '\s*PIC\s+(?P<pic>\S+)'
match for all 4 lines:

```<code>PIC S9(17).
PIC S9(13)V9(2).
PIC S9(9)V9(2) COMP-3.
PIC X(16).
</code>```

If I try the @the-fourth-bird regex I get:

```<code>In [2]: get_pics(data, r'\bPIC (?P<pic>(?:[A-Z]\d*\(\d+\))+)[^.\r\n]*\.')
   ...:
 => NOP:
     12 M-AR03-MONTANT-RDJ          PIC S9(17).
 => NOP:
        12 M-AR03-COMPTE-RDJ           PIC X(8).
 => NOP:
       09 M-N014-INC-CHARG-AMT-FSOL    PIC S9(9)V9(2) COMP-3.
 => NOP:
       09 M-N014-CHARGE-TYPE-FSOL      PIC X(5).

In [3]:
</code>```

答:
If you want capturing group pic with those values and there should be at dot at the end present, you could make the pattern a bit more specific:

```<code>\bPIC (?P<pic>(?:[A-Z]\d*\(\d+\))+)[^.\r\n]*\.
</code>```

\bPIC  Word boundary, match PIC and space

(?P<pic> Named group pic

(?: Non capture group

[A-Z]\d*\(\d+\) Match a char A-Z, opitonal digits and 1+ digits between parenthesis

)+ Close group an repeat 1+ times

) Close group pic

[^.\r\n]*\. Match any char except a dot and newline 0+ times and match the trailing dot

Regex demo | Python demo

In your code, you don't have to make the group optional using ? The pattern for the group pic already contains matching the ending dot so you could omit end = r'\.$'

Between the first and the second pattern, there are one or more spaces which you could match using [^\S\r\n]+ which will match 1 or more times any whitespace char except a newline.

For example

```<code>import re
def get_pics(data, pic):
    base = r'(?P<level>\d{2})\s+(?P<name>\S+)'
    pattern = re.compile(f"^{base}[^\S\r\n]+{pic}$")
    for row in data.strip().split('\n'):
        re_match = pattern.match(row.strip())
        if not re_match:
            print(' => NOP:\n    ', row)
        else:
            match = re_match.groupdict()
            print('ok:', match)

data = """
   12 M-AR03-MONTANT-RDJ                 PIC S9(17).
   12 M-AR03-COMPTE-RDJ                  PIC X(8).
  09 M-N014-INC-CHARG-AMT-FSOL           PIC S9(9)V9(2) COMP-3.
  09 M-N014-CHARGE-TYPE-FSOL             PIC X(5).
"""

get_pics(data, r'\bPIC (?P<pic>(?:[A-Z]\d*\(\d+\))+)[^.\r\n]*\.')
</code>```

Output

```<code>ok: {'level': '12', 'name': 'M-AR03-MONTANT-RDJ', 'pic': 'S9(17)'}
ok: {'level': '12', 'name': 'M-AR03-COMPTE-RDJ', 'pic': 'X(8)'}
ok: {'level': '09', 'name': 'M-N014-INC-CHARG-AMT-FSOL', 'pic': 'S9(9)V9(2)'}
ok: {'level': '09', 'name': 'M-N014-CHARGE-TYPE-FSOL', 'pic': 'X(5)'}
</code>```

Body:
I try to catch with one unique regex

either: ' PIC S9(17).'            # with 'S9(17)'      in Named Capture Group pic
either: ' PIC S9(13)V9(2).'       # with 'S9(13)V9(2)' in Named Capture Group pic
either: ' PIC S9(9)V9(2) COMP-3.' # with 'S9(9)V9(2)'  in Named Capture Group pic
either: ' PIC X(16).'             # with 'X(16)'       in Named Capture Group pic

with r'\s*PIC\s+(?P<pic>\S+)'
  I catch all but ' PIC S9(9)V9(2) COMP-3.'

with r'\s*PIC\s+(?P<pic>\S+) COMP-3'
  I catch only ' PIC S9(9)V9(2) COMP-3.'

This is my Python code:

import re
def get_pics(data, pic):
    base = r'^(?P<level>\d{2})\s+(?P<name>\S+)'
    end = r'\.$'
    pformat = "({})?"
    pattern = re.compile(base + pformat.format(pic) + end)

    for row in data.strip().split('\n'):
        re_match = pattern.match(row.strip())
        if not re_match:
            print(' => NOP:\n    ', row)
        else:
            match = re_match.groupdict()
            print('ok:', match)

data = """
   12 M-AR03-MONTANT-RDJ                 PIC S9(17).
   12 M-AR03-COMPTE-RDJ                  PIC X(8).
  09 M-N014-INC-CHARG-AMT-FSOL           PIC S9(9)V9(2) COMP-3.
  09 M-N014-CHARGE-TYPE-FSOL             PIC X(5).
"""

So we get:

>>> get_pics(data, r'\s*PIC\s+(?P<pic>\S+)')
ok: {'level': '12', 'name': 'M-AR03-MONTANT-RDJ', 'pic': 'S9(17)'}
ok: {'level': '12', 'name': 'M-AR03-COMPTE-RDJ', 'pic': 'X(8)'}
 => NOP:
       09 M-N014-INC-CHARG-AMT-FSOL  PIC S9(9)V9(2) COMP-3.
ok: {'level': '09', 'name': 'M-N014-CHARGE-TYPE-FSOL', 'pic': 'X(5)'}
>>>

or

>>> get_pics(data, r'\s*PIC\s+(?P<pic>\S+) COMP-3')
 => NOP:
     12 M-AR03-MONTANT-RDJ         PIC S9(17).
 => NOP:
        12 M-AR03-COMPTE-RDJ       PIC X(8).
ok: {'level': '09', 'name': 'M-N014-INC-CHARG-AMT-FSOL', 'pic': 'S9(9)V9(2)'}
 => NOP:
       09 M-N014-CHARGE-TYPE-FSOL  PIC X(5).
>>>

What is strange is that in https://regex101.com/ the '\s*PIC\s+(?P<pic>\S+)'
match for all 4 lines:

PIC S9(17).
PIC S9(13)V9(2).
PIC S9(9)V9(2) COMP-3.
PIC X(16).

If I try the @the-fourth-bird regex I get:

In [2]: get_pics(data, r'\bPIC (?P<pic>(?:[A-Z]\d*\(\d+\))+)[^.\r\n]*\.')
   ...:
 => NOP:
     12 M-AR03-MONTANT-RDJ          PIC S9(17).
 => NOP:
        12 M-AR03-COMPTE-RDJ           PIC X(8).
 => NOP:
       09 M-N014-INC-CHARG-AMT-FSOL    PIC S9(9)V9(2) COMP-3.
 => NOP:
       09 M-N014-CHARGE-TYPE-FSOL      PIC X(5).

In [3]:

Body:
If you want capturing group pic with those values and there should be at dot at the end present, you could make the pattern a bit more specific:

\bPIC (?P<pic>(?:[A-Z]\d*\(\d+\))+)[^.\r\n]*\.

\bPIC  Word boundary, match PIC and space

(?P<pic> Named group pic

(?: Non capture group

[A-Z]\d*\(\d+\) Match a char A-Z, opitonal digits and 1+ digits between parenthesis

)+ Close group an repeat 1+ times

) Close group pic

[^.\r\n]*\. Match any char except a dot and newline 0+ times and match the trailing dot

Regex demo | Python demo

In your code, you don't have to make the group optional using ? The pattern for the group pic already contains matching the ending dot so you could omit end = r'\.$'

Between the first and the second pattern, there are one or more spaces which you could match using [^\S\r\n]+ which will match 1 or more times any whitespace char except a newline.

For example

import re
def get_pics(data, pic):
    base = r'(?P<level>\d{2})\s+(?P<name>\S+)'
    pattern = re.compile(f"^{base}[^\S\r\n]+{pic}$")
    for row in data.strip().split('\n'):
        re_match = pattern.match(row.strip())
        if not re_match:
            print(' => NOP:\n    ', row)
        else:
            match = re_match.groupdict()
            print('ok:', match)

data = """
   12 M-AR03-MONTANT-RDJ                 PIC S9(17).
   12 M-AR03-COMPTE-RDJ                  PIC X(8).
  09 M-N014-INC-CHARG-AMT-FSOL           PIC S9(9)V9(2) COMP-3.
  09 M-N014-CHARGE-TYPE-FSOL             PIC X(5).
"""

get_pics(data, r'\bPIC (?P<pic>(?:[A-Z]\d*\(\d+\))+)[^.\r\n]*\.')

Output

ok: {'level': '12', 'name': 'M-AR03-MONTANT-RDJ', 'pic': 'S9(17)'}
ok: {'level': '12', 'name': 'M-AR03-COMPTE-RDJ', 'pic': 'X(8)'}
ok: {'level': '09', 'name': 'M-N014-INC-CHARG-AMT-FSOL', 'pic': 'S9(9)V9(2)'}
ok: {'level': '09', 'name': 'M-N014-CHARGE-TYPE-FSOL', 'pic': 'X(5)'}


问:
What is wrong with how I'm dynamically allocating space for this 2d array?
I'm trying to create a 2D array that will store be able to store each character of a .txt file as an element in the 2D array.

How do I dynamically allocate space for it?

This what I've done so far to malloc it. (this was copied of GeeksForGeeks)

```<code>char *arr[rownum2];

for (i = 0; i < rownum2; i++) {
    arr[i] = (char *)malloc(colnum * sizeof(char));
</code>```

However, I think this is the source of serious memory related issues later on in my program, and I've also been told some parts of this are unnecessary.

Can I please get the most suitable way to dynamically allocate memory for the 2D array in this specific scenario?

答:
The only serious problem I see in your code is that you are casting the returned value of malloc(3), and probably you have forgotten to #include <stdlib.h> also (this is a dangerous cocktail), and this way, you are destroying the returned value of the call with the cast you put before malloc(3).  Let me explain:

First, you have (or haven't, but I have to guess) a 64bit architecture (as it is common today) and pointers are 64bit wide in your system, while int integers are 32bit wide.

You have probably forgotten to #include <stdlib.h> in your code (which is something I have to guess also), so the compiler is assuming that malloc(3) is actually a function returning int (this is legacy in C, if you don't provide a prototype for a function external to the compilation unit), so the compiler is generating code to get just a 32 bit value from the malloc(3) function, and not the 64bit pointer that (probably, but I have to guess also) malloc(3) actually returns.

You are casting that int 32bit value (already incorrect) to a 64bit pointer (far more incorrect, but I have to guess...), making any warning about type conversions between integer values and pointers to dissapear, and be silenced when you put the cast (the compiler assumes that, as a wise programmer you are, you have put the cast there on purpose, and that you know what you are doing)

The first (undefined behaviour) returned value is being (undefined behaviour) just cut to 32 bit, and then converted (from int to char *, with more undefined behaviour) to be used in your code.  This makes the original pointer returned from malloc(3) to be completely different value when reinterpreted and cast to (char *).  This makes your pointers to point to a different place, and break your program on execution.

Your code should be something like (again, a snippet has to be used, as your code is not complete):

```<code>#include <stdlib.h> /* for malloc() */

/* ... */

char *arr[rownum2];

for (i = 0; i < rownum2; i++) {
    arr[i] = malloc(colnum); /* sizeof(char) is always 1 */
</code>```

I need finally to do you a recommendation:

Please, read (and follow) the how to create a minimal, verifiable example page, as your probable missing #include error, is something I had to guess.... Posting snippets of code makes many times your mistakes to go away, and we have to guess what can be happening here.  This is the most important thing you have to learn from this answer.  Post complete, compilable and verifiable code (that is, code that you can check fails, before posting, not a snippet you selected where you guess the problem can be).  The code you posted does allow nobody to verify why it can be failing, because it must be completed (and repaired, probably) to make it executable.

Body:
I'm trying to create a 2D array that will store be able to store each character of a .txt file as an element in the 2D array.

How do I dynamically allocate space for it?

This what I've done so far to malloc it. (this was copied of GeeksForGeeks)

char *arr[rownum2];

for (i = 0; i < rownum2; i++) {
    arr[i] = (char *)malloc(colnum * sizeof(char));

However, I think this is the source of serious memory related issues later on in my program, and I've also been told some parts of this are unnecessary.

Can I please get the most suitable way to dynamically allocate memory for the 2D array in this specific scenario?

Body:
The only serious problem I see in your code is that you are casting the returned value of malloc(3), and probably you have forgotten to #include <stdlib.h> also (this is a dangerous cocktail), and this way, you are destroying the returned value of the call with the cast you put before malloc(3).  Let me explain:

First, you have (or haven't, but I have to guess) a 64bit architecture (as it is common today) and pointers are 64bit wide in your system, while int integers are 32bit wide.

You have probably forgotten to #include <stdlib.h> in your code (which is something I have to guess also), so the compiler is assuming that malloc(3) is actually a function returning int (this is legacy in C, if you don't provide a prototype for a function external to the compilation unit), so the compiler is generating code to get just a 32 bit value from the malloc(3) function, and not the 64bit pointer that (probably, but I have to guess also) malloc(3) actually returns.

You are casting that int 32bit value (already incorrect) to a 64bit pointer (far more incorrect, but I have to guess...), making any warning about type conversions between integer values and pointers to dissapear, and be silenced when you put the cast (the compiler assumes that, as a wise programmer you are, you have put the cast there on purpose, and that you know what you are doing)

The first (undefined behaviour) returned value is being (undefined behaviour) just cut to 32 bit, and then converted (from int to char *, with more undefined behaviour) to be used in your code.  This makes the original pointer returned from malloc(3) to be completely different value when reinterpreted and cast to (char *).  This makes your pointers to point to a different place, and break your program on execution.

Your code should be something like (again, a snippet has to be used, as your code is not complete):

#include <stdlib.h> /* for malloc() */

/* ... */

char *arr[rownum2];

for (i = 0; i < rownum2; i++) {
    arr[i] = malloc(colnum); /* sizeof(char) is always 1 */

I need finally to do you a recommendation:

Please, read (and follow) the how to create a minimal, verifiable example page, as your probable missing #include error, is something I had to guess.... Posting snippets of code makes many times your mistakes to go away, and we have to guess what can be happening here.  This is the most important thing you have to learn from this answer.  Post complete, compilable and verifiable code (that is, code that you can check fails, before posting, not a snippet you selected where you guess the problem can be).  The code you posted does allow nobody to verify why it can be failing, because it must be completed (and repaired, probably) to make it executable.


问:
SwiftUI - ForEach - Type '_' has no member 'name'
I'm am trying to ForEach over a String Array inside of a Class and receiving an error:
Type '_' has no member 'name'

I'm trying to model off what I read in this tutorial and don't understand why mine is failing to compile.
https://www.hackingwithswift.com/books/ios-swiftui/working-with-identifiable-items-in-swiftui

```<code>struct StatisticItem: Codable {
    let name: String
    let startValue: Int
    let modifier: Int
}

class Statistics: ObservableObject {
    let statisticsNames = ["One", "Two"]
    @Published var statList: [StatisticItem]

    init() {
        self.statList = [];
        for statisticsName in statisticsNames {
            self.statList.append(StatisticItem(name: statisticsName, startValue:  Int.random(in: 20 ... 100), modifier: 0))
        }
    }
}

struct ContentView: View {
    @ObservedObject var statistics = Statistics()

    var body: some View {
        Form {
            List {
                // Error shows up on this line: Type '_' has no member 'name'
                ForEach(statistics.statList, id:\.name) { stat in
                    TextField(stat.name)
                }
            }
        }
    }
}
</code>```

答:
First of all your model needs to be modifiable (so used var instead of let)

```<code>struct StatisticItem: Codable {
    var name: String
    var startValue: Int
    var modifier: Int
}
</code>```

Second, TextField requires Binding, so it should be like below

```<code>ForEach(Array(statistics.statList.enumerated()), id:\.1.name) { (i, stat) in
    TextField("", text: self.$statistics.statList[i].name)
}
</code>```

Body:
I'm am trying to ForEach over a String Array inside of a Class and receiving an error:
Type '_' has no member 'name'

I'm trying to model off what I read in this tutorial and don't understand why mine is failing to compile.
https://www.hackingwithswift.com/books/ios-swiftui/working-with-identifiable-items-in-swiftui

struct StatisticItem: Codable {
    let name: String
    let startValue: Int
    let modifier: Int
}

class Statistics: ObservableObject {
    let statisticsNames = ["One", "Two"]
    @Published var statList: [StatisticItem]

    init() {
        self.statList = [];
        for statisticsName in statisticsNames {
            self.statList.append(StatisticItem(name: statisticsName, startValue:  Int.random(in: 20 ... 100), modifier: 0))
        }
    }
}

struct ContentView: View {
    @ObservedObject var statistics = Statistics()

    var body: some View {
        Form {
            List {
                // Error shows up on this line: Type '_' has no member 'name'
                ForEach(statistics.statList, id:\.name) { stat in
                    TextField(stat.name)
                }
            }
        }
    }
}

Body:
First of all your model needs to be modifiable (so used var instead of let)

struct StatisticItem: Codable {
    var name: String
    var startValue: Int
    var modifier: Int
}

Second, TextField requires Binding, so it should be like below

ForEach(Array(statistics.statList.enumerated()), id:\.1.name) { (i, stat) in
    TextField("", text: self.$statistics.statList[i].name)
}


问:
Using Hist function to build series of 1D histograms in Python 3d plot
I am using pythons hist function to generate 1d histograms each linked to a given experiment.
Now I understand that the Hist function allows one to plot multiple histograms on the same x axis for comparison. I normally use something akin to the following for this purpose and the result is a very nice plot where x1,x2 and x3 are defined as follows
x1 = lengths expt1
x2 = lengths expt2
x3 = lengths expt3

```<code>P.figure()
n, bins, patches = P.hist( [x0,x1,x2], 10, weights=[w0, w1, w2], histtype='bar')
P.show()
</code>```

I was hoping to try achieve a 3d effect however and therefore I ask dose anyone know if it is it possible to have each unique histogram offset from the other in the y plane by a given unit thus generating a 3d effect.

I would appreciate any help on this .

答:
I believe you just want matplotlib.pyplot.bar3d.

```<code>import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

x0, x1, x2 = [np.random.normal(loc=loc, size=100) for loc in [1, 2, 3]]

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

yspacing = 1
for i, measurement in enumerate([x0, x1, x2]):
    hist, bin_edges = np.histogram(measurement, bins=10)
    dx = np.diff(bin_edges)
    dy = np.ones_like(hist)
    y = i * (1 + yspacing) * np.ones_like(hist)
    z = np.zeros_like(hist)
    ax.bar3d(bin_edges[:-1], y, z, dx, dy, hist, color='b',
            zsort='average', alpha=0.5)

plt.show()
</code>```

Body:
I am using pythons hist function to generate 1d histograms each linked to a given experiment.
Now I understand that the Hist function allows one to plot multiple histograms on the same x axis for comparison. I normally use something akin to the following for this purpose and the result is a very nice plot where x1,x2 and x3 are defined as follows
x1 = lengths expt1
x2 = lengths expt2
x3 = lengths expt3

P.figure()
n, bins, patches = P.hist( [x0,x1,x2], 10, weights=[w0, w1, w2], histtype='bar')
P.show()

I was hoping to try achieve a 3d effect however and therefore I ask dose anyone know if it is it possible to have each unique histogram offset from the other in the y plane by a given unit thus generating a 3d effect.

I would appreciate any help on this .

Body:
I believe you just want matplotlib.pyplot.bar3d.

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

x0, x1, x2 = [np.random.normal(loc=loc, size=100) for loc in [1, 2, 3]]

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

yspacing = 1
for i, measurement in enumerate([x0, x1, x2]):
    hist, bin_edges = np.histogram(measurement, bins=10)
    dx = np.diff(bin_edges)
    dy = np.ones_like(hist)
    y = i * (1 + yspacing) * np.ones_like(hist)
    z = np.zeros_like(hist)
    ax.bar3d(bin_edges[:-1], y, z, dx, dy, hist, color='b',
            zsort='average', alpha=0.5)

plt.show()


问:
UIBezierPath not equally fat everywhere and cut off
I am trying to draw a line with a smooth quadratic curve attached to its end. Therefore, I am using this code:

```<code>import Foundation
import UIKit

class IndicatingView: UIView {
    var path: UIBezierPath!

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    func createLineWithCurve() {
        path = UIBezierPath()

        path.move(to: CGPoint(x: 0, y: 0))

        path.addLine(to: CGPoint(x: 0, y: self.frame.height - self.frame.width))

        path.addQuadCurve(to: CGPoint(x: self.frame.width, y: self.frame.height), controlPoint: CGPoint(x: 0, y: self.frame.height))
    }

    override func draw(_ rect: CGRect) {
        self.createLineWithCurve()

        path.lineWidth = 3
        // Specify a border (stroke) color.
        UIColor.purple.setStroke()
        path.stroke()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
</code>```

And the output I get looks quite good already:

However, as you can see, the quad-curve is fatter than the normal line. Also, the quad-curve seems to be cut off at the bottom. How can I fix that? I want the path to be completely smooth without looking fatter at some points or being cut-off somehow.

Thanks in advance for your help :)

答:
The problem is that your path is getting clipped by the bounds of the view. For example, in your vertical stroke starting at 0, 0, half of the path’s vertical stroke will fall outside of the left edge of the view.

You should use insetBy(dx:dy:) to inset the stroked path by half the line width, which will ensure the whole stroke will fall within the bounds of the view. And then use minX, maxX, etc. of that resulting inset CGRect to figure out the various CGPoint for your path.

For example:

```<code>class IndicatingView: UIView {
    func lineWithCurve() -> UIBezierPath {
        let lineWidth: CGFloat = 3
        let rect = bounds.insetBy(dx: lineWidth / 2, dy: lineWidth / 2)

        let path = UIBezierPath()
        path.lineWidth = lineWidth
        path.lineCapStyle = .square

        path.move(to: CGPoint(x: rect.minX, y: rect.minY))
        path.addLine(to: CGPoint(x: rect.minX, y: rect.maxY - rect.width))
        path.addQuadCurve(to: CGPoint(x: rect.maxX, y: rect.maxY), controlPoint: CGPoint(x: rect.minX, y: rect.maxY))

        return path
    }

    override func draw(_ rect: CGRect) {
        UIColor.purple.setStroke()
        lineWithCurve().stroke()
    }
}
</code>```

That yields:

Body:
I am trying to draw a line with a smooth quadratic curve attached to its end. Therefore, I am using this code:

import Foundation
import UIKit

class IndicatingView: UIView {
    var path: UIBezierPath!

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    func createLineWithCurve() {
        path = UIBezierPath()

        path.move(to: CGPoint(x: 0, y: 0))

        path.addLine(to: CGPoint(x: 0, y: self.frame.height - self.frame.width))

        path.addQuadCurve(to: CGPoint(x: self.frame.width, y: self.frame.height), controlPoint: CGPoint(x: 0, y: self.frame.height))
    }

    override func draw(_ rect: CGRect) {
        self.createLineWithCurve()

        path.lineWidth = 3
        // Specify a border (stroke) color.
        UIColor.purple.setStroke()
        path.stroke()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

And the output I get looks quite good already:

However, as you can see, the quad-curve is fatter than the normal line. Also, the quad-curve seems to be cut off at the bottom. How can I fix that? I want the path to be completely smooth without looking fatter at some points or being cut-off somehow.

Thanks in advance for your help :)

Body:
The problem is that your path is getting clipped by the bounds of the view. For example, in your vertical stroke starting at 0, 0, half of the path’s vertical stroke will fall outside of the left edge of the view.

You should use insetBy(dx:dy:) to inset the stroked path by half the line width, which will ensure the whole stroke will fall within the bounds of the view. And then use minX, maxX, etc. of that resulting inset CGRect to figure out the various CGPoint for your path.

For example:

class IndicatingView: UIView {
    func lineWithCurve() -> UIBezierPath {
        let lineWidth: CGFloat = 3
        let rect = bounds.insetBy(dx: lineWidth / 2, dy: lineWidth / 2)

        let path = UIBezierPath()
        path.lineWidth = lineWidth
        path.lineCapStyle = .square

        path.move(to: CGPoint(x: rect.minX, y: rect.minY))
        path.addLine(to: CGPoint(x: rect.minX, y: rect.maxY - rect.width))
        path.addQuadCurve(to: CGPoint(x: rect.maxX, y: rect.maxY), controlPoint: CGPoint(x: rect.minX, y: rect.maxY))

        return path
    }

    override func draw(_ rect: CGRect) {
        UIColor.purple.setStroke()
        lineWithCurve().stroke()
    }
}

That yields:


问:
How to navigate vscode save changes before closing dialog without using mouse?
In macOS vscode, when I close a file that has some changes made to it, I get a dialog on top. How do i navigate the buttons here with just my keyboard?

The screenshot doesn't show it but it defaults to the Save button.

答:
I don't know if VS Code follows normal Mac conventions but, if it does, Return should select the default button (Save, presumably); Escape should cancel; and Command-D or possibly Command-Delete should select Don't Save.

Also, if you have System Preferences > Keyboard > Shortcuts > Full Keyboard Access set to "All controls", the Tab key should move focus among the buttons and Space will press the one with focus. If you don't normally have that set that way, Control-F7 will toggle it on.


问:
Unicode CSS Font Awesome Icons Rendering as Boxes in React
I am using the jPlayer example in a create-react-app. Here is a CodeSandbox showing the issue of font-awesome icon's rendering as boxes.

The icons render via css rules specifying content as unicode for  tags with the fa class.

I installed the font-awesome dependency which was in the jPlayer example's package.json. Then, I implemented an AudioPlayer component and used the skins provided by jPlayer. The component renders but the icons are all boxes, and I can see the unicode content in the source.

Here's an example of the project architecture. This is the play button in /src/AudioPlayer/AudioPlayer.jsx.

<Play>{/* Icon set in css */}</Play>

Then, the AudioPlayer is imported into App.jsx. App.jsx imports a stylesheet which has this relevant rule:

```<code>.fa, .fas, .far {
    font-family: FontAwesome !important;
}
</code>```

App.jsx is then rendered by index.js. Inside index.js, we import the audio player's stylesheets:

```<code>// Styles the jPlayer to look nice
import 'react-jplayer/dist/css/skins/sleek.min.css';
// Styles Play/Pause/Mute etc when icons (<i />) are used for them
import 'react-jplayer/dist/css/controls/iconControls.min.css';
</code>```

The rule for the play button in iconControls.css looks like this:

```<code>.jp-jplayer .jp-icon-controls .jp-play i:before {
  content: "\F04B";
  font-family: 'Font Awesome\ 5 Free';
  font-weight: 900;
}
</code>```

then within index.html's head I include the font-awesome CDN as a final attempt at fixing the boxes being rendered instead of font-awesome icons.

答:
Font characters show as open squares when:

The Unicode character specified doesn't exist in the font file.

The requested font file can't be found and there's no fallback specified.

Since its's Font Awesome, there's no fallback font AND the requested character doesn't exist in most fonts. So you get a double problem.

This almost always happens when the browser can't find the font file due to path issues. I'd look through your CSS to find where @font-face is requested and fix the path to match your project. I would guess this is in the player CSS file AND that it expect's a local file not from the CDN.

Also, be aware that Webpack sometimes moves files and updates paths found in CSS so you may need to move those to a "static" directory and change paths as needed.

Finally, you should check the name of the font to make sure it matches what you have available in your system. According to Font Awesome's Docs, it should be font-family: "Font Awesome 5 Free"; your's seems to have an extra back slash.

Body:
I am using the jPlayer example in a create-react-app. Here is a CodeSandbox showing the issue of font-awesome icon's rendering as boxes.

The icons render via css rules specifying content as unicode for  tags with the fa class.

I installed the font-awesome dependency which was in the jPlayer example's package.json. Then, I implemented an AudioPlayer component and used the skins provided by jPlayer. The component renders but the icons are all boxes, and I can see the unicode content in the source.

Here's an example of the project architecture. This is the play button in /src/AudioPlayer/AudioPlayer.jsx.

<Play>{/* Icon set in css */}</Play>

Then, the AudioPlayer is imported into App.jsx. App.jsx imports a stylesheet which has this relevant rule:

.fa, .fas, .far {
    font-family: FontAwesome !important;
}

App.jsx is then rendered by index.js. Inside index.js, we import the audio player's stylesheets:

// Styles the jPlayer to look nice
import 'react-jplayer/dist/css/skins/sleek.min.css';
// Styles Play/Pause/Mute etc when icons () are used for them
import 'react-jplayer/dist/css/controls/iconControls.min.css';

The rule for the play button in iconControls.css looks like this:

.jp-jplayer .jp-icon-controls .jp-play i:before {
  content: "\F04B";
  font-family: 'Font Awesome\ 5 Free';
  font-weight: 900;
}

then within index.html's head I include the font-awesome CDN as a final attempt at fixing the boxes being rendered instead of font-awesome icons.


问:
How to update state with the useState hook
I have a default state that looks like this:

```<code>const [selectedFilters, setSelectedFilters] = useState({movie: 'default' , species : 'default' , planet : 'default'});
</code>```

How do I update the movie value to something else. I tried this :

```<code>  const handleMovieChange  = (e) => {
    console.log(e.target.value)
    setSelectedFilters(prevState => ({ ...prevState, movie : e.target.value}));
  }
</code>```

However when I change values this gives me :

```<code>×
TypeError: Cannot read property 'value' of null
(anonymous function)
C:/Users/klmaa/OneDrive/Bureaublad/swcase/client/src/App.js:48
  45 |
  46 |  const handleMovieChange  = (e) => {
  47 |    console.log(e.target.value)
> 48 |    setSelectedFilters(prevState => ({ ...prevState, movie : e.target.value}));
     | ^  49 |  }
  50 |
  51 |  console.log(selectedFilters);
</code>```

答:
BTW, Based on React documentation, Its advised to split into multiple state variables. https://reactjs.org/docs/hooks-state.html#tip-using-multiple-state-variables.

Following should work for your scenario.

```<code>const [movie, setMovie] = useState("default");
const [species, setSpecies] = useState("default");
const [planet, setPlanet] = useState("default");

const handleMovieChange = e => {
  console.log(e.target.value);
  setMovie(e.target.value);
};
</code>```

Body:
I have a default state that looks like this:

const [selectedFilters, setSelectedFilters] = useState({movie: 'default' , species : 'default' , planet : 'default'});

How do I update the movie value to something else. I tried this :

  const handleMovieChange  = (e) => {
    console.log(e.target.value)
    setSelectedFilters(prevState => ({ ...prevState, movie : e.target.value}));
  }

However when I change values this gives me :

×
TypeError: Cannot read property 'value' of null
(anonymous function)
C:/Users/klmaa/OneDrive/Bureaublad/swcase/client/src/App.js:48
  45 |
  46 |  const handleMovieChange  = (e) => {
  47 |    console.log(e.target.value)
> 48 |    setSelectedFilters(prevState => ({ ...prevState, movie : e.target.value}));
     | ^  49 |  }
  50 |
  51 |  console.log(selectedFilters);

Body:
BTW, Based on React documentation, Its advised to split into multiple state variables. https://reactjs.org/docs/hooks-state.html#tip-using-multiple-state-variables.

Following should work for your scenario.

const [movie, setMovie] = useState("default");
const [species, setSpecies] = useState("default");
const [planet, setPlanet] = useState("default");

const handleMovieChange = e => {
  console.log(e.target.value);
  setMovie(e.target.value);
};


问:
Modelling Cassandra Data Struncture for both real-time and search from all?
My project serves both real-time data and past data. It works like feed, so it shows real-time data through socket and past data(if scroll down) through REST api. To get real-time data efficiently, I set date as partition key and time as clustering key. For real-time service, I think this data structure is well modeled. But I also have to get limited number of recent datas(like pagination), which should able to show whole data if requested. To serve data like recent 0~20 / 20~40 / 40~60 through REST api calls, my data-serving server has to remember what it showed before to load next 20 datas continuously, as bookmark. If it was SQL I would use IDs or page&offset things but I cannot do that with Cassandra. So I tried:

```<code>SELECT * FROM examples WHERE date<='DATEMARK' AND create_at < 'TIMEMARK' AND entities CONTAINS 'something' limit 20 ALLOW FILTERING;
</code>```

But since date is the partition key, I cannot use comparison operation >, <. The past data could be created very far from now.

Can I satisfy my real-time+past requirements with Cassandra? I wonder if I have to make another DB for accessing past data.

答:
we have been using Cassandra extensively for showing real-time + past data. I request you not to use allow filtering option in Cassandra as it's not a good practice. Try to make your schema properly such that you need not required to jump the columns. Suppose you have a schema:

Created_date | Created_time | user_id | Country | Name | Activity

In this schema, you are considering Created_date,created_time,user_id, country as a primary key but you want the user_id of a particular country. In this case, even though you have considered Country column as a primary key you can't query like:

"SELECT * from table where Created_date='2020-02-14' and Country ='india' allow filtering ";

If your query in this pattern you will lose data in your resultset and will get errors when working with big data. Or you'll be using the allow filtering option which is not suggested. So, you need to change the structure of your schema.

Created_date | Country | City | Created_time | user_id | Name | Activity

"SELECT * from table where created_date='2020-02-14' and country='india'";
Using this structure will give you a very consistent result and you will never face any errors. Suppose you want to get all the data for the last seven days. In that case use loop and traverse through the results of each day and store it into some data structure. Hope you understand.

Body:
My project serves both real-time data and past data. It works like feed, so it shows real-time data through socket and past data(if scroll down) through REST api. To get real-time data efficiently, I set date as partition key and time as clustering key. For real-time service, I think this data structure is well modeled. But I also have to get limited number of recent datas(like pagination), which should able to show whole data if requested. To serve data like recent 0~20 / 20~40 / 40~60 through REST api calls, my data-serving server has to remember what it showed before to load next 20 datas continuously, as bookmark. If it was SQL I would use IDs or page&offset things but I cannot do that with Cassandra. So I tried:

SELECT * FROM examples WHERE date<='DATEMARK' AND create_at < 'TIMEMARK' AND entities CONTAINS 'something' limit 20 ALLOW FILTERING;

But since date is the partition key, I cannot use comparison operation >, <. The past data could be created very far from now.

Can I satisfy my real-time+past requirements with Cassandra? I wonder if I have to make another DB for accessing past data.


答:
```<code>if(preg_match("~\d{5}~", $searchval)) {
</code>```

Left code stays the same

Title: Deprecated: Function ereg()

Body:
Possible Duplicate:

  Function ereg() is deprecated

I understand that in the new version of PHP ereg is deprecated:

Deprecated: Function ereg() is deprecated

The code below worked fine in the old PHP. So I replaced ereg with preg_match and I am now getting the following error:

Warning: preg_match() [function.preg-match]: Unknown modifier '{' in

Here is my code...

if (!empty($searchval))
{
    if(ereg("[0-9]{5}", $searchval)) {
        $zip = $searchval;
    }
    else {
        $city = $searchval;
    }
} else
{
    $error .= "
Please enter zip
";
    $zip = false;
}

Body:
if(preg_match("~\d{5}~", $searchval)) {

Left code stays the same


问:
Javascript - Create a currying function returning the list of parameters
I'm trying to create a currying function returning the list of parameters but I don't how to make it.
This is my code :

const getParameters = arg => {
  const parameters = [];

  const innerFunction = arg => {
    parameters.push(arg);
    return innerFunction;
  };
  return innerFunction(arg);
};

getParameters(1)(2)(5); // => expected value [1,2,5]
getParameters(1)(2)(5)(20); // => expected value [1,2,5,20]
```

答:
const getParameters = a => b => c => [a, b, c];

console.log(getParameters(1)(2)(5));```


问:
Different user types table laravel
i have a problem on my project on my user table im using an usertype it has a Student Teacher Admin and i want them to have a separate table with out using an eloquent just a simple query/code or an simple tutorial to help my problem..

controller

```<code>public function index()
{
    $users = User::find();
    return view('teacherpage.teacher_table',  compact('users'));
}
</code>```

teacher_table

```<code> @foreach ($users as $position)

                <tbody>
                    <tr>
                        <td>{{ $position->id}}</td>
                        <td>{{ $position->first_name}}</td>
                        <td>{{ $position->last_name}}</td>
                        <td>{{ $position->contact}}</td>
                        <td>{{ $position->department}}</td>

                        <td>{{ $position->usertype}}</td>

                        <td>{{ $position->email}}</td>

                        <th>
                            <a href="{{action('AdminTableController@edit',['id' =>$position->id])}}" class="btn btn-success">Edit </a>
                    </th>

                            </tr>
                        </tbody>
                        @endforeach
</code>```

**i want to view the Student usertype i don't know please help me **

答:
Adding an additional model makes it possible to assign a type/role to a user. Start by creating the Role model:

```<code>php artisan make:model Role -m
</code>```

and then editing the following migration: database/migrations/*_*_creates_roles_table.php to have the following up method:

```<code>public function up()
{
    Schema::create('roles', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        $table->timestamps();
    });

    Schema::table('users', function (Blueprint $table) {
        $table->unsignedBigInteger('role_id')->nullable();

        $table->foreign('role_id')->references('id')->on('roles');
    });
}
</code>```

The Role model can now be associated with a User by adding a relation to the user model:

app/User.php

```<code>class User extends Authenticatable
{
    use Notifiable;

    protected $fillable = [
        'name', 'email', 'password',
    ];

    protected $hidden = [
        'password', 'remember_token',
    ];

    public function role(){
        return $this->hasOne(Role::class);
    }
}

</code>```

after migrating the database(php artisan migrate) the following code can be used:

```<code>public function index()
{
    $users = User::with('role')->get();
    return view('teacherpage.teacher_table',  compact('users'));
}
</code>```

Title: Different user types table laravel

Body:
i have a problem on my project on my user table im using an usertype it has a Student Teacher Admin and i want them to have a separate table with out using an eloquent just a simple query/code or an simple tutorial to help my problem..

controller

public function index()
{
    $users = User::find();
    return view('teacherpage.teacher_table',  compact('users'));
}

teacher_table

 @foreach ($users as $position)

                        {{ $position->id}}
                        {{ $position->first_name}}
                        {{ $position->last_name}}
                        {{ $position->contact}}
                        {{ $position->department}}

                        {{ $position->usertype}}

                        {{ $position->email}}

                            $position->id])}}" class="btn btn-success">Edit

                        @endforeach

**i want to view the Student usertype i don't know please help me **

Body:
Adding an additional model makes it possible to assign a type/role to a user. Start by creating the Role model:

php artisan make:model Role -m

and then editing the following migration: database/migrations/*_*_creates_roles_table.php to have the following up method:

public function up()
{
    Schema::create('roles', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        $table->timestamps();
    });

    Schema::table('users', function (Blueprint $table) {
        $table->unsignedBigInteger('role_id')->nullable();

        $table->foreign('role_id')->references('id')->on('roles');
    });
}

The Role model can now be associated with a User by adding a relation to the user model:

app/User.php

class User extends Authenticatable
{
    use Notifiable;

    protected $fillable = [
        'name', 'email', 'password',
    ];

    protected $hidden = [
        'password', 'remember_token',
    ];

    public function role(){
        return $this->hasOne(Role::class);
    }
}

after migrating the database(php artisan migrate) the following code can be used:

public function index()
{
    $users = User::with('role')->get();
    return view('teacherpage.teacher_table',  compact('users'));
}


问:
Find index of number if item exists in ObservableCollection in C#/WPF
In the following code I'm checking if a certain item exists in an ObservableCollection and if it does, I want to grab its index so I can move that item to the top but I cannot figure it out.

My object:

```<code>public class RecentFile
{
    public string FileName { get; set; }
    public string DateAdded { get; set; }
}
</code>```

Cod for finding index of item:

```<code>if (recentFilesObservableCollection.Any(f => f.FileName == "MyFileName")) {

    foreach (RecentFile file in recentFilesObservableCollection) {
        if (file.FileName == "MyFileName") {
            var x = RecentFilesDataGrid[(recentFilesObservableCollection.IndexOf(file)];
        }
    }
}
</code>```

What would be the best way to get the index number if the item exists?

Ultimately what I need to do is...

Check if item exists

If it does move it to the top of the list

答:
You can create extension methods similar to List<T>.FindIndex(...) methods:

public static class ObservableCollectionExtensions
{
    public static int FindIndex<T>(this ObservableCollection<T> ts, Predicate<T> match)
    {
        return ts.FindIndex(0, ts.Count, match);
    }

    public static int FindIndex<T>(this ObservableCollection<T> ts, int startIndex, Predicate<T> match)
    {
        return ts.FindIndex(startIndex, ts.Count, match);
    }

    public static int FindIndex<T>(this ObservableCollection<T> ts, int startIndex, int count, Predicate<T> match)
    {
        if (startIndex < 0) startIndex = 0;
        if (count > ts.Count) count = ts.Count;

        for (int i = startIndex; i < count; i++)
        {
            if (match(ts[i])) return i;
        }

        return -1;
    }
}
```

<p>Usage:</p>

```int index = recentFilesObservableCollection.FindIndex(f => f.FileName == "MyFileName");
if (index > 0)
{
    // Move it to the top of the list
    recentFilesObservableCollection.Move(index, 0);
}
```

Body:
In the following code I'm checking if a certain item exists in an ObservableCollection and if it does, I want to grab its index so I can move that item to the top but I cannot figure it out.

My object:

public class RecentFile
{
    public string FileName { get; set; }
    public string DateAdded { get; set; }
}

Cod for finding index of item:

if (recentFilesObservableCollection.Any(f => f.FileName == "MyFileName")) {

    foreach (RecentFile file in recentFilesObservableCollection) {
        if (file.FileName == "MyFileName") {
            var x = RecentFilesDataGrid[(recentFilesObservableCollection.IndexOf(file)];
        }
    }
}

What would be the best way to get the index number if the item exists?

Ultimately what I need to do is...

Check if item exists

If it does move it to the top of the list

Body:
You can create extension methods similar to List<T>.FindIndex(...) methods:

public static class ObservableCollectionExtensions
{
    public static int FindIndex<T>(this ObservableCollection<T> ts, Predicate<T> match)
    {
        return ts.FindIndex(0, ts.Count, match);
    }

    public static int FindIndex<T>(this ObservableCollection<T> ts, int startIndex, Predicate<T> match)
    {
        return ts.FindIndex(startIndex, ts.Count, match);
    }

    public static int FindIndex<T>(this ObservableCollection<T> ts, int startIndex, int count, Predicate<T> match)
    {
        if (startIndex < 0) startIndex = 0;
        if (count > ts.Count) count = ts.Count;

        for (int i = startIndex; i < count; i++)
        {
            if (match(ts[i])) return i;
        }

        return -1;
    }
}

Usage:

int index = recentFilesObservableCollection.FindIndex(f => f.FileName == "MyFileName");
if (index > 0)
{
    // Move it to the top of the list
    recentFilesObservableCollection.Move(index, 0);
}