问:
Need to access variable defined in a function. Is nested loop the solution?
I have the following code and need to access the variable "density" and put it in a popup. Density is defined in the mapCities function, but the markers I'm adding and the popups I'm creating are created in a for loop outside of the map cities function resulting in a ReferenceError: density is not defined
index.html:151:42. This is error is expected. I just don't know how to access that density variable. Should it be doe with a nested loop?</p>

```<code>              function mapCities(units) {
                for (var i = 0; i < cities.length; i++) {
                    var cityName = cities[i];
                    var cityNumPeeps = cityPops[i];
                    var cityZone = cityAreas[i];
                    var cityXY = cityCoords[i];
                    var density = calcPopDensity(cityNumPeeps, cityZone, units); // call calcPopDensity passing population, cityZone and units as arguments

                    console.log(density);
                }
            };

            function calcPopDensity(cityNumPeeps, cityZone, units) {
                if (units == "miles") {
                    return cityNumPeeps / cityZone // calculate population density in miles and return it

                } else if (units == "km") {
                    return cityNumPeeps / cityZone * 1.60934 // calculate population density in miles and return it

                }

            };

            for (var i = 0; i < cities.length; i++) {
                var cityName = cities[i];
                var cityNumPeeps = cityPops[i];
                var cityZone = cityAreas[i];
                var cityXY = cityCoords[i];
                var popup = `<b>${cityName}</b><br>
                    <b>population</b>: ${density}<br>`
                L.marker(cityXY).addTo(map) // add marker to map based on cityCoords array and bind to popup
                    .bindPopup(popup);
                console.log(popup)
                //if statement determines units to place in popup text
                if (units == "miles") {
                    popup += `miles`; // add text if if var density returns miles
                } else if (units == "km")
                    popup += `kilometers`; // add text if if var density returns kilometers
                L.marker(cityXY).addTo(map) // add popup again based on if statement
                    .bindPopup(popup);
                console.log(popup)

            }
```

</code>```

答:
Just create a variable for the density local to the for-loop where you need it.
The above density variable is out of scope so you won't be able to use it as is.

```<code>for (var i = 0; i < cities.length; i++) {
    var cityName = cities[i];
    var cityNumPeeps = cityPops[i];
    var cityZone = cityAreas[i];
    var cityXY = cityCoords[i];

    var density = calcPopDensity(cityNumPeeps, cityZone, units);

    var popup = `<b>${cityName}</b><br>
        <b>population</b>: ${density}<br>`
    L.marker(cityXY).addTo(map) // add marker to map based on cityCoords array and bind to popup
        .bindPopup(popup);
    console.log(popup)
    //if statement determines units to place in popup text
    if (units == "miles") {
        popup += `miles`; // add text if if var density returns miles
    } else if (units == "km")
        popup += `kilometers`; // add text if if var density returns kilometers
    L.marker(cityXY).addTo(map) // add popup again based on if statement
        .bindPopup(popup);
    console.log(popup)
}
</code>```

Body:
I have the following code and need to access the variable "density" and put it in a popup. Density is defined in the mapCities function, but the markers I'm adding and the popups I'm creating are created in a for loop outside of the map cities function resulting in a ReferenceError: density is not defined
index.html:151:42. This is error is expected. I just don't know how to access that density variable. Should it be doe with a nested loop?

              function mapCities(units) {
                for (var i = 0; i < cities.length; i++) {
                    var cityName = cities[i];
                    var cityNumPeeps = cityPops[i];
                    var cityZone = cityAreas[i];
                    var cityXY = cityCoords[i];
                    var density = calcPopDensity(cityNumPeeps, cityZone, units); // call calcPopDensity passing population, cityZone and units as arguments

                    console.log(density);
                }
            };

            function calcPopDensity(cityNumPeeps, cityZone, units) {
                if (units == "miles") {
                    return cityNumPeeps / cityZone // calculate population density in miles and return it

                } else if (units == "km") {
                    return cityNumPeeps / cityZone * 1.60934 // calculate population density in miles and return it

                }

            };

            for (var i = 0; i < cities.length; i++) {
                var cityName = cities[i];
                var cityNumPeeps = cityPops[i];
                var cityZone = cityAreas[i];
                var cityXY = cityCoords[i];
                var popup = `${cityName}

                    population: ${density}
`
                L.marker(cityXY).addTo(map) // add marker to map based on cityCoords array and bind to popup
                    .bindPopup(popup);
                console.log(popup)
                //if statement determines units to place in popup text
                if (units == "miles") {
                    popup += `miles`; // add text if if var density returns miles
                } else if (units == "km")
                    popup += `kilometers`; // add text if if var density returns kilometers
                L.marker(cityXY).addTo(map) // add popup again based on if statement
                    .bindPopup(popup);
                console.log(popup)

            }
```

Body:
Just create a variable for the density local to the for-loop where you need it.
The above density variable is out of scope so you won't be able to use it as is.

for (var i = 0; i < cities.length; i++) {
    var cityName = cities[i];
    var cityNumPeeps = cityPops[i];
    var cityZone = cityAreas[i];
    var cityXY = cityCoords[i];

    var density = calcPopDensity(cityNumPeeps, cityZone, units);

    var popup = `<b>${cityName}</b><br>
        <b>population</b>: ${density}<br>`
    L.marker(cityXY).addTo(map) // add marker to map based on cityCoords array and bind to popup
        .bindPopup(popup);
    console.log(popup)
    //if statement determines units to place in popup text
    if (units == "miles") {
        popup += `miles`; // add text if if var density returns miles
    } else if (units == "km")
        popup += `kilometers`; // add text if if var density returns kilometers
    L.marker(cityXY).addTo(map) // add popup again based on if statement
        .bindPopup(popup);
    console.log(popup)
}


来源: stackexchange

问:
PrimeFaces InputNumberRenderer Exception
I'm using PrimeFaces in my Java code as follows:

```<code>HtmlForm form = (HtmlForm) event.getComponent();

InputNumber inputNumber = new InputNumber();
inputNumber.setId("input");

form.getChildren().add(inputNumber);
</code>```

And it gives the following error:

java.lang.NoSuchMethodError:
  org.primefaces.component.inputnumber.InputNumberRenderer.renderAccessibilityAttributes(Ljavax/faces/context/FacesContext;Ljavax/faces/component/UIInput;)V

What could it be caused by?

答:
This is how I solved the issue.

```<code>HtmlForm form = (HtmlForm) event.getComponent();
InputNumber inputNumber = new InputNumber();

inputNumber.setId("input1");
ValueExpression inputNumberValue = ef.createValueExpression(
context.getELContext(), "#{ruleManagedBean.inputNumber}",
Double.class);
inputNumber.setValueExpression("value", inputNumberValue);

form.getChildren().add(inputNumber);
</code>```

And in xhtml file:

```<code><h:form id="form">
    <f:event type="postAddToView"
        listener="#{ruleManagedBean.populateForm}" />
        <pe:blockUI></pe:blockUI>
</h:form>
</code>```

Note:Primefaces Extension(PE) 4.0 jar is used for InputNumber. So I had to include an empty PE tag(I used pe:blockUI) because it seems like PE js files are not included unless it has at least one PE tag.

ContentLicense: CC BY-SA 4.0

Body:
I'm using PrimeFaces in my Java code as follows:

HtmlForm form = (HtmlForm) event.getComponent();

InputNumber inputNumber = new InputNumber();
inputNumber.setId("input");

form.getChildren().add(inputNumber);

And it gives the following error:

java.lang.NoSuchMethodError:
  org.primefaces.component.inputnumber.InputNumberRenderer.renderAccessibilityAttributes(Ljavax/faces/context/FacesContext;Ljavax/faces/component/UIInput;)V

What could it be caused by?

Body:
This is how I solved the issue.

HtmlForm form = (HtmlForm) event.getComponent();
InputNumber inputNumber = new InputNumber();

inputNumber.setId("input1");
ValueExpression inputNumberValue = ef.createValueExpression(
context.getELContext(), "#{ruleManagedBean.inputNumber}",
Double.class);
inputNumber.setValueExpression("value", inputNumberValue);

form.getChildren().add(inputNumber);

And in xhtml file:

<h:form id="form">
    <f:event type="postAddToView"
        listener="#{ruleManagedBean.populateForm}" />
        <pe:blockUI></pe:blockUI>
</h:form>

Note:Primefaces Extension(PE) 4.0 jar is used for InputNumber. So I had to include an empty PE tag(I used pe:blockUI) because it seems like PE js files are not included unless it has at least one PE tag.


问:
Is there a way to use SQL Server 2019 and CDC (Change Data Capture) at the same time?
I am working on a project where I have to use CDC, catalog collation SQL_Latin1_General_CP1_CI_AS and a CS collation for data. I get an collation conflict error from sp_cdc_create_populate_stored_procs when enabling cdc for any table. This is called from other procedure "sys.sp_cdc_enable_table_internal" and again this is call from my own sql-script "sys.sp_cdc_enable_table". To me this seems like a bug but would appreciate if there's any new ideas how to implement production level workaround on this matter.</p>

答:
This is a documented limitation of Contained Databases.

Limitations

Partially contained databases do not allow the following
  features.

-Partially contained databases cannot use replication, change data
  capture, or change tracking.

-Numbered procedures

-Schema-bound objects that depend on built-in functions with collation
  changes

-Binding change resulting from collation changes, including references
  to objects, columns, symbols, or types.

-Replication, change data capture, and change tracking.

Contained Databases - Limitations

If you need a case-insensitive catalog collation along with a case-sensitive collation for data, you can set the column collation directly on your text columns instead of using the database's default collation.


问:
Google Spreadsheet MATCH for multiple strings
I am trying to find the formula to MATCH() for multiple strings. Normally I would just use the wildcard like MATCH("String1*String2";A:A) where String1 and String2 are two strings to be found in one cell of column A but these two could be separated with any other string but the wildcard does not work in this case.

A more complex version of the problem is when String1 and String2 could occur in any order inside one cell.

答:
try regex:</p>

```<code>=REGEXMATCH(A1, "string1|string2")
</code>```

Body:
try regex:

=REGEXMATCH(A1, "string1|string2")


问:
How to get different output from one click event in Angular with more than one component?
I have no idea how to display a pop-up window with various content using the same method. I have two components - first one contains a form with some info links.

form-component.html

```<code><a href="" (click)="openInfoPopup()">Info</a>
...
<a href="" (click)="openInfoPopup()">Info</a>
...
<a href="" (click)="openInfoPopup()">Info</a>
</code>```

form-component.ts

```<code>openInfoPopup() {
...
let dialogRef = dialog.open(MyDialogComponent, dialogConf)
}
</code>```

It works perfectly - openInfoPopup() opens my dialog as I want, but my poor knowlegde of Angular so far doesn't allow me to take the next step. Depending on which link you click, my popup should contain another text message. Clicking first link should open new dialog with first element of array below etc. In the second component, I created an array with my messages:

my-dialog-component.ts

```<code>infoArr = ["Text1", "Text2", "Text3", "Text4", "Text5", "Text6"];
</code>```

my-dialog-component.html

```<code><p *ngFor="let message of infoArr; let i = index"> {{ }} </p>
</code>```

What should I do to make it work? How can I transfer data from my array to form-component and what I need to insert into my-dialog-component.html interpolation?

答:
The first thing to do here is parameterise your openInfoPopup() calls. The parameter would be whatever the unique key is for the different types. I'll use a string for simplicity.

form-component.html

```<code><a href="" (click)="openInfoPopup('type1')">Info</a>
...
<a href="" (click)="openInfoPopup('type2')">Info</a>
...
<a href="" (click)="openInfoPopup('type3')">Info</a>
</code>```

form-component.ts

```<code>selectedType: string;

openInfoPopup(type: string): void {
  this.selectedType = type;

  // open dialog
}
</code>```

Once you know what the source of the event is, you can pass that information to the dialog.

Edit:

You've now clarified that you're using Angular Material.

In which case, you pass the key in via the open() function:

```<code>openInfoPopup(type: string) {
  this.selectedType = type;

  const dialogConf = new MatDialogConfig();
  dialogConf.width = "480px";
  let dialogRef = this.dialog.open(MyDialogComponent, {
    width: '480px',
    data: { type: this.selectedType }
  });
}
</code>```

From the docs, you can access injected information like this:

```<code>export class YourDialog {
  constructor(@Inject(MAT_DIALOG_DATA) public data: any) { }
}
</code>```

Body:
I have no idea how to display a pop-up window with various content using the same method. I have two components - first one contains a form with some info links.

form-component.html

Info
...
Info
...
Info

form-component.ts

openInfoPopup() {
...
let dialogRef = dialog.open(MyDialogComponent, dialogConf)
}

It works perfectly - openInfoPopup() opens my dialog as I want, but my poor knowlegde of Angular so far doesn't allow me to take the next step. Depending on which link you click, my popup should contain another text message. Clicking first link should open new dialog with first element of array below etc. In the second component, I created an array with my messages:

my-dialog-component.ts

infoArr = ["Text1", "Text2", "Text3", "Text4", "Text5", "Text6"];

my-dialog-component.html

 {{ }}

What should I do to make it work? How can I transfer data from my array to form-component and what I need to insert into my-dialog-component.html interpolation?

Body:
The first thing to do here is parameterise your openInfoPopup() calls. The parameter would be whatever the unique key is for the different types. I'll use a string for simplicity.

form-component.html

<a href="" (click)="openInfoPopup('type1')">Info</a>
...
<a href="" (click)="openInfoPopup('type2')">Info</a>
...
<a href="" (click)="openInfoPopup('type3')">Info</a>

form-component.ts

selectedType: string;

openInfoPopup(type: string): void {
  this.selectedType = type;

  // open dialog
}

Once you know what the source of the event is, you can pass that information to the dialog.

Edit:

You've now clarified that you're using Angular Material.

In which case, you pass the key in via the open() function:

openInfoPopup(type: string) {
  this.selectedType = type;

  const dialogConf = new MatDialogConfig();
  dialogConf.width = "480px";
  let dialogRef = this.dialog.open(MyDialogComponent, {
    width: '480px',
    data: { type: this.selectedType }
  });
}

From the docs, you can access injected information like this:

export class YourDialog {
  constructor(@Inject(MAT_DIALOG_DATA) public data: any) { }
}


问:
Unable to load script. Make sure you're either running a Metro server (run 'react-native start') or that your bundle 'index.android.bundle'
Running my project in android studio I get that error, I just installed everything and I followed everything step by step, I'm using genymotion as an emulator, and use react-native start from the root, check port 8081, disable instant run, everything which is the following link

Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release

答:
You can check your Metro server is on or not..?

do the following command in your cmd path on your server

open two cmd window do 2nd point and 3rd point another cmd window

check you localhost 8080 is running your browser chrome

like: localhost:8080

//----- then do this in your cmd path

D:para\Android\testing>react-native start --port=8081

D:para\Android\testing>react-native run-android --no-jetifier

That's it... check your mobile or emulator now show welcome to react...

Thank you.


问:
Pointer assignment does not work in recursive function
I have a binary tree program, when I am trying to traverse the tree for insertion in a recursive function pointer assignment does not seem to work. First things first here is the inserting function which is not working:

```<code>void append(Node* &curr, int val){

    if(curr==nullptr){
        Node* newNode = new Node(val);
        std::cout << "Created new Node with value: " << newNode->value << std::endl;
        curr = newNode;
        return;
    }
    if(curr->value > val){
        curr = curr->left;
        append(curr, val);
    }
    else{
        curr = curr->right;
        append(curr,val);
    }
}
</code>```

But when I tweak the same function like following, it seems to work just fine:

```<code>void append(Node* &curr, int val){
        if(curr==nullptr){
            Node* newNode = new Node(val);
            std::cout << "Created new Node with value: " << newNode->value << std::endl;
            curr = newNode;
            return;
        }
        if(curr->value > val){
            append(curr->left, val);
        }
        else{
            std::cout << "Right" << curr->value << std::endl;
            append(curr->right,val);
        }
    }
</code>```

I came to fix this after hours of work, and still can't understand why the first function does not work while the second one works as expected. Was hoping anyone can tell me why curr=curr->left is different than passing curr->left to the recursion.

答:
In this function implementation

```<code>void append(Node* &curr, int val){

    if(curr==nullptr){
        Node* newNode = new Node(val);
        std::cout << "Created new Node with value: " << newNode->value << std::endl;
        curr = newNode;
        return;
    }
    if(curr->value > val){
        curr = curr->left;
        append(curr, val);
    }
    else{
        curr = curr->right;
        append(curr,val);
    }
}
</code>```

As the pointer curr is passed by reference then in these statements

```<code>        curr = curr->left;
        curr = curr->right;
</code>```

the value of the pointer is overwritten.

Pay attention to that the first if statement can be rewritten simpler without introducing an intermediate variable.

```<code>    if ( curr == nullptr ){
        curr = new Node(val);
    }
</code>```

Body:
I have a binary tree program, when I am trying to traverse the tree for insertion in a recursive function pointer assignment does not seem to work. First things first here is the inserting function which is not working:

void append(Node* &curr, int val){

    if(curr==nullptr){
        Node* newNode = new Node(val);
        std::cout << "Created new Node with value: " << newNode->value << std::endl;
        curr = newNode;
        return;
    }
    if(curr->value > val){
        curr = curr->left;
        append(curr, val);
    }
    else{
        curr = curr->right;
        append(curr,val);
    }
}

But when I tweak the same function like following, it seems to work just fine:

void append(Node* &curr, int val){
        if(curr==nullptr){
            Node* newNode = new Node(val);
            std::cout << "Created new Node with value: " << newNode->value << std::endl;
            curr = newNode;
            return;
        }
        if(curr->value > val){
            append(curr->left, val);
        }
        else{
            std::cout << "Right" << curr->value << std::endl;
            append(curr->right,val);
        }
    }

I came to fix this after hours of work, and still can't understand why the first function does not work while the second one works as expected. Was hoping anyone can tell me why curr=curr->left is different than passing curr->left to the recursion.

Body:
In this function implementation

void append(Node* &curr, int val){

    if(curr==nullptr){
        Node* newNode = new Node(val);
        std::cout << "Created new Node with value: " << newNode->value << std::endl;
        curr = newNode;
        return;
    }
    if(curr->value > val){
        curr = curr->left;
        append(curr, val);
    }
    else{
        curr = curr->right;
        append(curr,val);
    }
}

As the pointer curr is passed by reference then in these statements

        curr = curr->left;
        curr = curr->right;

the value of the pointer is overwritten.

Pay attention to that the first if statement can be rewritten simpler without introducing an intermediate variable.

    if ( curr == nullptr ){
        curr = new Node(val);
    }


问:
C# Async await in a function called without await
I have a code to call a function in a loop, which would access endpoints asynchronously, coded like this:

```<code>public async Task HitEndPointsAsync()
{
    for (int i = 0; i < _urls.Length; i++)
    {
        await HitOneEndPointAsync(i);
    }
}
</code>```

The simplified function HitOneEndPointAsync looks like this:

```<code>private async Task HitOneEndPointAsync(int i)
{
    var newRec = InsertRec(i);
    ExtURL extUrl = new ExtURL(_urls[i]);
    result = await extUrl.GetAsync(_parms[i]);
    UpdateRec(i, result);
}
</code>```

If I remove the await in HitEndPointsAsync, then the await that is in HitOneEndPointAsync is no longer effective. If I need all endpoints to be called at once, but on each call await for the response to process that response further, would this be an option? Because as soon as I remove the await at the function call level, the await down the line is ignored. Thoughts?

答:
You could try something like this if you don't want to await within the loop:

```<code>public async Task HitEndPointsAsync()
{
    var tasks = new List<Task>();

    for (int i = 0; i < _urls.Length; i++)
    {
        tasks.Add(HitOneEndPointsAsync(i));
    }

    await Task.WhenAll(tasks);
}
</code>```

Note that this may add extra threads due to the calls to HitEndPointAsync being wrapped in a Task so I am not sure it has any advantages over the original version, maybe you could add more context to your question to know exactly what you are trying to do.

Body:
I have a code to call a function in a loop, which would access endpoints asynchronously, coded like this:

public async Task HitEndPointsAsync()
{
    for (int i = 0; i < _urls.Length; i++)
    {
        await HitOneEndPointAsync(i);
    }
}

The simplified function HitOneEndPointAsync looks like this:

private async Task HitOneEndPointAsync(int i)
{
    var newRec = InsertRec(i);
    ExtURL extUrl = new ExtURL(_urls[i]);
    result = await extUrl.GetAsync(_parms[i]);
    UpdateRec(i, result);
}

If I remove the await in HitEndPointsAsync, then the await that is in HitOneEndPointAsync is no longer effective. If I need all endpoints to be called at once, but on each call await for the response to process that response further, would this be an option? Because as soon as I remove the await at the function call level, the await down the line is ignored. Thoughts?

Body:
You could try something like this if you don't want to await within the loop:

public async Task HitEndPointsAsync()
{
    var tasks = new List<Task>();

    for (int i = 0; i < _urls.Length; i++)
    {
        tasks.Add(HitOneEndPointsAsync(i));
    }

    await Task.WhenAll(tasks);
}

Note that this may add extra threads due to the calls to HitEndPointAsync being wrapped in a Task so I am not sure it has any advantages over the original version, maybe you could add more context to your question to know exactly what you are trying to do.


问:
My gradle configuration does not use the correct classpath during build
I have a multi-project setup (ProjectB -> ProjectA), and I'm using flatDir to specify a single lib directory in each project.

ProjectA:

```<code>repositories {
    flatDir name: 'localRepository', dirs: 'lib'
}

dependencies {
    compile group: 'com.google.guava', name: 'guava', version: 'r08'
    compile group: 'com.miglayout', name: 'miglayout', version: '3.7.4'
    testCompile group: 'junit', name: 'junit', version: '4.+'
    testCompile group: 'org.easymock', name: 'easymock', version: '2.5.2'
}
</code>```

ProjectB:

```<code>repositories {
    flatDir name: 'localRepository', dirs: 'lib'
}

dependencies {
    compile group: 'yan', name: 'yan', version: '5.0.2'
    runtime group: 'yan', name: 'jfunutil', version: '5.0.2'
    compile project(':ProjectA')
    testCompile group: 'junit', name: 'junit', version: '4.+'
    testCompile group: 'org.easymock', name: 'easymock', version: '2.5.2'
</code>```

}

When I use gradle dependencies for ProjectB, the correct dependency list is generated, showing transitive dependencies from ProjectA (eg, including guava-r08). However, when I gradle build, the actual classpath used for javac only includes the direct dependencies of ProjectB, and the jar generated by building ProjectA.

Another annoyance is it seems for testCompile, I have to re-declare the dependency on junit for ProjectB otherwise gradle dependencies will not be successful.

Any pointers much appreciated - I am new to Gradle.

答:
About your project structure...

It seems like a better idea to have a single lib folder instead of having one for each project.

Your directory structure is like this:

```<code>project/settings.gradle
project/ProjectA/lib
project/ProjectA/src
project/ProjectB/lib
project/ProjectB/src
</code>```

Any particular reason why you want to have a lib folder for each subproject? This seems like a better idea:

```<code>project/settings.gradle
project/lib
project/ProjectA/src
project/ProjectB/src
</code>```

You can create a build.gradle in the root of the project (project/build.gradle) that contains the following:

```<code>subprojects{
   apply plugin: 'java'
   repositories {
        flatDir name: 'localRepository', dirs: "$rootProject.projectDir/lib"
   }
}
</code>```

This way you can drop all your dependencies into project/lib.

About your test depencendies...

You may also place your testCompile dependencies into this root build.gradle file. It becomes:

```<code>subprojects{
   apply plugin: 'java'
   repositories {
        flatDir name: 'localRepository', dirs: "$rootProject.projectDir/lib"
   }
   dependencies{
        testCompile group: 'junit', name: 'junit', version: '4.+'
        testCompile group: 'org.easymock', name: 'easymock', version: '2.5.2'
   }
}
</code>```

This way you do not have to specify the testCompile dependency in each subproject's build.gradle file.

However, when I gradle build, the
  actual classpath used for javac only
  includes the direct dependencies of
  ProjectB, and the jar generated by
  building ProjectA.

In order to compile ProjectB, you only need ProjectA. Only ProjectA is your compile dependency; ProjectA compile dependencies become ProjectB's transitive dependencies.

ContentLicense: CC BY-SA 3.0

Body:
I have a multi-project setup (ProjectB -> ProjectA), and I'm using flatDir to specify a single lib directory in each project.

ProjectA:

repositories {
    flatDir name: 'localRepository', dirs: 'lib'
}

dependencies {
    compile group: 'com.google.guava', name: 'guava', version: 'r08'
    compile group: 'com.miglayout', name: 'miglayout', version: '3.7.4'
    testCompile group: 'junit', name: 'junit', version: '4.+'
    testCompile group: 'org.easymock', name: 'easymock', version: '2.5.2'
}

ProjectB:

repositories {
    flatDir name: 'localRepository', dirs: 'lib'
}

dependencies {
    compile group: 'yan', name: 'yan', version: '5.0.2'
    runtime group: 'yan', name: 'jfunutil', version: '5.0.2'
    compile project(':ProjectA')
    testCompile group: 'junit', name: 'junit', version: '4.+'
    testCompile group: 'org.easymock', name: 'easymock', version: '2.5.2'

}

When I use gradle dependencies for ProjectB, the correct dependency list is generated, showing transitive dependencies from ProjectA (eg, including guava-r08). However, when I gradle build, the actual classpath used for javac only includes the direct dependencies of ProjectB, and the jar generated by building ProjectA.

Another annoyance is it seems for testCompile, I have to re-declare the dependency on junit for ProjectB otherwise gradle dependencies will not be successful.

Any pointers much appreciated - I am new to Gradle.

Body:
About your project structure...

It seems like a better idea to have a single lib folder instead of having one for each project.

Your directory structure is like this:

project/settings.gradle
project/ProjectA/lib
project/ProjectA/src
project/ProjectB/lib
project/ProjectB/src

Any particular reason why you want to have a lib folder for each subproject? This seems like a better idea:

project/settings.gradle
project/lib
project/ProjectA/src
project/ProjectB/src

You can create a build.gradle in the root of the project (project/build.gradle) that contains the following:

subprojects{
   apply plugin: 'java'
   repositories {
        flatDir name: 'localRepository', dirs: "$rootProject.projectDir/lib"
   }
}

This way you can drop all your dependencies into project/lib.

About your test depencendies...

You may also place your testCompile dependencies into this root build.gradle file. It becomes:

subprojects{
   apply plugin: 'java'
   repositories {
        flatDir name: 'localRepository', dirs: "$rootProject.projectDir/lib"
   }
   dependencies{
        testCompile group: 'junit', name: 'junit', version: '4.+'
        testCompile group: 'org.easymock', name: 'easymock', version: '2.5.2'
   }
}

This way you do not have to specify the testCompile dependency in each subproject's build.gradle file.

However, when I gradle build, the
  actual classpath used for javac only
  includes the direct dependencies of
  ProjectB, and the jar generated by
  building ProjectA.

In order to compile ProjectB, you only need ProjectA. Only ProjectA is your compile dependency; ProjectA compile dependencies become ProjectB's transitive dependencies.


问:
I am getting this error message while trying to use Testng in Eclipse?
I am getting the error message such as stack overflow, heap memory error and similar messages after trying to use TestNG. And after installing TestNg the Eclipse feels heavy and became very slow to respond. and throwing this error message.

答: An error of such kind Stackoverflow and heap memory error occurs because of physical lack of resources such as lower Ram or slower processor. So the only solution to this was to allocate more memory to eclipse IDE. you can allocate more memory to eclipse by finding the eclipse.ini file in your directory where you have installed it. After finding the file, the file should be in notepad. open the file in  notepad and  edit the memory allocated. there are two things you need to change. Xms and XMX, which is minimum and max memory. I made mine from 256m to 512m for XMS and from 1024m to 2048M. But make sure  you allocate only the memory which is spare. otherwise your PC might crash. Hope this helps.</p>


问:
Multidimensional Arrays lengths in Java
How to find the lengths of a multidimensional array with non equal indices?

For example, I have int[][] pathList = new int[6][4]

Without actually hard-coding the indices, I need to find the '6' and the '4'.

I can find the 6 with pathList.length, but how to obtain the '4'?

答:
In Java we can't use Length field like we used to one-dimensional arrays.
So simply writing a few lines of code solves this problem.
First, you need to know that the output of the Length field in multidimensional arrays is the number of rows.I mean when you have below array

int[][] numbers = {{1,2,3,4,2,6},{4,5,6,7}};

the result of
System.out.println(numbers.length);
is 2, because you have 2 rows. So, you should use this to solve this problem.
Example:

```<code>public class Main {

public static void main(String[] args) {

    //Array definition
    int[][] numbers = {{1,2,3,4,2,6},{4,5,6,7}};

    //Number of array's elements
    int result = 0;

    //calculate via loop
    for(int i=0; i< numbers.length; i++){
        result +=  numbers[i].length;
    }

    //output
    System.out.println(result);
}
</code>```

}

Title: Multidimensional Arrays lengths in Java

Body:
In Java we can't use Length field like we used to one-dimensional arrays.
So simply writing a few lines of code solves this problem.
First, you need to know that the output of the Length field in multidimensional arrays is the number of rows.I mean when you have below array

int[][] numbers = {{1,2,3,4,2,6},{4,5,6,7}};

the result of
System.out.println(numbers.length);
is 2, because you have 2 rows. So, you should use this to solve this problem.
Example:

public class Main {

public static void main(String[] args) {

    //Array definition
    int[][] numbers = {{1,2,3,4,2,6},{4,5,6,7}};

    //Number of array's elements
    int result = 0;

    //calculate via loop
    for(int i=0; i< numbers.length; i++){
        result +=  numbers[i].length;
    }

    //output
    System.out.println(result);
}

}


问:
prolog - create list from facts by criteria
I'm trying to create list from the facts in SWI-Prolog.
There are amount of exapmles but I don't understand how to create list by criteria.
You can see my code below.
Predicate extract doesn't work as I expected.

I need:

```<code>L = [depos(sbr, 3000, 3), depos(psb, 4000, 4), depos(hkb, 5000, 5)]
</code>```

But I get:

```<code>?- deposit(X), extract(X, 3, 5, Ls).

X = depos(sbr, 3000, 3),
Ls = [depos(sbr, 3000, 3)] ;
X = depos(psb, 4000, 4),
Ls = [depos(psb, 4000, 4)] ;
X = depos(hkb, 5000, 5),
Ls = [depos(hkb, 5000, 5)] ;
false.
</code>```

What do I wrong?

```<code>% vim: ft=prolog

depos(rsb, 1000, 1).
depos(vtb, 2000, 2).
depos(sbr, 3000, 3).
depos(psb, 4000, 4).
depos(hkb, 5000, 5).
depos(mkb, 6000, 6).

deposit(depos(Bank, Body, Rate)) :- depos(Bank, Body, Rate).

bank(depos(Bank,_,_), Bank).
body(depos(_,Body,_), Body).
rate(depos(_,_,Rate), Rate).

% Usage:
% deposit(X), bank(X, Ba), body(X, Bo), rate(X, Ra).

% Usage: create List from Body
% ?- findall(Bo, depos(Ba, Bo, Ra), L).
% L = [1000, 2000, 3000, 4000, 5000, 6000].

% Usage: create List from Rate
% ?- findall(Ra, depos(Ba, Bo, Ra), L).
% L = [1, 2, 3, 4, 5, 6].

profit(X, Prof) :-
  body(X, Body),
  rate(X, Rate),
  Prof is Body * Rate.

% Usage:
% ?- deposit(X), profit(X, Pro).
% X = depos(rsb, 1000, 1),
% Pro = 1000 ;
% X = depos(vtb, 2000, 2),
% Pro = 4000 ;

critRate(X, From, Before) :-
  rate(X, Rate),
  Rate >= From,
  Rate =< Before.

% Usage:
% ?- deposit(X), critRate(X, 3, 5).
% X = depos(sbr, 3000, 3) ;
% X = depos(psb, 4000, 4) ;
% X = depos(hkb, 5000, 5) ;

critProf(X, From, Before, Prof) :-
  profit(X, Prof),
  Prof >= From,
  Prof =< Before.

% Usage:
% ?- deposit(X), critProf(X, 9000, 25000).
% X = depos(sbr, 3000, 3) ;
% X = depos(psb, 4000, 4) ;
% X = depos(hkb, 5000, 5) ;

% How to create List Ls from deposit with Rate From to Before ???
extract(X, From, Before, Ls) :-
  bagof(X, critRate(X, From, Before), Ls).

% Expected:
% L = [depos(sbr, 3000, 3), depos(psb, 4000, 4), depos(hkb, 5000, 5)]
</code>```

答:
I think your problem is related in structuring your code with 'accessors', like these 3

bank(depos(Bank,_,_), Bank).
body(depos(_,Body,_), Body).
rate(depos(_,_,Rate), Rate).
```

<blockquote>
  <p>and using them in a functional fashion.</p>
</blockquote>

<p><em>edit by OP</em></p>

<p>Can you, please, explain that aspect in more detail? I'm a new in Prolog.
I've read about <strong>accessors</strong> in Bratko and use it without full understanding.
When I can use and when I don't.</p>

<blockquote>
  <p>Prolog has a relational data model, so you should rethink your workflow. For instance, simplify extract/4 to extract/3 in this way</p>
</blockquote>

<pre class="lang-erlang prettyprint-override"><code>extract(From, Before, Ls) :-
  bagof(X, (deposit(X),critRate(X, From, Before)), Ls).
</code>```

and you'll get what you need:

?- extract(3, 5, Ls).
Ls = [depos(sbr, 3000, 3), depos(psb, 4000, 4), depos(hkb, 5000, 5)].
```

<p><strong>That works! Thank you.</strong></p>

<p><em>edit by OP</em></p>

<p>I added new predicate for <strong>critProf</strong> </p>

```extract_prof4(From, Before, Prof, Ls) :-
  bagof(X, (deposit(X), critProf(X, From, Before, Prof)), Ls).
```

<p>and it doesn't work again.</p>

```?- extract_prof4(3000,25000,P,L).
P = 4000,
L = [depos(vtb, 2000, 2)] ;
P = 9000,
L = [depos(sbr, 3000, 3)] ;
```

<p>BUT if I added another predicates (without Prof as an argument), like this:</p>

```critProf3(X, From, Before) :-
  profit(X, Prof),
  Prof >= From,
  Prof =< Before.

extract_prof(From, Before, Ls) :-
  bagof(X, (deposit(X), critProf3(X, From, Before)), Ls).
```

<p>they work correctly:</p>

```?- extract_prof(3000,25000,L).
L = [depos(vtb, 2000, 2), depos(sbr, 3000, 3), depos(psb, 4000, 4), depos(hkb, 5000, 5)].
```

Why?

Body:
I'm trying to create list from the facts in SWI-Prolog.
There are amount of exapmles but I don't understand how to create list by criteria.
You can see my code below.
Predicate extract doesn't work as I expected.

I need:

L = [depos(sbr, 3000, 3), depos(psb, 4000, 4), depos(hkb, 5000, 5)]

But I get:

?- deposit(X), extract(X, 3, 5, Ls).

X = depos(sbr, 3000, 3),
Ls = [depos(sbr, 3000, 3)] ;
X = depos(psb, 4000, 4),
Ls = [depos(psb, 4000, 4)] ;
X = depos(hkb, 5000, 5),
Ls = [depos(hkb, 5000, 5)] ;
false.

What do I wrong?

% vim: ft=prolog

depos(rsb, 1000, 1).
depos(vtb, 2000, 2).
depos(sbr, 3000, 3).
depos(psb, 4000, 4).
depos(hkb, 5000, 5).
depos(mkb, 6000, 6).

deposit(depos(Bank, Body, Rate)) :- depos(Bank, Body, Rate).

bank(depos(Bank,_,_), Bank).
body(depos(_,Body,_), Body).
rate(depos(_,_,Rate), Rate).

% Usage:
% deposit(X), bank(X, Ba), body(X, Bo), rate(X, Ra).

% Usage: create List from Body
% ?- findall(Bo, depos(Ba, Bo, Ra), L).
% L = [1000, 2000, 3000, 4000, 5000, 6000].

% Usage: create List from Rate
% ?- findall(Ra, depos(Ba, Bo, Ra), L).
% L = [1, 2, 3, 4, 5, 6].

profit(X, Prof) :-
  body(X, Body),
  rate(X, Rate),
  Prof is Body * Rate.

% Usage:
% ?- deposit(X), profit(X, Pro).
% X = depos(rsb, 1000, 1),
% Pro = 1000 ;
% X = depos(vtb, 2000, 2),
% Pro = 4000 ;

critRate(X, From, Before) :-
  rate(X, Rate),
  Rate >= From,
  Rate =< Before.

% Usage:
% ?- deposit(X), critRate(X, 3, 5).
% X = depos(sbr, 3000, 3) ;
% X = depos(psb, 4000, 4) ;
% X = depos(hkb, 5000, 5) ;

critProf(X, From, Before, Prof) :-
  profit(X, Prof),
  Prof >= From,
  Prof =< Before.

% Usage:
% ?- deposit(X), critProf(X, 9000, 25000).
% X = depos(sbr, 3000, 3) ;
% X = depos(psb, 4000, 4) ;
% X = depos(hkb, 5000, 5) ;

% How to create List Ls from deposit with Rate From to Before ???
extract(X, From, Before, Ls) :-
  bagof(X, critRate(X, From, Before), Ls).

% Expected:
% L = [depos(sbr, 3000, 3), depos(psb, 4000, 4), depos(hkb, 5000, 5)]

Body:
I think your problem is related in structuring your code with 'accessors', like these 3

bank(depos(Bank,_,_), Bank).
body(depos(_,Body,_), Body).
rate(depos(_,_,Rate), Rate).

and using them in a functional fashion.

edit by OP

Can you, please, explain that aspect in more detail? I'm a new in Prolog.
I've read about accessors in Bratko and use it without full understanding.
When I can use and when I don't.

Prolog has a relational data model, so you should rethink your workflow. For instance, simplify extract/4 to extract/3 in this way

extract(From, Before, Ls) :-
  bagof(X, (deposit(X),critRate(X, From, Before)), Ls).

and you'll get what you need:

?- extract(3, 5, Ls).
Ls = [depos(sbr, 3000, 3), depos(psb, 4000, 4), depos(hkb, 5000, 5)].

That works! Thank you.

edit by OP

I added new predicate for critProf

extract_prof4(From, Before, Prof, Ls) :-
  bagof(X, (deposit(X), critProf(X, From, Before, Prof)), Ls).

and it doesn't work again.

?- extract_prof4(3000,25000,P,L).
P = 4000,
L = [depos(vtb, 2000, 2)] ;
P = 9000,
L = [depos(sbr, 3000, 3)] ;

BUT if I added another predicates (without Prof as an argument), like this:

critProf3(X, From, Before) :-
  profit(X, Prof),
  Prof >= From,
  Prof =< Before.

extract_prof(From, Before, Ls) :-
  bagof(X, (deposit(X), critProf3(X, From, Before)), Ls).

they work correctly:

?- extract_prof(3000,25000,L).
L = [depos(vtb, 2000, 2), depos(sbr, 3000, 3), depos(psb, 4000, 4), depos(hkb, 5000, 5)].

Why?


问:
How to have one script trigger another [j Query] Shrinking and expanding searchbox
Hey, I have a simple question, but I'll set up the scenario first.

I'm making a menu bar similar to that of apple.com (when the search bar is clicked it auto expands to show available user input)

Now I have a script that expands the search for when clicked an is as follows:

```<code><script>
$("#searchbar").focus(function() {
$("#searchbar").animate(
        {width: 170},
        "medium");
});
$("#searchbar").blur(function() {
$("#searchbar").animate(
        {width: 92},
        "medium");
});
</script>
</code>```

So I need to somehow shrink the rest of the menu bar, this is what I'm thinking: if I make the buttons in a separate div tag then just call upon the shrinking of the div when the search bar is clicked that should work fine.

The only problem is I do not know how to accomplish this task. That is why I have come to ask this question, I hope I am not asking a complete noobish question! :)

Thanks for all the help!
-John

答:
You want to add a complete callback to your animate functions.  See http://api.jquery.com/animate/

Callbacks happen after an event is done (animate in your case).

Body:
Hey, I have a simple question, but I'll set up the scenario first.

I'm making a menu bar similar to that of apple.com (when the search bar is clicked it auto expands to show available user input)

Now I have a script that expands the search for when clicked an is as follows:

So I need to somehow shrink the rest of the menu bar, this is what I'm thinking: if I make the buttons in a separate div tag then just call upon the shrinking of the div when the search bar is clicked that should work fine.

The only problem is I do not know how to accomplish this task. That is why I have come to ask this question, I hope I am not asking a complete noobish question! :)

Thanks for all the help!
-John


问:
Can we use AWS Data Migration Service for replication from Aurora Serverless as source?
My DMS replication instance (which is in same VPC as of Aurora serverless DB instance) is not able to find DB while creating endpoint in DMS.

However, I am able to create a cloud9 instance in same VPC as aurora serverless instance and connect to it from there.

Am I missing something here or it is not possible to use AWS DMS for migrating data from Aurora serverless as source?

答:
Above issue was resolved by explicitly specifying the connection details for aurora serverless cluster (instead of dropdown selection). But the answer to original question of using Aurora serverless DB as source in DMS replication -

Yes, if only one time replication is required

No, If ongoing replication is required. For ongoing replication, It is required to change the values of binlog_format parameter for source database. Although, Aurora serverless allows changing value for this parameter but it has no impact in actual. Only a few parameters are supported for change which are listed here


问:
Smartsheet - How to attach a file to a row using Smartsheet API and PHP curl
The smartsheet api docs provide this documentation to attach a file to a row.

```<code>curl https://api.smartsheet.com/2.0/sheets/{sheetId}/rows/{rowId}/attachments
</code>```

\
      -H "Authorization: Bearer ll352u9jujauoqz4gstvsae05" \
      -H "Content-Type: application/msword" \
      -H 'Content-Disposition: attachment; filename="ProgressReport.docx"' \
      -H "Content-Length: FILE_SIZE" \
      -X POST \
      --data-binary @ProgressReport.docx

How do I translate this into the appropriate calls to a curl session in php?

I assume that I need to create a header block such as

```<code>$headersAttachment = array(
    "Authorization: Bearer " . $AccessToken,
    "Content-Type: application/pdf",
    'Content-Disposition: attachment; filename="mydoc.pdf"', // **is this for just the filename or the full path?**
    "Content-Length: " . $FileSizeOfMyDoc
);
</code>```

and use it like so

```<code>$curlSession = curl_init($rowsURL . '/' . $rowId . '/attachments');
curl_setopt($curlSession, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curlSession, CURLOPT_HTTPHEADER, $headersAttachment);
curl_setopt($curlSession, CURLOPT_POSTFIELDS, $body);
curl_setopt($curlSession, CURLOPT_POST, TRUE);
$getSheetResponseData = curl_exec($curlSession);
</code>```

What do I need to put in $body so that the data from the file is uploaded?

The smartsheet api docs say

The following example request shows a simple upload that adds a file
  attachment to a sheet:

POST
  https://api.smartsheet.com/2.0/sheets/4509093797881732/attachments
  Authorization: Bearer ll352u9jujauoqz4gstvsae05 Content-Disposition:
  attachment; filename="ProgressReport.docx" Content-Type:
  application/msword Content-Length: 5463

< Binary content for file >

As shown in this example, the contents of the file is included in the
  body of the POST request. In most programming languages, this is done
  by reading the file from an input stream and writing it out to the
  output stream of the HTTP request.

this is done by reading the file from an input stream and writing it out to the output stream of the HTTP request. <--- How Do I Do This In PHP?

As an after thought, how can I check this with Postman?

Thanks in advance. Any help would be awesome.

答:
It would appear that Postman had the answer all the time. Postman has an option to generate code snippets, which up to now I had not read correctly, as I was fixated on CURL. I then noticed on the left hand side there was an option for PHP - cURL which gave me the answer I wanted. Using this code finally worked for me.</p>

```<code><?php

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://api.smartsheet.com/2.0/sheets/SHEETID/rows/ROWID/columns/COLOUMNID/cellimages",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => "<file contents here>",
  CURLOPT_HTTPHEADER => array(
    "Authorization: Bearer ACCESSTOKEN",
    "Content-Type: image/png",
    "Content-Disposition: attachment; filename=\"modify.png\"",
    "Content-Length: <file size here>
  ),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;
</code>```

Body:
The smartsheet api docs provide this documentation to attach a file to a row.

curl https://api.smartsheet.com/2.0/sheets/{sheetId}/rows/{rowId}/attachments

\
      -H "Authorization: Bearer ll352u9jujauoqz4gstvsae05" \
      -H "Content-Type: application/msword" \
      -H 'Content-Disposition: attachment; filename="ProgressReport.docx"' \
      -H "Content-Length: FILE_SIZE" \
      -X POST \
      --data-binary @ProgressReport.docx

How do I translate this into the appropriate calls to a curl session in php?

I assume that I need to create a header block such as

$headersAttachment = array(
    "Authorization: Bearer " . $AccessToken,
    "Content-Type: application/pdf",
    'Content-Disposition: attachment; filename="mydoc.pdf"', // **is this for just the filename or the full path?**
    "Content-Length: " . $FileSizeOfMyDoc
);

and use it like so

$curlSession = curl_init($rowsURL . '/' . $rowId . '/attachments');
curl_setopt($curlSession, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curlSession, CURLOPT_HTTPHEADER, $headersAttachment);
curl_setopt($curlSession, CURLOPT_POSTFIELDS, $body);
curl_setopt($curlSession, CURLOPT_POST, TRUE);
$getSheetResponseData = curl_exec($curlSession);

What do I need to put in $body so that the data from the file is uploaded?

The smartsheet api docs say

The following example request shows a simple upload that adds a file
  attachment to a sheet:

POST
  https://api.smartsheet.com/2.0/sheets/4509093797881732/attachments
  Authorization: Bearer ll352u9jujauoqz4gstvsae05 Content-Disposition:
  attachment; filename="ProgressReport.docx" Content-Type:
  application/msword Content-Length: 5463

< Binary content for file >

As shown in this example, the contents of the file is included in the
  body of the POST request. In most programming languages, this is done
  by reading the file from an input stream and writing it out to the
  output stream of the HTTP request.

this is done by reading the file from an input stream and writing it out to the output stream of the HTTP request. <--- How Do I Do This In PHP?

As an after thought, how can I check this with Postman?

Thanks in advance. Any help would be awesome.

Body:
It would appear that Postman had the answer all the time. Postman has an option to generate code snippets, which up to now I had not read correctly, as I was fixated on CURL. I then noticed on the left hand side there was an option for PHP - cURL which gave me the answer I wanted. Using this code finally worked for me.

<?php

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://api.smartsheet.com/2.0/sheets/SHEETID/rows/ROWID/columns/COLOUMNID/cellimages",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => "<file contents here>",
  CURLOPT_HTTPHEADER => array(
    "Authorization: Bearer ACCESSTOKEN",
    "Content-Type: image/png",
    "Content-Disposition: attachment; filename=\"modify.png\"",
    "Content-Length: <file size here>
  ),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;


问:
Transfer SQL Server data to SQL Azure
I have a local database SQL Server 2008 Express and I have tables along with data in them. I want to export those schemas and data to SQL Azure database.

What I have tried in SQL Management Studio is to right-click database (contextual menu) and Tasks->Generate Scripts. But those SQL scripts were only the schema, stored procedures etc and no data is exported at all.

Then I have tried Tasks->Export Data, but there were no appropriate export types. I have seen only Flat File dump and I think SQL Mgmt Studio 2008 R2 does not support importing flat files for SQL Azure.

Is there a nicer way to export data from SQL Server as sql scripts and execute them on a remote server without using any 3rd party tools?

答:
You can try SQL Server Import and Export Wizard.

For Detailed steps reg how to do it, check link.

I have worked with it already and it works fine for both Azure and on-premises.

Title: Transfer SQL Server data to SQL Azure


问:
Sorting the columns based on value of a column. Pandas
df1

```<code>ITEM      CATEGORY       COLOR     LOCATION      PRICE

23661      BIKE          BLUE        A           30000
23661      BIKE          BLUE        B           43563
23661      BIKE          BLUE        C           45124
23661      BIKE          BLUE        D           28000
48684      CAR           RED         B           45145
48684      CAR           RED         D           35613
48684      CAR           RED         A           82312
48684      CAR           RED         C           24536
48684      CAR           RED         E           45613
54519      BIKE          BLACK       A           21345
54519      BIKE          BLACK       B           62623
54519      BIKE          BLACK       C           14613
54519      BIKE          BLACK       E           14365
54519      BIKE          BLACK       D           67353
</code>```

Expecting outcome is the location that has the highest price for the vehicle.

```<code>ITEM      CATEGORY       COLOR     LOCATION      PRICE

23661      BIKE          BLUE        C           45124
48684      CAR           RED         A           82312
54519      BIKE          BLACK       D           67353
</code>```

df.sort_values(df['PRICE'],  ascending=False, kind='quicksort') Using this code we can manually do one by one. How to do this for the whole df.

答:
sort_values + drop_duplicates:

```<code>df.sort_values(['ITEM','PRICE'],ascending=[True,False]).drop_duplicates('ITEM')
</code>```

```<code>     ITEM CATEGORY  COLOR LOCATION  PRICE
2   23661     BIKE   BLUE        C  45124
6   48684      CAR    RED        A  82312
13  54519     BIKE  BLACK        D  67353
</code>```

Body:
df1

ITEM      CATEGORY       COLOR     LOCATION      PRICE

23661      BIKE          BLUE        A           30000
23661      BIKE          BLUE        B           43563
23661      BIKE          BLUE        C           45124
23661      BIKE          BLUE        D           28000
48684      CAR           RED         B           45145
48684      CAR           RED         D           35613
48684      CAR           RED         A           82312
48684      CAR           RED         C           24536
48684      CAR           RED         E           45613
54519      BIKE          BLACK       A           21345
54519      BIKE          BLACK       B           62623
54519      BIKE          BLACK       C           14613
54519      BIKE          BLACK       E           14365
54519      BIKE          BLACK       D           67353

Expecting outcome is the location that has the highest price for the vehicle.

ITEM      CATEGORY       COLOR     LOCATION      PRICE

23661      BIKE          BLUE        C           45124
48684      CAR           RED         A           82312
54519      BIKE          BLACK       D           67353

df.sort_values(df['PRICE'],  ascending=False, kind='quicksort') Using this code we can manually do one by one. How to do this for the whole df.

Body:
sort_values + drop_duplicates:

df.sort_values(['ITEM','PRICE'],ascending=[True,False]).drop_duplicates('ITEM')

     ITEM CATEGORY  COLOR LOCATION  PRICE
2   23661     BIKE   BLUE        C  45124
6   48684      CAR    RED        A  82312
13  54519     BIKE  BLACK        D  67353


问:
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]
```

答:
As we all know world of JavaScript is a magic world, and even this thing, like infinite currying is possible

const nice = (...args) => {
  return Object.assign(
    nice.bind(0, ...args),
    { valueOf: () => args.reduce((a, b) => a + b, 0) }
  )
}

console.log(+nice(1)()(2)) // ~> 3
console.log(+nice(1, 2)()(3)()()) // ~> 6
console.log(+nice()()()()()()(1)) // ~> 1
console.log(+nice()()()(2)()()()) // ~> 2

console.log(nice(2)()(1) + '') // ~> '3'

console.log(nice()(3)() == 3) // ~> true

console.log(nice()(3)() === 3) // ~> false```
</div>
</div>
</p>

<p>The trick is that adding unary + or using non-strict equality calls <code>valueOf</code> method right after all function calls, so we've got ourselves an infinite currying :)</p>

<p>And list currying to answer your question. It works because <code>'' +</code> forces toString method to be called:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const nice = (...args) => {
  return Object.assign(
    nice.bind(0, ...args),
    { toString: () => JSON.stringify(args) }
  )
}

console.log('' + nice(1,2)(3)(4)(5)(6,7)) // ~> [1,2,3,4,5,6,7]</code>```

By the way, it's possible to make this infinite currying even more legit, because it can take any type and any amount of parameters which's really cool.

<3

Body:
As we all know world of JavaScript is a magic world, and even this thing, like infinite currying is possible

const nice = (...args) => {
  return Object.assign(
    nice.bind(0, ...args),
    { valueOf: () => args.reduce((a, b) => a + b, 0) }
  )
}

console.log(+nice(1)()(2)) // ~> 3
console.log(+nice(1, 2)()(3)()()) // ~> 6
console.log(+nice()()()()()()(1)) // ~> 1
console.log(+nice()()()(2)()()()) // ~> 2

console.log(nice(2)()(1) + '') // ~> '3'

console.log(nice()(3)() == 3) // ~> true

console.log(nice()(3)() === 3) // ~> false

The trick is that adding unary + or using non-strict equality calls valueOf method right after all function calls, so we've got ourselves an infinite currying :)

And list currying to answer your question. It works because '' + forces toString method to be called:

const nice = (...args) => {
  return Object.assign(
    nice.bind(0, ...args),
    { toString: () => JSON.stringify(args) }
  )
}

console.log('' + nice(1,2)(3)(4)(5)(6,7)) // ~> [1,2,3,4,5,6,7]

By the way, it's possible to make this infinite currying even more legit, because it can take any type and any amount of parameters which's really cool.

<3


问:
In C# (or any language) what is/are your favourite way of removing repetition?
I've just coded a 700 line class. Awful. I hang my head in shame.  It's as opposite to DRY as a British summer.

It's full of cut and paste with minor tweaks here and there.  This makes it's a prime candidate for refactoring.  Before I embark on this, I'd thought I'd ask when you have lots of repetition, what are the first refactoring opportunities you look for?

For the record, mine are probably using:

Generic classes and methods

Method overloading/chaining.

What are yours?

答:
I like to start refactoring when I need to, rather than the first opportunity that I get. You might say this is somewhat of an agile approach to refactoring. When do I feel I need to? Usually when I feel that the ugly parts of my codes are starting to spread. I think ugliness is okay as long as they are contained, but the moment when they start having the urge to spread, that's when you need to take care of business.

The techniques you use for refactoring should start with the simplest. I would strongly recommand Martin Fowler's book. Combining common code into functions, removing unneeded variables, and other simple techniques gets you a lot of mileage. For list operations, I prefer using functional programming idioms. That is to say, I use internal iterators, map, filter and reduce(in python speak, there are corresponding things in ruby, lisp and haskell) whenever I can, this makes code a lot shorter and more self-contained.

OwnerDisplayName: IainMH

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: toby


问:
What should I know about C# before walking into an interview for a .NET job?
Sure, we all have written tons of C# code. So walking into an interview for a .NET job should be a no-brainer, right? And then you read some stackoverflow posts and it hits you: You don't know squat!

Remember that site with the cram sessions to go through, before taking an exam? I think stackoverflow could be used to make a sorted (voting) list of topics to know about.

Please only put one topic per post.
Please also add some information about the topic. Links, reference material etc.

EDIT: I guess some of you misunderstood the reason for the post - I'm hoping to generate a list of stuff to know about .NET, a sort of cram session that can be reviewed by everyone on the planet to regularly review. This should help us all remember arcane stuff we never really use.

答: Reflection. and the power of custom attributes in reflection.

OwnerDisplayName: Daren Thomas

LastEditorDisplayName: Daren Thomas

OwnerDisplayName: ScarletGarden


问:
Compare Txt Files in Linux and Return Elements in File 1 for Elements in File 2
Here is the problem.

Host.txt file has only Hostnames as follows:

```
GVC-CH-ZRH-BRA-5H81-PELE
GVC-US-NYC-9TH-4C101-MEDROOM
GVC-US-NYC-9TH-4C101E-EXTRA
GVC-US-NYC-9TH-5E117-STUDIO54
```

2.HosandIp.txt has the Hostnames and Ip as follows (HostandIP has hostname,IP Address Note the Comma (,)):

```
GVC-CH-ZRH-BRA-5H81-PELE,170.16.75.101
GVC-US-NYC-9TH-4C101-MEDROOM,170.26.114.242
GVC-US-NYC-9TH-4C101E-EXTRA,170.26.108.224
GVC-US-NYC-9TH-5E117-STUDIO54,170.26.108.95
beta-gvc-personal-antoniop-526,170.26.107.180
beta-gvc-personal-antoniop-9100,170.26.106.206
beta-gvc-personal-antoniop-9100b,170.26.106.41
beta-gvc-personal-antoniop-office,170.26.107.192
```

I need to compare these two files and get only the IP Address in another text file called IPOnly.txt

IPOnly.txt has only the IP's common to both Host.txt and HostandIp.txt as follows:

```
170.16.75.101
170.26.114.242
170.26.108.224
170.26.108.95
```

It can be done in JAVA using HASH MAP. Is there a Linux Command to do this ? Please Help!

答:
one-liner:

```<code>for line in $(cat host.txt); do sed -n s/$line',\(.*\)/\1/p' host-and-ip.txt ; done > ip-only.txt
</code>```

in readable form:

```<code>for line in $(cat host.txt)
do
  sed -n s/$line',\(.*\)/\1/p' host-and-ip.txt
done > ipOnly.txt
</code>```

Body:
Here is the problem.

Host.txt file has only Hostnames as follows:

GVC-CH-ZRH-BRA-5H81-PELE
GVC-US-NYC-9TH-4C101-MEDROOM
GVC-US-NYC-9TH-4C101E-EXTRA
GVC-US-NYC-9TH-5E117-STUDIO54

2.HosandIp.txt has the Hostnames and Ip as follows (HostandIP has hostname,IP Address Note the Comma (,)):

GVC-CH-ZRH-BRA-5H81-PELE,170.16.75.101
GVC-US-NYC-9TH-4C101-MEDROOM,170.26.114.242
GVC-US-NYC-9TH-4C101E-EXTRA,170.26.108.224
GVC-US-NYC-9TH-5E117-STUDIO54,170.26.108.95
beta-gvc-personal-antoniop-526,170.26.107.180
beta-gvc-personal-antoniop-9100,170.26.106.206
beta-gvc-personal-antoniop-9100b,170.26.106.41
beta-gvc-personal-antoniop-office,170.26.107.192

I need to compare these two files and get only the IP Address in another text file called IPOnly.txt

IPOnly.txt has only the IP's common to both Host.txt and HostandIp.txt as follows:

170.16.75.101
170.26.114.242
170.26.108.224
170.26.108.95

It can be done in JAVA using HASH MAP. Is there a Linux Command to do this ? Please Help!

Body:
one-liner:

for line in $(cat host.txt); do sed -n s/$line',\(.*\)/\1/p' host-and-ip.txt ; done > ip-only.txt

in readable form:

for line in $(cat host.txt)
do
  sed -n s/$line',\(.*\)/\1/p' host-and-ip.txt
done > ipOnly.txt


问:
Count max increasing number sequence in array
I have to find the max increasing number sequence in this array.
Does anyone know why my code doesn't run?</p>

```<code>public class Array {

public static void main(String[] args) {

    int[] a = {4,7,15,3,9,22,36,24,28,14,19,27,30,31,2,9,29,30,16,19};

    int counter = 0;
    int maxCounter = 0;

    for (int i : a) {

        if (a[i] < a[i + 1]) {
            counter++;
        }

        if (a[i] > a[i + 1]) {
            maxCounter = counter;
            counter = 0;
        }

    }

    System.out.println(maxCounter);
}

}
</code>```

答:
You have two bugs, your loop should be an ordinary loop over array indices (not a for-each loop over array contents); and your setting of maxCounter should involve a comparison (not a blind assignment). Like,

```<code>for (int i = 0; i + 1 < a.length; i++) { // <-- not a for-each loop
    if (a[i] < a[i + 1]) {
        counter++;
    } else if (a[i] > a[i + 1]) { // <-- An else doesn't hurt
        // maxCounter = counter; // <-- not a blind assignment
        maxCounter = Math.max(maxCounter, counter);
        counter = 0;
    }
}
</code>```

Body:
I have to find the max increasing number sequence in this array.
Does anyone know why my code doesn't run?

public class Array {

public static void main(String[] args) {

    int[] a = {4,7,15,3,9,22,36,24,28,14,19,27,30,31,2,9,29,30,16,19};

    int counter = 0;
    int maxCounter = 0;

    for (int i : a) {

        if (a[i]  a[i + 1]) {
            maxCounter = counter;
            counter = 0;
        }

    }

    System.out.println(maxCounter);
}

}

Body:
You have two bugs, your loop should be an ordinary loop over array indices (not a for-each loop over array contents); and your setting of maxCounter should involve a comparison (not a blind assignment). Like,

for (int i = 0; i + 1 < a.length; i++) { // <-- not a for-each loop
    if (a[i] < a[i + 1]) {
        counter++;
    } else if (a[i] > a[i + 1]) { // <-- An else doesn't hurt
        // maxCounter = counter; // <-- not a blind assignment
        maxCounter = Math.max(maxCounter, counter);
        counter = 0;
    }
}


问:
What are the differences between application/json and application/x-www-form-urlencoded?
What is the difference between

request.ContentType = "application/json; charset=utf-8";

and

webRequest.ContentType = "application/x-www-form-urlencoded";

答:
webRequest.ContentType = "application/x-www-form-urlencoded";

Where does application/x-www-form-urlencoded's name come from?

If you send HTTP GET request, you can use query parameters as follows:

http://example.com/path/to/page?name=ferret&color=purple

The content of the fields is encoded as a query string. The application/x-www-form-
urlencoded's name come from the previous url query parameter but the query parameters is
in where the body of request instead of url.

The whole form data is sent as a long query string.The query string contains name-
value pairs separated by & character

e.g. field1=value1&field2=value2

It can be simple request called simple - don't trigger a preflight check

Simple request must have some properties. You can look here for more info. One of
them is that there are only three values allowed for Content-Type header for simple
requests

application/x-www-form-urlencoded

multipart/form-data

text/plain

3.For mostly flat param trees, application/x-www-form-urlencoded is tried and tested.

request.ContentType = "application/json; charset=utf-8";

The data will be json format.

axios and superagent, two of the more popular npm HTTP libraries, work with JSON bodies by default.

```<code>{
  "id": 1,
  "name": "Foo",
  "price": 123,
  "tags": [
    "Bar",
    "Eek"
  ],
  "stock": {
    "warehouse": 300,
    "retail": 20
  }
}
</code>```

"application/json" Content-Type is one of the  Preflighted requests.

Now, if the request isn't simple request, the browser automatically sends a HTTP request before the original one by OPTIONS method to check whether it is safe to send the original request. If itis ok, Then send actual request. You can look here for more info.

application/json is beginner-friendly. URL encoded arrays can be a nightmare!

Body:
webRequest.ContentType = "application/x-www-form-urlencoded";

Where does application/x-www-form-urlencoded's name come from?

If you send HTTP GET request, you can use query parameters as follows:

http://example.com/path/to/page?name=ferret&color=purple

The content of the fields is encoded as a query string. The application/x-www-form-
urlencoded's name come from the previous url query parameter but the query parameters is
in where the body of request instead of url.

The whole form data is sent as a long query string.The query string contains name-
value pairs separated by & character

e.g. field1=value1&field2=value2

It can be simple request called simple - don't trigger a preflight check

Simple request must have some properties. You can look here for more info. One of
them is that there are only three values allowed for Content-Type header for simple
requests

application/x-www-form-urlencoded

multipart/form-data

text/plain

3.For mostly flat param trees, application/x-www-form-urlencoded is tried and tested.

request.ContentType = "application/json; charset=utf-8";

The data will be json format.

axios and superagent, two of the more popular npm HTTP libraries, work with JSON bodies by default.

{
  "id": 1,
  "name": "Foo",
  "price": 123,
  "tags": [
    "Bar",
    "Eek"
  ],
  "stock": {
    "warehouse": 300,
    "retail": 20
  }
}

"application/json" Content-Type is one of the  Preflighted requests.

Now, if the request isn't simple request, the browser automatically sends a HTTP request before the original one by OPTIONS method to check whether it is safe to send the original request. If itis ok, Then send actual request. You can look here for more info.

application/json is beginner-friendly. URL encoded arrays can be a nightmare!


问:
are there any memory leaks in this code?
I have successfully created a UITableView/UITableViewCell that is able to slide up and down and adjusting the height to show options. To see what this means, I have created a video here. The code is as follows:

```<code>- (void)swipe:(UISwipeGestureRecognizer *)recognizer direction:(UISwipeGestureRecognizerDirection)direction
{
    if (recognizer && recognizer.state == UIGestureRecognizerStateEnded)
    {
        // Get the table view cell where the swipe occured
        CGPoint location = [recognizer locationInView:self.tableView];
        NSIndexPath* indexPath = [self.tableView indexPathForRowAtPoint:location];
        MyCell* cell = (MyCell *) [self.tableView cellForRowAtIndexPath:indexPath];

        [self.tableView beginUpdates];

        //removing the options view at the other cell before adding a new one

        if (global != nil && global.row != indexPath.row){
            [sideSwipeView removeFromSuperview];
            sideSwipeView = nil;
        }

        //options already exist, we need to remove it
        if (sideSwipeView != nil){
            [sideSwipeView removeFromSuperview];
            sideSwipeView = nil;
            slide = NO;
        } else {
            //options do not exist and therefore we need to add it
            NSArray * buttonData = [[NSArray arrayWithObjects:
                                     [NSDictionary dictionaryWithObjectsAndKeys:@"Mark Read", @"title", @"mark.png", @"image", nil],
                                     [NSDictionary dictionaryWithObjectsAndKeys:@"Track", @"title", @"play.png", @"image", nil],
                                     nil] retain];

            NSMutableArray * buttons = [[NSMutableArray alloc] initWithCapacity:buttonData.count];
            sideSwipeView = [[UIView alloc] initWithFrame:CGRectMake(0, cell.frame.size.height-25, 320, 25)];
            [sideSwipeView setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin];
            [sideSwipeView setBackgroundColor:[UIColor colorWithPatternImage: [UIImage imageNamed:@"dotted-pattern.png"]]];
            [sideSwipeView setTag:-10];

            CGFloat leftEdge = BUTTON_LEFT_MARGIN;
            for (NSDictionary* buttonInfo in buttonData)
            {
                if (!([[buttonInfo objectForKey:@"title"] isEqualToString:@"Mark Read"] && [[[topics objectAtIndex:indexPath.row] unread] intValue] == 0))
                {

                    UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];

                    button.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleTopMargin;

                    UIImage* buttonImage = [UIImage imageNamed:[buttonInfo objectForKey:@"image"]];
                    if ([[topics objectAtIndex:indexPath.row] tracked] && [[buttonInfo objectForKey:@"title"] isEqualToString:@"Track"]){
                        buttonImage = [UIImage imageNamed:@"pause.png"];
                        [button setSelected:YES];
                    } else {
                        [button setSelected:NO];
                    }
                    button.frame = CGRectMake(leftEdge, 0, buttonImage.size.width, buttonImage.size.height);

                    UIImage* grayImage = [self imageFilledWith:[UIColor colorWithWhite:0.9 alpha:1.0] using:buttonImage];
                    [button setImage:grayImage forState:UIControlStateNormal];

                    if ([[buttonInfo objectForKey:@"title"] isEqualToString:@"Mark Read"]){
                        [button addTarget:self action:@selector(markRead:) forControlEvents:UIControlEventTouchUpInside];
                    } else if ([[buttonInfo objectForKey:@"title"] isEqualToString:@"Track"]){
                        [button addTarget:self action:@selector(track:) forControlEvents:UIControlEventTouchUpInside];
                    }
                    [button setTag:indexPath.row];
                    [buttons addObject:button];

                    [sideSwipeView addSubview:button];

                    leftEdge = leftEdge + buttonImage.size.width + BUTTON_SPACING;
                }
            }

            [cell.contentView addSubview:sideSwipeView];
            [sideSwipeView release];
            global = indexPath;
            slide = YES;

        }
        [self.tableView endUpdates];
        [self.tableView deselectRowAtIndexPath:indexPath animated:YES];

    }
}
</code>```

However, I am not confident that the code is memory correct (i.e: ther's no memory leak and I am not misusing anything). I am mostly not confident in the sideSwipeView alloc, dealloc, and setting it up to nil. I think the others are fine. Can someone give me any pointers?

Profiler result:

答:
The rule of thumb when dealing with memory management in Objective-C is that you should explicitly release objects that you are: (1) allocating (alloc), (2) cloning (copy), or newing up (new, which is a combination of alloc/init).

With that knowledge, go over your code, look for places where you're doing the above, and make sure you're releasing them once you're done with them. One example of an object that you're not releasing is buttons.

You should also read up on how objects are retained. For example, when you remove a view from a superview, if it is not retained anywhere else, it'll be released. You don't need to explicitly set the value to nil.

Body:
I have successfully created a UITableView/UITableViewCell that is able to slide up and down and adjusting the height to show options. To see what this means, I have created a video here. The code is as follows:

- (void)swipe:(UISwipeGestureRecognizer *)recognizer direction:(UISwipeGestureRecognizerDirection)direction
{
    if (recognizer && recognizer.state == UIGestureRecognizerStateEnded)
    {
        // Get the table view cell where the swipe occured
        CGPoint location = [recognizer locationInView:self.tableView];
        NSIndexPath* indexPath = [self.tableView indexPathForRowAtPoint:location];
        MyCell* cell = (MyCell *) [self.tableView cellForRowAtIndexPath:indexPath];

        [self.tableView beginUpdates];

        //removing the options view at the other cell before adding a new one

        if (global != nil && global.row != indexPath.row){
            [sideSwipeView removeFromSuperview];
            sideSwipeView = nil;
        }

        //options already exist, we need to remove it
        if (sideSwipeView != nil){
            [sideSwipeView removeFromSuperview];
            sideSwipeView = nil;
            slide = NO;
        } else {
            //options do not exist and therefore we need to add it
            NSArray * buttonData = [[NSArray arrayWithObjects:
                                     [NSDictionary dictionaryWithObjectsAndKeys:@"Mark Read", @"title", @"mark.png", @"image", nil],
                                     [NSDictionary dictionaryWithObjectsAndKeys:@"Track", @"title", @"play.png", @"image", nil],
                                     nil] retain];

            NSMutableArray * buttons = [[NSMutableArray alloc] initWithCapacity:buttonData.count];
            sideSwipeView = [[UIView alloc] initWithFrame:CGRectMake(0, cell.frame.size.height-25, 320, 25)];
            [sideSwipeView setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin];
            [sideSwipeView setBackgroundColor:[UIColor colorWithPatternImage: [UIImage imageNamed:@"dotted-pattern.png"]]];
            [sideSwipeView setTag:-10];

            CGFloat leftEdge = BUTTON_LEFT_MARGIN;
            for (NSDictionary* buttonInfo in buttonData)
            {
                if (!([[buttonInfo objectForKey:@"title"] isEqualToString:@"Mark Read"] && [[[topics objectAtIndex:indexPath.row] unread] intValue] == 0))
                {

                    UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];

                    button.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleTopMargin;

                    UIImage* buttonImage = [UIImage imageNamed:[buttonInfo objectForKey:@"image"]];
                    if ([[topics objectAtIndex:indexPath.row] tracked] && [[buttonInfo objectForKey:@"title"] isEqualToString:@"Track"]){
                        buttonImage = [UIImage imageNamed:@"pause.png"];
                        [button setSelected:YES];
                    } else {
                        [button setSelected:NO];
                    }
                    button.frame = CGRectMake(leftEdge, 0, buttonImage.size.width, buttonImage.size.height);

                    UIImage* grayImage = [self imageFilledWith:[UIColor colorWithWhite:0.9 alpha:1.0] using:buttonImage];
                    [button setImage:grayImage forState:UIControlStateNormal];

                    if ([[buttonInfo objectForKey:@"title"] isEqualToString:@"Mark Read"]){
                        [button addTarget:self action:@selector(markRead:) forControlEvents:UIControlEventTouchUpInside];
                    } else if ([[buttonInfo objectForKey:@"title"] isEqualToString:@"Track"]){
                        [button addTarget:self action:@selector(track:) forControlEvents:UIControlEventTouchUpInside];
                    }
                    [button setTag:indexPath.row];
                    [buttons addObject:button];

                    [sideSwipeView addSubview:button];

                    leftEdge = leftEdge + buttonImage.size.width + BUTTON_SPACING;
                }
            }

            [cell.contentView addSubview:sideSwipeView];
            [sideSwipeView release];
            global = indexPath;
            slide = YES;

        }
        [self.tableView endUpdates];
        [self.tableView deselectRowAtIndexPath:indexPath animated:YES];

    }
}

However, I am not confident that the code is memory correct (i.e: ther's no memory leak and I am not misusing anything). I am mostly not confident in the sideSwipeView alloc, dealloc, and setting it up to nil. I think the others are fine. Can someone give me any pointers?

Profiler result:


问:
How to fix the issue:Your PHP installation appears to be missing the MySQL extension
Environment:os and apache and php and mariadb version.

```<code>uname -a
Linux MiWiFi-R3-srv 4.9.0-11-amd64 #1 SMP Debian 4.9.189-3+deb9u2 (2019-11-11) x86_64 GNU/Linux

sudo apachectl -v
Server version: Apache/2.4.25 (Debian)
Server built:   2019-10-13T15:43:54

php -v
PHP 7.0.33-0+deb9u6 (cli) (built: Oct 24 2019 18:50:20) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2017 Zend Technologies
    with Zend OPcache v7.0.33-0+deb9u6, Copyright (c) 1999-2017, by Zend Technologies
</code>```

Login mariadb with password and input status:

```<code>Server:         MariaDB
Server version:     10.1.41-MariaDB-0+deb9u1 Debian 9.9
</code>```

Check php-mysql:

```<code>sudo dpkg -l php-mysql
Desired=Unknown/Install/Remove/Purge/Hold
| Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend
|/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)
||/ Name           Version      Architecture Description
+++-==============-============-============-=================================
ii  php-mysql      1:7.0+49     all          MySQL module for PHP [default]
</code>```

Get the mysql.so library:

```<code>sudo find  /  -name  "*mysql.so"
/usr/lib/php/20151012/pdo_mysql.so
</code>```

Chekc all modules which contain mysql:

```<code>php -m |grep  mysql
PHP Warning:  PHP Startup: Unable to load dynamic library '/usr/lib/php/20151012/php_pdo_mysql.so' - /usr/lib/php/20151012/php_pdo_mysql.so: cannot open shared object file: No such file or directory in Unknown on line 0
mysqli
mysqlnd
pdo_mysql

sudo vim  /etc/php/7.0/fpm/php.ini
</code>```

Rewrite

```<code>; ... or under UNIX:
;
;extension=mysql.so
</code>```

as

```<code>extension=mysqli.so
</code>```

or

```<code>extension=mysqlnd.so
</code>```

or

```<code>extension=pdo_mysql.so
</code>```

Restart apache2 and mariadb database,the issue remains ,none of the three format can work,how to fix then?

答:
MatsLindh is right, mysql is deprecated from php 7, it seems that you have deployed old php5 code on the server that is why you received this error, now you can do two things

either install php5.6 and select the version for that website folder depending on which hosting you have and restart the server

or you can upgrade the code to php 7+ either yourself or by using tools which I do not know if it works perfectly, recently I came across this
Rector Tool for upgrading php legacy code

We were down the same path in previous months and and we updated mysql code to mysqli and also updated the classes declarations and added the necessary checking, fixed the error handling and we were able to run the legacy app on the php 7 successfully.
Sometime due to complicated development, it is not possible to upgrade in an instant and it is also not possible to start from the scratch either because of the business logic introduced over the years so changes can only be introduced with baby steps, I can say this because we handle our high traffic ecommerce site.

Body:
Environment:os and apache and php and mariadb version.

uname -a
Linux MiWiFi-R3-srv 4.9.0-11-amd64 #1 SMP Debian 4.9.189-3+deb9u2 (2019-11-11) x86_64 GNU/Linux

sudo apachectl -v
Server version: Apache/2.4.25 (Debian)
Server built:   2019-10-13T15:43:54

php -v
PHP 7.0.33-0+deb9u6 (cli) (built: Oct 24 2019 18:50:20) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2017 Zend Technologies
    with Zend OPcache v7.0.33-0+deb9u6, Copyright (c) 1999-2017, by Zend Technologies

Login mariadb with password and input status:

Server:         MariaDB
Server version:     10.1.41-MariaDB-0+deb9u1 Debian 9.9

Check php-mysql:

sudo dpkg -l php-mysql
Desired=Unknown/Install/Remove/Purge/Hold
| Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend
|/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)
||/ Name           Version      Architecture Description
+++-==============-============-============-=================================
ii  php-mysql      1:7.0+49     all          MySQL module for PHP [default]

Get the mysql.so library:

sudo find  /  -name  "*mysql.so"
/usr/lib/php/20151012/pdo_mysql.so

Chekc all modules which contain mysql:

php -m |grep  mysql
PHP Warning:  PHP Startup: Unable to load dynamic library '/usr/lib/php/20151012/php_pdo_mysql.so' - /usr/lib/php/20151012/php_pdo_mysql.so: cannot open shared object file: No such file or directory in Unknown on line 0
mysqli
mysqlnd
pdo_mysql

sudo vim  /etc/php/7.0/fpm/php.ini

Rewrite

; ... or under UNIX:
;
;extension=mysql.so

as

extension=mysqli.so

or

extension=mysqlnd.so

or

extension=pdo_mysql.so

Restart apache2 and mariadb database,the issue remains ,none of the three format can work,how to fix then?


问:
broadcasting across tensors in `pytorch`
I am using pytorch as an array processing language (not for the traditional deep learning purposes), and I am wondering what the canonical way is to do "batching" parallelism.

For example, suppose I want to compute svds of two dimensional layers of a 3-d tensor (using torch.svd(), say), and I want to return a tuple of stacked us, stacked s, stacked v.

Presumably, through the magic of SIMD parallelism, this should be doable in roughly the same time as a single layer svd (on gpu), but how to program it?

答:
PyTorch is a high level software library with lots of python wrappers for highly optimized compiled code. A function or operator either supports batch data or not.
There is no other way around it than writing your own C/C++/CUDA code and invoke it with python.

Luckily, most functions support batch processing (including torch.svd() as pointed out by jodag) and it can be assumed that the developers (or the compiler) paid attention to data parallelism in the implementation. I recommend you to stack your tensors wherever you can. It usually leads to significant speedups.

Note that the batch dimension is always the first dimension of a tensor. PyTorch supports broadcasting for common operators like +, -, *, / as documented here. Because of possible ambiguities you are sometimes required to reshape your data accordingly to make clear what you want. For example if you want to add a batch of scalars to a batch of vectors you need to do something like:

```<code>a = torch.zeros(2, 2)
b = torch.arange(2)
a + b.view(2, 1) # or b.reshape(2, 1)
# tensor([[0., 0.],
          [1., 1.]])
</code>```

Body:
PyTorch is a high level software library with lots of python wrappers for highly optimized compiled code. A function or operator either supports batch data or not.
There is no other way around it than writing your own C/C++/CUDA code and invoke it with python.

Luckily, most functions support batch processing (including torch.svd() as pointed out by jodag) and it can be assumed that the developers (or the compiler) paid attention to data parallelism in the implementation. I recommend you to stack your tensors wherever you can. It usually leads to significant speedups.

Note that the batch dimension is always the first dimension of a tensor. PyTorch supports broadcasting for common operators like +, -, *, / as documented here. Because of possible ambiguities you are sometimes required to reshape your data accordingly to make clear what you want. For example if you want to add a batch of scalars to a batch of vectors you need to do something like:

a = torch.zeros(2, 2)
b = torch.arange(2)
a + b.view(2, 1) # or b.reshape(2, 1)
# tensor([[0., 0.],
          [1., 1.]])


问:
Powershell regex group regex matches but doesn't have my group. What's missing?
I have some code that I am porting from a jenkins script and I need it as a shell command. So I know the regex works - What's blowing my mind is how it can match but then not have my capture group. What I need is just the root level directory names as such:

```<code>foo
baz
</code>```

How can it "match" but then not have my group? BTW: If there is a simpler way to achieve this, I am all ears.

PS E:\SysData\Jenkins\workspace\chb0_chb0mb_example> git diff --name-only origin/master  feature/foo |  %{ Resolve-Path -Relative $_ } | sls  '.\\.*\\.*'  | sls '\\.\\(.+?)\\.*|.*' | %{$_.matches}

Groups   : {0}
Success  : True
Name     : 0
Captures : {0}
Index    : 0
Length   : 48
Value    : .\foo\Nuget\deleteme.txt

Groups   : {0}
Success  : True
Name     : 0
Captures : {0}
Index    : 0
Length   : 55
Value    : .\baz\QC_OH_DARKESol\deleteme.txt

```

答:
js2010's helpful answer points out a potential problem with your approach (.\\ should be \.\\), succinctly demonstrates the unexplained behavior you've experienced (for which they've created a GitHub issue), and suggests a workaround (inserting | % Line).

To solve your problem more directly:

```<code># Inputs are sample paths.
'.\foo\Nuget\deleteme.txt',
'.\bar\QC_OH_DARKESol\deleteme.txt' |
  foreach { if ($_ -match '^\.\\([^\\]+)') { $Matches[1] } }
</code>```

The above yields the following strings:

```<code>foo
bar
</code>```

That is, it extracts the first path component following literal .\ from the input paths, using foreach (ForEach-Object) to apply -match, the regular-expression matching operator to each input string, whose matching results are reflected in the automatic $Matches variable, which is a hash table whose 0 entry is the overall match, with entry 1 containing the 1st capture group's value, 2 the 2nd's, ...; named capture groups (e.g., (?<root>...)), if present, have entries by their name (e.g., root).

An alternative is to use the switch statement with the -Regex option:

```<code>switch -Regex (
  git diff --name-only origin/master feature/foo | Resolve-Path -Relative
) {
  '^\.\\([^\\]+)' { $Matches[1] }
}
</code>```

Body:
I have some code that I am porting from a jenkins script and I need it as a shell command. So I know the regex works - What's blowing my mind is how it can match but then not have my capture group. What I need is just the root level directory names as such:

foo
baz

How can it "match" but then not have my group? BTW: If there is a simpler way to achieve this, I am all ears.

PS E:\SysData\Jenkins\workspace\chb0_chb0mb_example> git diff --name-only origin/master  feature/foo |  %{ Resolve-Path -Relative $_ } | sls  '.\\.*\\.*'  | sls '\\.\\(.+?)\\.*|.*' | %{$_.matches}

Groups   : {0}
Success  : True
Name     : 0
Captures : {0}
Index    : 0
Length   : 48
Value    : .\foo\Nuget\deleteme.txt

Groups   : {0}
Success  : True
Name     : 0
Captures : {0}
Index    : 0
Length   : 55
Value    : .\baz\QC_OH_DARKESol\deleteme.txt

Body:
js2010's helpful answer points out a potential problem with your approach (.\\ should be \.\\), succinctly demonstrates the unexplained behavior you've experienced (for which they've created a GitHub issue), and suggests a workaround (inserting | % Line).

To solve your problem more directly:

# Inputs are sample paths.
'.\foo\Nuget\deleteme.txt',
'.\bar\QC_OH_DARKESol\deleteme.txt' |
  foreach { if ($_ -match '^\.\\([^\\]+)') { $Matches[1] } }

The above yields the following strings:

foo
bar

That is, it extracts the first path component following literal .\ from the input paths, using foreach (ForEach-Object) to apply -match, the regular-expression matching operator to each input string, whose matching results are reflected in the automatic $Matches variable, which is a hash table whose 0 entry is the overall match, with entry 1 containing the 1st capture group's value, 2 the 2nd's, ...; named capture groups (e.g., (?<root>...)), if present, have entries by their name (e.g., root).

An alternative is to use the switch statement with the -Regex option:

switch -Regex (
  git diff --name-only origin/master feature/foo | Resolve-Path -Relative
) {
  '^\.\\([^\\]+)' { $Matches[1] }
}


问:
Distinct Pairing of users of different groups using Sql
50 Users with a record format

Id,

Name,

Group_Id

And Groups

```<code>1,
2,
3
</code>```

Are to be inserted into a pairs table in the format

Id,

Pair_1,

Pair_2

Note

Users belongs to different groups.

Users from group 2 cannot pair with each other and users from group 3 can also not pair with each other, duplicates must also be avoided.

How do i go about this in Sql. Am a novice.

答:
This is a sample data in Javascript
[
{
Id:1,
Name:"James",
Group_Id:3
},
{
Id:2,
Name:"Daniel",
Group_Id:3
},
{
Id:3,
Name:"Jonathan",
Group_Id:2
},
{
Id:4,
Name:"Esther",
Group_Id:1
},
{
Id:5,
Name:"Leo",
Group_Id:1
}
]

Pair_1 & Pair_2 are two paired users to be added to a pairs table based on the condition explained earlier.

Body:
50 Users with a record format

Id,

Name,

Group_Id

And Groups

1,
2,
3

Are to be inserted into a pairs table in the format

Id,

Pair_1,

Pair_2

Note

Users belongs to different groups.

Users from group 2 cannot pair with each other and users from group 3 can also not pair with each other, duplicates must also be avoided.

How do i go about this in Sql. Am a novice.


问:
How to use custom variable in JavaScript
I just want to know to how to use custom varible with javascript.suppose we have 5 id with name zawsz,baws2,tawsx,paws4,vawsa and we want to execute single DOM command to all these element whose id is define here.

```<code>document.getElementById("-aws-").onclick=function(){}
</code>```

Here -aws- define all the id define above.(-) can be replace with any char/int value;

答:
You can use document.querySelectorAll for this:

```<code>document.querySelectorAll('[id^="aws"]')
</code>```

That will select all elements where the id attribute starts with (^=) "aws".

Body:
I just want to know to how to use custom varible with javascript.suppose we have 5 id with name zawsz,baws2,tawsx,paws4,vawsa and we want to execute single DOM command to all these element whose id is define here.

document.getElementById("-aws-").onclick=function(){}

Here -aws- define all the id define above.(-) can be replace with any char/int value;

Body:
You can use document.querySelectorAll for this:

document.querySelectorAll('[id^="aws"]')

That will select all elements where the id attribute starts with (^=) "aws".


问:
Understanding the difference between numpy.log and numpy.sum for custom array containers
I am creating a custom container for a NumPy array by following the instructions on the SciPy website. I've written the following code which:

creates a class, NpContainer

defines custom behavior for the functions np.sum and np.log to output a string.

import numpy as np

HANDLED_FUNCTIONS = {}

class NpContainer:
    def __init__(self, val):
        self.val = val

    def __array__(self):
        return np.array(self.val)

    def __array_function__(self, func, types, args, kwargs):
        if func not in HANDLED_FUNCTIONS:
            raise NotImplementedError()

        return HANDLED_FUNCTIONS[func](*args, **kwargs)

def implements(np_function):
    def decorator(func):
        HANDLED_FUNCTIONS[np_function] = func
        return func
    return decorator

@implements(np.sum)
def sum(a, **kwargs):
    return 'Sum Val: {}'.format(np.sum(a.val, **kwargs))

@implements(np.log)
def log(a, **kwargs):
    return 'Log Val: {}'.format(np.log(a, **kwargs))
```

<p>I test the code using:</p>

<pre class="lang-py prettyprint-override"><code>if __name__ == "__main__":
    container1 = NpContainer(val=np.array([1., 2.]))

    sum_result = np.sum(container1)
    print(sum_result)
    print(type(sum_result))

    log_result = np.log(container1)
    print(log_result)
    print(type(log_result))
</code>```

Sum produces the expected result.

```<code>Sum Val: 3.0
<class 'str'>
</code>```

However np.log returns a NumPy array instead of a string.

```<code>[0.         0.69314718]
<class 'numpy.ndarray'>
</code>```

Does anyone know why np.log skips my custom-defined function? Any help is appreciated!

答:
Ok, so I think - I know what is happening. You implemented function __array_function__, which should fit np.sum but for np.log you should do __array_ufunc__, since it is an universal function (https://docs.scipy.org/doc/numpy/reference/arrays.classes.html#numpy.class.array_ufunc).

There's some more flavour to it, which I recommend you to check out here:

https://numpy.org/neps/nep-0018-array-function-protocol.html

Now oddly enough- once __array_ufunc__ is implemented, even np.sum will be processed as ufunc, which messes up with the decorator.

ufunc auto-casted function for np.sum is np.add, so the below will do the trick for you - although I would rather recommend to implement sum() as a function for NpContainer - so you can do container1.sum() instead

import numpy as np

HANDLED_FUNCTIONS = {}

class NpContainer:
    def __init__(self, val):
        self.val = val

    def __array__(self):
        return np.array(self.val)

    def __array_function__(self, func, types, args, kwargs):
        if func not in HANDLED_FUNCTIONS:
            raise NotImplementedError()

        return HANDLED_FUNCTIONS[func](*args, **kwargs)

    def __array_ufunc__(self, ufunc, method, *args, **kwargs):
        if ufunc not in HANDLED_FUNCTIONS:
            raise NotImplementedError()

        return HANDLED_FUNCTIONS[ufunc](*args, **kwargs)

def implements(np_function):
    def decorator(func):
        HANDLED_FUNCTIONS[np_function] = func
        return func
    return decorator

@implements(np.add)
def sum(a, **kwargs):
    return 'Sum Val: {}'.format(np.sum(a.val, **kwargs))

@implements(np.log)
def log(a, **kwargs):
    return 'Log Val: {}'.format(np.log(a.val, **kwargs))

if __name__ == "__main__":
    container1 = NpContainer(val=np.array([1., 2.]))

    log_result = np.log(container1)
    print(log_result)
    print(type(log_result))

    sum_result = np.sum(container1)
    print(sum_result)
    print(type(sum_result))
```

Body:
I am creating a custom container for a NumPy array by following the instructions on the SciPy website. I've written the following code which:

creates a class, NpContainer

defines custom behavior for the functions np.sum and np.log to output a string.

import numpy as np

HANDLED_FUNCTIONS = {}

class NpContainer:
    def __init__(self, val):
        self.val = val

    def __array__(self):
        return np.array(self.val)

    def __array_function__(self, func, types, args, kwargs):
        if func not in HANDLED_FUNCTIONS:
            raise NotImplementedError()

        return HANDLED_FUNCTIONS[func](*args, **kwargs)

def implements(np_function):
    def decorator(func):
        HANDLED_FUNCTIONS[np_function] = func
        return func
    return decorator

@implements(np.sum)
def sum(a, **kwargs):
    return 'Sum Val: {}'.format(np.sum(a.val, **kwargs))

@implements(np.log)
def log(a, **kwargs):
    return 'Log Val: {}'.format(np.log(a, **kwargs))

I test the code using:

if __name__ == "__main__":
    container1 = NpContainer(val=np.array([1., 2.]))

    sum_result = np.sum(container1)
    print(sum_result)
    print(type(sum_result))

    log_result = np.log(container1)
    print(log_result)
    print(type(log_result))

Sum produces the expected result.

Sum Val: 3.0
<class 'str'>

However np.log returns a NumPy array instead of a string.

[0.         0.69314718]
<class 'numpy.ndarray'>

Does anyone know why np.log skips my custom-defined function? Any help is appreciated!