问:
Mysqli bind parameters not working
I'm trying to use prepared statements to enter data in a database. The unprepared statement works but this prepared statement does not. I can't find out why.
Prepared version:

```<code>$stmt = $mysqli->prepare("INSERT INTO videos (file_name, upload_by, date, path)
VALUES (?, ?, ?, ?)");
$stmt->bind_param('ssss', $newstring, $id, $date->format('Y-m-d'), $location);
$stmt->execute();
</code>```

Unprepared version:

```<code>  $sql = "INSERT INTO videos (file_name, upload_by, date, path) VALUES ('$newstring', '$id', '
          $date', 'Nominator/$location$newstring')";
  mysqli_query($mysqli, $sql);
</code>```

答:
Replace $stmt-execute(); with $stmt->execute();

Also, don't use date and path in query. Rename them with some other name like date1 and path1.

Update your Query like below that will surely work (Tested Offline):

```<code><?php
$mysqli = new mysqli('localhost', 'root', '', 'test2');

if ($mysqli->errno) {
printf("Connect failed: %s\n", $mysqli->error);
exit();
}

$stmt = $mysqli->prepare("INSERT INTO videos (file_name, upload_by, date1, path1) VALUES (?, ?, ?, ?)");
$stmt->bind_param('ssss', $file_name, $upload_by, $date1, $path1);
$date1 = date("Y-m-d");
$file_name = "test.jpg";
$upload_by = "amit";
$path1 = "test";
if ($result = $stmt->execute()){
echo "success";
$stmt->free_result();
} else {
echo "error";
}
$stmt->close();
?>
</code>```

Title: Mysqli bind parameters not working

Body:
I'm trying to use prepared statements to enter data in a database. The unprepared statement works but this prepared statement does not. I can't find out why.
Prepared version:

$stmt = $mysqli->prepare("INSERT INTO videos (file_name, upload_by, date, path)
VALUES (?, ?, ?, ?)");
$stmt->bind_param('ssss', $newstring, $id, $date->format('Y-m-d'), $location);
$stmt->execute();

Unprepared version:

  $sql = "INSERT INTO videos (file_name, upload_by, date, path) VALUES ('$newstring', '$id', '
          $date', 'Nominator/$location$newstring')";
  mysqli_query($mysqli, $sql);

Body:
Replace $stmt-execute(); with $stmt->execute();

Also, don't use date and path in query. Rename them with some other name like date1 and path1.

Update your Query like below that will surely work (Tested Offline):

<?php
$mysqli = new mysqli('localhost', 'root', '', 'test2');

if ($mysqli->errno) {
printf("Connect failed: %s\n", $mysqli->error);
exit();
}

$stmt = $mysqli->prepare("INSERT INTO videos (file_name, upload_by, date1, path1) VALUES (?, ?, ?, ?)");
$stmt->bind_param('ssss', $file_name, $upload_by, $date1, $path1);
$date1 = date("Y-m-d");
$file_name = "test.jpg";
$upload_by = "amit";
$path1 = "test";
if ($result = $stmt->execute()){
echo "success";
$stmt->free_result();
} else {
echo "error";
}
$stmt->close();
?>


来源: stackexchange

问:
rewriting an iOS app to work on both iOS and Mac-- how to organize controller code?
I have an iOS app that I am rewriting to work on both Mac and iOS.  I have my views working reasonably well, but everything is static at the moment.

What do I typically do with my view controller code?  In the iOS-only app, it is typically a bunch of stuff that says things like "if the user touches here, do that."

I've found the hitTest: method.  So I'm pretty sure I can write everything so it works.  I guess my question is more organizational.  Ideally, I would want to set things up so that the code that is currently in UIViewController subclasses would work on both platforms.

答:
You won't be able to make the UIViewController code work on both platforms. The Mac doesn't have UIKit, and iPhone doesn't have AppKit.

What you really want to do at this point is have all of your networking, math and logic code in external classes. Normally subclasses of NSObject. Then, all you have to do is write code that calls these classes within your view controllers.

You're going to face one further challenge though - I don't think that you can have an app run on iPhone and Mac from one Bundle. When you compile your app, you normally compile to a specific processor. The Mac runs on Intel/PowerPC, and iPhone runs on Arm. You're going to have to fiddle with build targets etc. endlessly.

I would suggest maintaining two separate projects, and putting the aforementioned logic classes in a shared location and making sure that when you import them you don't choose the 'Copy to group destination folder' option. This way, any edits you make to the iPhone version of the code carries accross to the Mac version and vice-versa.

Happy coding,

Zane

ContentLicense: CC BY-SA 2.5


问:
BeanUtils.copyProperties and nested List

I want to convert an object to another one, and for that I use Spring BeanUtils. But a property 'foo' of type Bag<X> (issued from Hibernate) is copied in the target object of type List<Y> without problem.

The corresponding setter is used : setFoo(List<Y> foo) and in debug mode I see that 'foo' is of type Bag<X>.

Edit: example

```<code>class Foo {
    List<Integer> list = new ArrayList<Integer>() {{add(1);}};

    public List<Integer> getList() {
        return list;
    }

    public void setList(List<Integer> list) {
        this.list = list;
    }
}

class Bar {
    List<Double> list = new ArrayList<Double>() {{add(1.0);}};

    public List<Double> getList() {
        return list;
    }

    public void setList(List<Double> list) {
        this.list = list;
    }
}
</code>```

Then :

```<code>Foo foo = new Foo();
Bar bar = new Bar();
Bar bar2 = new Bar();
org.apache.commons.beanutils.BeanUtils.copyProperties(foo, bar);
org.springframework.beans.BeanUtils.copyProperties(foo, bar2);
</code>```

Result : bar.getList() is a List of Double (no modification) and bar2.getList() is a List of Integer (property copied from source to target).

Why no ClassCastException is thrown ?
How can Spring set this property ?

Thanks for your help.

答:
This is because, As you can see in this link

```<code>public class Bag
extends ODMGCollection
implements org.odmg.DBag, List
</code>```

Bag implements List.

ContentLicense: CC BY-SA 3.0

Body:
I want to convert an object to another one, and for that I use Spring BeanUtils. But a property 'foo' of type Bag<X> (issued from Hibernate) is copied in the target object of type List<Y> without problem.

The corresponding setter is used : setFoo(List<Y> foo) and in debug mode I see that 'foo' is of type Bag<X>.

Edit: example

class Foo {
    List<Integer> list = new ArrayList<Integer>() {{add(1);}};

    public List<Integer> getList() {
        return list;
    }

    public void setList(List<Integer> list) {
        this.list = list;
    }
}

class Bar {
    List<Double> list = new ArrayList<Double>() {{add(1.0);}};

    public List<Double> getList() {
        return list;
    }

    public void setList(List<Double> list) {
        this.list = list;
    }
}

Then :

Foo foo = new Foo();
Bar bar = new Bar();
Bar bar2 = new Bar();
org.apache.commons.beanutils.BeanUtils.copyProperties(foo, bar);
org.springframework.beans.BeanUtils.copyProperties(foo, bar2);

Result : bar.getList() is a List of Double (no modification) and bar2.getList() is a List of Integer (property copied from source to target).

Why no ClassCastException is thrown ?
How can Spring set this property ?

Thanks for your help.

Body:
This is because, As you can see in this link

public class Bag
extends ODMGCollection
implements org.odmg.DBag, List

Bag implements List.


问:
How to add option "params" in dropzone.js Angular4
I'm making an application in angular 4. I'm using dropzone.js to transfer files to back. To use Dropzone.js in angular 4, I'm using ngx-dropzone-wrapper.

I want to pass a new parameters when a file is sent (with the 'params' options). The parameters is a function that return a string, and the result change on a user click. It's actually a Singleton and the first time it's created is in the ngOnInit() function in the app.component.ts file.

My app.module.ts look like this (where the dropzone.js module is added to the project):

```<code>import { DropzoneModule, DropzoneConfigInterface } from 'ngx-dropzone-wrapper';
const DROPZONE_CONFIG: DropzoneConfigInterface = {
    url: 'http://localhost:81/api/createFiles',
    maxFilesize: 50,
    acceptedFiles: 'image/*',
    params: { 'whereToCreate': **the function goes here** }
};

@NgModule({
...
imports: [
    ...
    DropzoneModule.forRoot(DROPZONE_CONFIG)
</code>```

My HTML using the ngx-dropzone-wrapper (it's exactly like the example in the github of ngx-dropzone-wrapper):

```<code><dropzone [config]="config" [message]="'Click or drag images here to upload'" (error)="onUploadError($event)" (success)="onUploadSuccess($event)"></dropzone>
</code>```

答:
Try this:
When the file is sent it will trigger and many event among them sending event in this event you receive as parameters File , xhr, formData in the formData you can .append(key, value). Then it will send along with each file the new params.
Your html:

```<code>        <div class="text-center well">
          <dropzone [config]="dropzoneConfigI"
                [message]="'Click or drag images here to upload'"
                (error)="onError($event)"
                (sending)="onSending($event)"
                (sendingmultiple)="onSendingmultiple($event)"
                (success)="onSuccess($event)"
                (addedfile)="onAddedFile($event)"
           >
           </dropzone>
    </div>
</code>```

your controller:

```<code>  onSending(data): void {
    // data [ File , xhr, formData]
    const file = data[0];
    const formData = data[2];
    formData.append('order', someIteratorValue);
  }
</code>```

Hope it helps.

Body:
I'm making an application in angular 4. I'm using dropzone.js to transfer files to back. To use Dropzone.js in angular 4, I'm using ngx-dropzone-wrapper.

I want to pass a new parameters when a file is sent (with the 'params' options). The parameters is a function that return a string, and the result change on a user click. It's actually a Singleton and the first time it's created is in the ngOnInit() function in the app.component.ts file.

My app.module.ts look like this (where the dropzone.js module is added to the project):

import { DropzoneModule, DropzoneConfigInterface } from 'ngx-dropzone-wrapper';
const DROPZONE_CONFIG: DropzoneConfigInterface = {
    url: 'http://localhost:81/api/createFiles',
    maxFilesize: 50,
    acceptedFiles: 'image/*',
    params: { 'whereToCreate': **the function goes here** }
};

@NgModule({
...
imports: [
    ...
    DropzoneModule.forRoot(DROPZONE_CONFIG)

My HTML using the ngx-dropzone-wrapper (it's exactly like the example in the github of ngx-dropzone-wrapper):

<dropzone [config]="config" [message]="'Click or drag images here to upload'" (error)="onUploadError($event)" (success)="onUploadSuccess($event)"></dropzone>

Body:
Try this:
When the file is sent it will trigger and many event among them sending event in this event you receive as parameters File , xhr, formData in the formData you can .append(key, value). Then it will send along with each file the new params.
Your html:

        <div class="text-center well">
          <dropzone [config]="dropzoneConfigI"
                [message]="'Click or drag images here to upload'"
                (error)="onError($event)"
                (sending)="onSending($event)"
                (sendingmultiple)="onSendingmultiple($event)"
                (success)="onSuccess($event)"
                (addedfile)="onAddedFile($event)"
           >
           </dropzone>
    </div>

your controller:

  onSending(data): void {
    // data [ File , xhr, formData]
    const file = data[0];
    const formData = data[2];
    formData.append('order', someIteratorValue);
  }

Hope it helps.


问:
Scala Iterator.takeWhile is dropping the failed element
```<code>val i = (1 to 8).toIterator
val oneToThree = i.takeWhile(_ <= 3).toList
// List(1, 2, 3)
</code>```

So far so good.
Now I want the iterator to still contain (3, 4, 5, 6, 7, 8), but if I carry on:

```<code>val fourToSix = i.takeWhile(_ <= 6).toList
// List(5, 6)
</code>```

Element 3 has gone missing. I would preferably like fourToSix to be List(4, 5, 6). How can I use takeWhile or some similar operation so that this works?

答:
Note that the documentation on takeWhile states:

Reuse: After calling this method, one should discard the iterator it
  was called on, and use only the iterator that was returned. Using the
  old iterator is undefined, subject to change, and may result in
  changes to the new iterator as well.

So you shouldn't use i, after calling takeWhile on it.

But to achieve what you want you can use the span method:

```<code>scala> val i = (1 to 8).iterator
i: Iterator[Int] = non-empty iterator

scala> val (oneToThree, rest) = i.span(_ <= 3)
oneToThree: Iterator[Int] = non-empty iterator
rest: Iterator[Int] = unknown-if-empty iterator

scala> oneToThree.toList
res1: List[Int] = List(1, 2, 3)

scala> val fourToSix = rest.takeWhile(_ <= 6)
fourToSix: Iterator[Int] = non-empty iterator

scala> fourToSix.toList
res2: List[Int] = List(4, 5, 6)
</code>```

Body:
val i = (1 to 8).toIterator
val oneToThree = i.takeWhile(_ <= 3).toList
// List(1, 2, 3)

So far so good.
Now I want the iterator to still contain (3, 4, 5, 6, 7, 8), but if I carry on:

val fourToSix = i.takeWhile(_ <= 6).toList
// List(5, 6)

Element 3 has gone missing. I would preferably like fourToSix to be List(4, 5, 6). How can I use takeWhile or some similar operation so that this works?

Body:
Note that the documentation on takeWhile states:

Reuse: After calling this method, one should discard the iterator it
  was called on, and use only the iterator that was returned. Using the
  old iterator is undefined, subject to change, and may result in
  changes to the new iterator as well.

So you shouldn't use i, after calling takeWhile on it.

But to achieve what you want you can use the span method:

scala> val i = (1 to 8).iterator
i: Iterator[Int] = non-empty iterator

scala> val (oneToThree, rest) = i.span(_ <= 3)
oneToThree: Iterator[Int] = non-empty iterator
rest: Iterator[Int] = unknown-if-empty iterator

scala> oneToThree.toList
res1: List[Int] = List(1, 2, 3)

scala> val fourToSix = rest.takeWhile(_ <= 6)
fourToSix: Iterator[Int] = non-empty iterator

scala> fourToSix.toList
res2: List[Int] = List(4, 5, 6)


问:
Multiplication formula string - java
I'm trying to write a code that take a string : (7+5)*(6+9)
and return the string : 7*6 + 7*9 + 5*6 + 5*9
my algorithm is to create 2 char arrays (for this example : 75,69)
and run in O^2 loop in this 2 arrays and copy value from first array , * value from second array, +. i get index of bounds exception and don't understand why.

this is my code :

```<code> String s = "((7+5)*(6+9))";

 char[] ch = s.toCharArray();
 char[] newCh = new char[30];
 int j=0;
 int blocks = 2;
 int newi = 0;

 for (int i=0 ; i<ch.length ; i++) {
    if (ch[i]=='(' && ch[i+1]!='(') {
        j=i+1;
        while (blocks>0) {

            if (ch[j]==')') {
                blocks--;
                newCh[newi]='-';
                newi++;

            }
            if (ch[j]!='+' && ch[j]!='*' && ch[j]!=')' && ch[j]!='(') {
                if (blocks==0) {

                    break;
                }
                else {

                    newCh[newi]=ch[j];
                    newi++;
                }

            }
            j++;
        }

    }
    continue;
 }

 System.out.println("new Char array : ");
 for (int i=0 ; i<newCh.length ; i++) {
     System.out.print(newCh[i]);
 }
 System.out.println();

 Multy(newCh);
</code>```

and my multy method :

```<code>public static char[] Multy(char[] ch) {
 char[] newc = new char[50];
 char[] c1 = new char[30];
 char[] c2 = new char[30];
 int newi = 0;
 int i1 = 0;
 int i2 = 0;
 int flag = 0;

 for (int i=0 ; i<ch.length ; i++) {
     if (ch[i]!='-') {
         if (flag ==0) {
        c1[i1] = ch[i];
        i1++;
         }
         else {
             if (ch[i]!='-')
             c2[i2]= ch[i];
             i2++;
         }
     }
     if (ch[i]=='-')
         flag = 1;

 }
 System.out.println("In func");

 System.out.print("c1 : ");
 for (int i=0 ; i<c1.length ; i++) {
     System.out.print(c1[i]);
 }
 System.out.println();
 System.out.print("c2 : ");
 for (int i=0 ; i<c1.length ; i++) {
     System.out.print(c2[i]);
 }
 ///////////

 for (int i=0 ; i<c1.length ; i++) {
    for (int j=0 ; j<c2.length ; j++) {
        newc[newi]=c1[i];

        newc[newi+1] = '*';

        newc[newi+2] = c2[j];

        newc[newi+3] = '+';

        newi+=4;

    }
 }

 System.out.print("NEWc2 : ");
 for (int i=0 ; i<newc.length ; i++) {
     System.out.print(newc[i]);
 }

 return newc;
</code>```

}

答:
in te double for loop you iterate to the end of the array (c1.length and c2.length) while you add to a number in the loop newc[newi+X] but because you loop to the end you will run out of places and you will get the IndexOutOfBoundsException...

```<code>for (int i=0 ; i<c1.length ; i++) {
    for (int j=0 ; j<c2.length ; j++) {
        newc[newi]=c1[i];
        newc[newi+1] = '*';
        newc[newi+2] = c2[j];
        newc[newi+3] = '+';
        newi+=4;
    }
}
</code>```

UPDATE:

Extra explanation :-)

If you do something like this:

```<code>public class ArrayExample {
    public static void main(String[] args) {
        String[] strings = new String[3];
        System.out.println("strings.length = " + strings.length);
        strings[4] = "foo";
    }
}
</code>```

The output will be:

```<code>strings.length = 3
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
    at nl.ivonet.ArrayExample.main(ArrayExample.java:26)
</code>```

This is because I tried to assign a value at index 4 of the strings array, but the strings array was initialized with new String[3] giving it a fixed size of 3. That's what goes wrong and why your code failed.
An Array is not the same as a List. And Array is fixed size and a list not.

Title: Multiplication formula string - java

Body:
I'm trying to write a code that take a string : (7+5)*(6+9)
and return the string : 7*6 + 7*9 + 5*6 + 5*9
my algorithm is to create 2 char arrays (for this example : 75,69)
and run in O^2 loop in this 2 arrays and copy value from first array , * value from second array, +. i get index of bounds exception and don't understand why.

this is my code :

 String s = "((7+5)*(6+9))";

 char[] ch = s.toCharArray();
 char[] newCh = new char[30];
 int j=0;
 int blocks = 2;
 int newi = 0;

 for (int i=0 ; i<ch.length ; i++) {
    if (ch[i]=='(' && ch[i+1]!='(') {
        j=i+1;
        while (blocks>0) {

            if (ch[j]==')') {
                blocks--;
                newCh[newi]='-';
                newi++;

            }
            if (ch[j]!='+' && ch[j]!='*' && ch[j]!=')' && ch[j]!='(') {
                if (blocks==0) {

                    break;
                }
                else {

                    newCh[newi]=ch[j];
                    newi++;
                }

            }
            j++;
        }

    }
    continue;
 }

 System.out.println("new Char array : ");
 for (int i=0 ; i<newCh.length ; i++) {
     System.out.print(newCh[i]);
 }
 System.out.println();

 Multy(newCh);

and my multy method :

public static char[] Multy(char[] ch) {
 char[] newc = new char[50];
 char[] c1 = new char[30];
 char[] c2 = new char[30];
 int newi = 0;
 int i1 = 0;
 int i2 = 0;
 int flag = 0;

 for (int i=0 ; i<ch.length ; i++) {
     if (ch[i]!='-') {
         if (flag ==0) {
        c1[i1] = ch[i];
        i1++;
         }
         else {
             if (ch[i]!='-')
             c2[i2]= ch[i];
             i2++;
         }
     }
     if (ch[i]=='-')
         flag = 1;

 }
 System.out.println("In func");

 System.out.print("c1 : ");
 for (int i=0 ; i<c1.length ; i++) {
     System.out.print(c1[i]);
 }
 System.out.println();
 System.out.print("c2 : ");
 for (int i=0 ; i<c1.length ; i++) {
     System.out.print(c2[i]);
 }
 ///////////

 for (int i=0 ; i<c1.length ; i++) {
    for (int j=0 ; j<c2.length ; j++) {
        newc[newi]=c1[i];

        newc[newi+1] = '*';

        newc[newi+2] = c2[j];

        newc[newi+3] = '+';

        newi+=4;

    }
 }

 System.out.print("NEWc2 : ");
 for (int i=0 ; i<newc.length ; i++) {
     System.out.print(newc[i]);
 }

 return newc;

}

Body:
in te double for loop you iterate to the end of the array (c1.length and c2.length) while you add to a number in the loop newc[newi+X] but because you loop to the end you will run out of places and you will get the IndexOutOfBoundsException...

for (int i=0 ; i<c1.length ; i++) {
    for (int j=0 ; j<c2.length ; j++) {
        newc[newi]=c1[i];
        newc[newi+1] = '*';
        newc[newi+2] = c2[j];
        newc[newi+3] = '+';
        newi+=4;
    }
}

UPDATE:

Extra explanation :-)

If you do something like this:

public class ArrayExample {
    public static void main(String[] args) {
        String[] strings = new String[3];
        System.out.println("strings.length = " + strings.length);
        strings[4] = "foo";
    }
}

The output will be:

strings.length = 3
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
    at nl.ivonet.ArrayExample.main(ArrayExample.java:26)

This is because I tried to assign a value at index 4 of the strings array, but the strings array was initialized with new String[3] giving it a fixed size of 3. That's what goes wrong and why your code failed.
An Array is not the same as a List. And Array is fixed size and a list not.


问:
Pandas aggregate data and arrange over columns
I have a dataframe that looks like this:

```<code>     Values  State   Sort
3    a       Open    42
4    b       Close   42
5    d       Open    42
6    c       Open    42
7    b       Open    42
8    a       Open    45
9    d       Open    45
10   a       Open    45
11   c       Open    45
12   c       Open    45
13   d       Open    45
14   d       Open    46
15   b       Open    46
16   b       Open    46
17   c       Open    46
18   a       Open    46
</code>```

How can I aggregate the data so that it counts the values in columns "Values" and arranges the data over columns as per the values in column "Sort" to look like below:

```<code>Values   State   42   45   46
a        Open    1    2    1
b        Close   1    0    0
b        Open    1    0    2
c        Open    1    2    1
d        Open    1    2    1
</code>```

I wrote the following code for the same

```<code>tables_df = pd.DataFrame(alerts_df.groupby(['Values','State','Sort']).size().rename('Count'))
tables_df = pd.pivot_table(alerts_df, index=['Values','State'], columns=['Sort'], values=['Count'], aggfunc=np.sum)
tables_df=tables_df.reset_index()
</code>```

But it's returning an empty dataframe.

What am I doing wrong? Also is there a way to do this without using pivot table in pandas?

答:
I think you need:</p>

```<code>alerts_df = (alerts_df.groupby(['Values','State','Sort'])
                     .size()
                     .unstack(fill_value=0)
                     .reset_index()
                     .rename_axis(None, 1))
print (alerts_df)
  Values  State  42  45  46
0      a   Open   1   2   1
1      b  Close   1   0   0
2      b   Open   1   0   2
3      c   Open   1   2   1
4      d   Open   1   2   1
</code>```

Body:
I have a dataframe that looks like this:

     Values  State   Sort
3    a       Open    42
4    b       Close   42
5    d       Open    42
6    c       Open    42
7    b       Open    42
8    a       Open    45
9    d       Open    45
10   a       Open    45
11   c       Open    45
12   c       Open    45
13   d       Open    45
14   d       Open    46
15   b       Open    46
16   b       Open    46
17   c       Open    46
18   a       Open    46

How can I aggregate the data so that it counts the values in columns "Values" and arranges the data over columns as per the values in column "Sort" to look like below:

Values   State   42   45   46
a        Open    1    2    1
b        Close   1    0    0
b        Open    1    0    2
c        Open    1    2    1
d        Open    1    2    1

I wrote the following code for the same

tables_df = pd.DataFrame(alerts_df.groupby(['Values','State','Sort']).size().rename('Count'))
tables_df = pd.pivot_table(alerts_df, index=['Values','State'], columns=['Sort'], values=['Count'], aggfunc=np.sum)
tables_df=tables_df.reset_index()

But it's returning an empty dataframe.

What am I doing wrong? Also is there a way to do this without using pivot table in pandas?

Body:
I think you need:

alerts_df = (alerts_df.groupby(['Values','State','Sort'])
                     .size()
                     .unstack(fill_value=0)
                     .reset_index()
                     .rename_axis(None, 1))
print (alerts_df)
  Values  State  42  45  46
0      a   Open   1   2   1
1      b  Close   1   0   0
2      b   Open   1   0   2
3      c   Open   1   2   1
4      d   Open   1   2   1


问:
Browser does not recoginize JQuery prettyPhoto() when using asp.net Masterpage
```<code><script src="Scripts/jquery.prettyPhoto.js" type="text/javascript"></script>
<script src="Scripts/jquery-1.4.4.min.js" type="text/javascript"></script>

<a href="http://www.youtube-nocookie.com/v/Bkjv9SscotY&hl=it_IT&fs=1?rel=0" rel="prettyPhoto" title="">you tube
</a>
<script type="text/javascript">

    $(document).ready(
function () {
    $(
"a[rel^='prettyPhoto']").prettyPhoto();
});

</script>
</code>```

答:
Use</p>

```<code><script src="<%= ResolveUrl("~/Scripts/jquery.prettyPhoto.js") %>" type="text/javascript"></script>
</code>```

Body: you tube

Body:
Use

<script src="<%= ResolveUrl("~/Scripts/jquery.prettyPhoto.js") %>" type="text/javascript"></script>


问:
How can I safely print something to kmsg in interrupt context
I have a requirement to print a message to kernel log in an Irq service routine, so it's in "interrupt context". I understand that printk is not recommended for this scenario, so what would be the best alternatives here?
Thanks for if any suggestions.

I heard of one option about printk_deferred, I noticed this is used in scheduler, but haven't yet found where it's used in irq isr. Can anyone explain what's the difference between printk_deferred and printk?

答: One common idea is from interrupt handler we can update variables or info to be printed and then from kernel thread print that value to kernel log buffer. This way handler will remain intact and our objective will also be achieved.</p>


问:
HtmlAgilityPack - Nothing displays in the textbox
I have a Windows Form with a text box, and the code is suppose to pull information from a website using the xpath I got via chromes developer tools and display it in said text box.

The problem is when I run the program nothing displays in the text box. I'm not sure if my code that is used to get the information is wrong or if my code to display said information is wrong. Please note this code utilizes HtmlAgilityPack.

Here is the code in question:

```<code>private void richTextBox1_TextChanged(object sender, EventArgs e)
    {
        string Url = "https://apps.ko.com/aami/iguest/default.asp";
        HtmlWeb web = new HtmlWeb();
        HtmlAgilityPack.HtmlDocument doc = web.Load(Url);

        string username = doc.DocumentNode.SelectNodes("/html/body/center/div/table/tr[1]/td[2]/strong")[0].InnerText;
        string password = doc.DocumentNode.SelectNodes("/html/body/center/div/table/tr[2]/td[2]/strong")[0].InnerText;
        string summary = doc.DocumentNode.SelectNodes("/html/body/center/div/table/tr[4]")[0].InnerText;

        richTextBox1.Text = "User Name: " + username + " | Password: " + password + " | Summary: " + summary;

    }
</code>```

There is a username and password listed on the intranet page and I'm trying to pull it from the webpage and display it in the text box, and so long as this app is being run on a domain machine it should be able to access the page and show the required information. I'm not trying to login to anything, just pull some text from a webpage.

None of you can see the page because your not on the domain where its only accessible from.

Here is the pages HTML with the web addresses in the code changed for security reasons.

Guest Wireless Access

Guests may access the wireless service by using the log-in
credentials below.

      User ID:
      KOGUEST

      Password:
      P@ssword   (Password is case-sensitive.)

       The password is updated once a week on
 Saturday at midnight EST.

Print  instructions for your guest.

```

答:
You're copying an xpath from you got from a browser - which is highly unreliable. And I don't know whether the website has a different HTML depending on region. But I do not have 'strong' tag or a 'center' tag in mine.

Do a proper xpath that doesn't rely on an xpath you got from a browser - they are prone to changes and will break your program if small changes occur (already proven by the fact that the xpath does not work on my end). It is very easy to just do a simple one. Because what you have now does not give a clear indication of what you want while an xpath that relied on the attributes and content of the tags would.

Also to expand on your followup question(s) since I can already tell what you're trying to do... You cannot just put in your username and password by using HtmlAgilityPack and then log in. You can either analyze the webpackets with Fiddler and replicate how you login. Or you can go the easier route and use Selenium with a headless browser such as Phantomjs.

Finally. When you do make your xpaths look at the PAGE SOURCE. Do NOT inspect the elements. The page source represents the HTML that gets loaded into your HtmlDocument. IF you inspect elements you get the source code after some steps on site has happened(for instance if the site is depended on JS og ajax to update the content).

Body:
I have a Windows Form with a text box, and the code is suppose to pull information from a website using the xpath I got via chromes developer tools and display it in said text box.

The problem is when I run the program nothing displays in the text box. I'm not sure if my code that is used to get the information is wrong or if my code to display said information is wrong. Please note this code utilizes HtmlAgilityPack.

Here is the code in question:

private void richTextBox1_TextChanged(object sender, EventArgs e)
    {
        string Url = "https://apps.ko.com/aami/iguest/default.asp";
        HtmlWeb web = new HtmlWeb();
        HtmlAgilityPack.HtmlDocument doc = web.Load(Url);

        string username = doc.DocumentNode.SelectNodes("/html/body/center/div/table/tr[1]/td[2]/strong")[0].InnerText;
        string password = doc.DocumentNode.SelectNodes("/html/body/center/div/table/tr[2]/td[2]/strong")[0].InnerText;
        string summary = doc.DocumentNode.SelectNodes("/html/body/center/div/table/tr[4]")[0].InnerText;

        richTextBox1.Text = "User Name: " + username + " | Password: " + password + " | Summary: " + summary;

    }

There is a username and password listed on the intranet page and I'm trying to pull it from the webpage and display it in the text box, and so long as this app is being run on a domain machine it should be able to access the page and show the required information. I'm not trying to login to anything, just pull some text from a webpage.

None of you can see the page because your not on the domain where its only accessible from.

Here is the pages HTML with the web addresses in the code changed for security reasons.

Guest Wireless Access

Guests may access the wireless service by using the log-in
credentials below.

      User ID:
      KOGUEST

      Password:
      P@ssword   (Password is case-sensitive.)

       The password is updated once a week on
 Saturday at midnight EST.

Print  instructions for your guest.


答:
Try :</p>

```<code>SELECT *
  FROM student s
 WHERE NOT EXISTS
          (SELECT 1
             FROM grade g
            WHERE g.student_id = s.student_id AND grade NOT IN ('A', 'B'));
</code>```

Title: how to select records with specific value/condition in another table

Body:
I have 3 tables STUDENT, SUBJECT and GRADE.

STUDENT

+------------+------------+------------+
| student_id | first_name |  last_name |
+------------+------------+------------+
|          0 | Arthur     | Pain       |
|          1 | Richard    | Gordon     |
|          2 | Jennifer   | Adelaide   |
+------------+------------+------------+

SUBJECT

+------------+--------------+
| subject_id | subject_name |
+------------+--------------+
|        001 | Math         |
|        002 | Science      |
|        003 | English      |
+------------+--------------+

GRADE

+-------------+-------------+--------+
| student_id  | subject_id  |  grade |
+-------------+-------------+--------+
| 0           | 001         | A      |
| 0           | 002         | B      |
| 0           | 003         | A      |
| 1           | 001         | B      |
| 1           | 002         | A      |
| 1           | 003         | F      |
| 2           | 001         | A      |
| 2           | 002         | B      |
| 2           | 003         | B      |
+-------------+-------------+--------+

I have tried the query below.

SELECT * FROM student st WHERE EXISTS
       (SELECT 1 FROM grade g WHERE st.student_id = g.student_id AND g.grade IN ('A','B');

I want to select the students with grades only 'A' OR 'B'.

Body:
Try :

SELECT *
  FROM student s
 WHERE NOT EXISTS
          (SELECT 1
             FROM grade g
            WHERE g.student_id = s.student_id AND grade NOT IN ('A', 'B'));


问:
System.Windows.MessageBox vs System.Windows.Forms.MessageBox
I am having trouble finding out what the key differences are between the two message boxes. What is the difference between System.Windows.MessageBox and System.Windows.Forms.MessageBox?

答:
One additional point should be noted:

If you want to display a message box in an application that is neither a windows forms application or a forms application (such as a .NET console application), you should not drag in assembly references for either as seems to be the common mantra all over the internet.

Instead, you should use pinvoke and call into User32 as follows:

```<code>[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern MessageBoxResult MessageBox(IntPtr hWnd, String text, String caption, int options);

/// <summary>
/// Flags that define appearance and behaviour of a standard message box displayed by a call to the MessageBox function.
/// </summary>
[Flags]
public enum MessageBoxOptions : uint
{
    Ok = 0x000000,
    OkCancel = 0x000001,
    AbortRetryIgnore = 0x000002,
    YesNoCancel = 0x000003,
    YesNo = 0x000004,
    RetryCancel = 0x000005,
    CancelTryContinue = 0x000006,

    IconHand = 0x000010,
    IconQuestion = 0x000020,
    IconExclamation = 0x000030,
    IconAsterisk = 0x000040,
    UserIcon = 0x000080,
    IconWarning = IconExclamation,
    IconError = IconHand,
    IconInformation = IconAsterisk,
    IconStop = IconHand,
    DefButton1 = 0x000000,
    DefButton2 = 0x000100,
    DefButton3 = 0x000200,
    DefButton4 = 0x000300,

    ApplicationModal = 0x000000,
    SystemModal = 0x001000,
    TaskModal = 0x002000,

    Help = 0x004000, //Help Button
    NoFocus = 0x008000,

    SetForeground = 0x010000,
    DefaultDesktopOnly = 0x020000,
    Topmost = 0x040000,
    Right = 0x080000,
    RTLReading = 0x100000,
}

/// <summary>
/// Represents possible values returned by the MessageBox function.
/// </summary>
public enum MessageBoxResult : uint
{
    Ok = 1,
    Cancel,
    Abort,
    Retry,
    Ignore,
    Yes,
    No,
    Close,
    Help,
    TryAgain,
    Continue,
    Timeout = 32000
}

var result = User32.MessageBox(IntPtr.Zero, "Debugging Break", "Your Console Application", (int)User32.MessageBoxOptions.Ok);
</code>```

Body:
One additional point should be noted:

If you want to display a message box in an application that is neither a windows forms application or a forms application (such as a .NET console application), you should not drag in assembly references for either as seems to be the common mantra all over the internet.

Instead, you should use pinvoke and call into User32 as follows:

[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern MessageBoxResult MessageBox(IntPtr hWnd, String text, String caption, int options);

/// <summary>
/// Flags that define appearance and behaviour of a standard message box displayed by a call to the MessageBox function.
/// </summary>
[Flags]
public enum MessageBoxOptions : uint
{
    Ok = 0x000000,
    OkCancel = 0x000001,
    AbortRetryIgnore = 0x000002,
    YesNoCancel = 0x000003,
    YesNo = 0x000004,
    RetryCancel = 0x000005,
    CancelTryContinue = 0x000006,

    IconHand = 0x000010,
    IconQuestion = 0x000020,
    IconExclamation = 0x000030,
    IconAsterisk = 0x000040,
    UserIcon = 0x000080,
    IconWarning = IconExclamation,
    IconError = IconHand,
    IconInformation = IconAsterisk,
    IconStop = IconHand,
    DefButton1 = 0x000000,
    DefButton2 = 0x000100,
    DefButton3 = 0x000200,
    DefButton4 = 0x000300,

    ApplicationModal = 0x000000,
    SystemModal = 0x001000,
    TaskModal = 0x002000,

    Help = 0x004000, //Help Button
    NoFocus = 0x008000,

    SetForeground = 0x010000,
    DefaultDesktopOnly = 0x020000,
    Topmost = 0x040000,
    Right = 0x080000,
    RTLReading = 0x100000,
}

/// <summary>
/// Represents possible values returned by the MessageBox function.
/// </summary>
public enum MessageBoxResult : uint
{
    Ok = 1,
    Cancel,
    Abort,
    Retry,
    Ignore,
    Yes,
    No,
    Close,
    Help,
    TryAgain,
    Continue,
    Timeout = 32000
}

var result = User32.MessageBox(IntPtr.Zero, "Debugging Break", "Your Console Application", (int)User32.MessageBoxOptions.Ok);


问:
Attribute sending '<' instead of Integer, cannot figure out why
I'm trying to register a Follow User in my DB, but I'm getting the following error:
SQLSTATE[HY000]: General error: 1366 Incorrect integer value: '<' for column 'followed_id' at row 1

I already got that for some reason my input is sending < instead of Integer. I did a dump {{of the variable}} and is displaying the correct value (an integer, which is a user_id), but when sending info, it's sending something else.

I cannot understand why this is happening though. Instead of sending a variable I sent a number and it worked perfectly.

This is the Blade part where I send the info to the controller

```<code>                            <a href="{!! route('user.follow', ['id' => '{{$post->user_id}}']) !!}">
                        Follow User! {{$post->name}} {{$post->user_id}}</a>
</code>```

Im pretty sure Im not missing anything, I cannot figure out why its sending < instead of the integer.

This is my Controller

```<code>    function followUser($user_id)
{
  follower::create([
  'follower_id' => Auth::user()->id,
  'followed_id' => $user_id,
]);
return redirect()->route('posts');
</code>```

This is my DB

```<code>    public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->increments('id');
        $table->unsignedInteger('user_id');
        $table->string('post');
        $table->foreign('user_id')
          ->references('id')->on('users');
        $table->timestamps();
    });
}

    public function up()
{
    Schema::create('followers', function (Blueprint $table) {
        $table->increments('id');
        $table->unsignedInteger('follower_id');
        $table->unsignedInteger('followed_id');
        $table->foreign('follower_id')->references('id')->on('users')->onDelete('cascade');
        $table->timestamps();

    });
}
</code>```

This is the Controller that send the Object into the view

```<code>function allPosts()
{
  $todos = DB::table('posts')
                ->select('posts.post','posts.id','posts.user_id','users.name')
                ->join('users','users.id','=','posts.user_id')
                ->get();

return view('/posts', [
    'all' => $all,
    ]);
</code>```

答:
change this line:

href="{!! route('user.follow', ['id' => '{{$post->user_id}}']) !!}">

to this:

href="{!! route('user.follow', ['id' => $post->user_id]) !!}">

Body:
I'm trying to register a Follow User in my DB, but I'm getting the following error:
SQLSTATE[HY000]: General error: 1366 Incorrect integer value: '<' for column 'followed_id' at row 1

I already got that for some reason my input is sending < instead of Integer. I did a dump {{of the variable}} and is displaying the correct value (an integer, which is a user_id), but when sending info, it's sending something else.

I cannot understand why this is happening though. Instead of sending a variable I sent a number and it worked perfectly.

This is the Blade part where I send the info to the controller

                             '{{$post->user_id}}']) !!}">
                        Follow User! {{$post->name}} {{$post->user_id}}

Im pretty sure Im not missing anything, I cannot figure out why its sending < instead of the integer.

This is my Controller

    function followUser($user_id)
{
  follower::create([
  'follower_id' => Auth::user()->id,
  'followed_id' => $user_id,
]);
return redirect()->route('posts');

This is my DB

    public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->increments('id');
        $table->unsignedInteger('user_id');
        $table->string('post');
        $table->foreign('user_id')
          ->references('id')->on('users');
        $table->timestamps();
    });
}

    public function up()
{
    Schema::create('followers', function (Blueprint $table) {
        $table->increments('id');
        $table->unsignedInteger('follower_id');
        $table->unsignedInteger('followed_id');
        $table->foreign('follower_id')->references('id')->on('users')->onDelete('cascade');
        $table->timestamps();

    });
}

This is the Controller that send the Object into the view

function allPosts()
{
  $todos = DB::table('posts')
                ->select('posts.post','posts.id','posts.user_id','users.name')
                ->join('users','users.id','=','posts.user_id')
                ->get();

return view('/posts', [
    'all' => $all,
    ]);

Body:
change this line:

<a href="{!! route('user.follow', ['id' => '{{$post->user_id}}']) !!}">

to this:

<a href="{!! route('user.follow', ['id' => $post->user_id]) !!}">


问:
How to make an HTTP get() on a local json file using rxjs?
I am trying to make a request to my local JSON file using Ionic typescript, and retrieve all of the game objects in my JSON file. Here is what I have so far:

```<code>import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { map } from 'rxjs/operators/map';
import { catchError } from 'rxjs/operators/catchError';
import { Observable } from "rxjs/Observable";
import { Game } from "../../models/Game";

import { Http, Response, RequestOptions, Headers } from '@angular/http';

/*
  Generated class for the GamesProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export class GamesProvider {
  constructor(public http: HttpClient) {

  }

  public getGames(): Observable<Array<Game>> {

      return this.http.get('/assets/games.json').pipe(
        map((res: Response) => res.json().games),
        catchError(this.handleError)
      );
  }

  public handleError(error: any) {
      // log error
      // could be something more sofisticated
      let errorMsg = error.message || `Yikes! There was a problem with our hyperdrive device and we couldn't retrieve your data!`
      console.error(errorMsg);

      // throw an application level error
      return Observable.throw(errorMsg);
  }
}
</code>```

I am getting a result that looks like this when I call the getGames() function:

```<code>operator
    :CatchOperator {caught: Observable, selector: ƒ}
    source
    :Observable {_isScalar: false, source: Observable, operator: MapOperator}
    _isScalar
    :false
    __proto__
    :Object
</code>```

What I am expecting is an Observable Array of Game objects.

Game.ts:

```<code>export class Game {
    gameid: number
    genres: string
    images: string
    name: string
    developer: string
    publisher: string
    date: string
    description: string
    players: number
}
</code>```

This is what my JSON file looks like:

```<code>{
    "games":[
  {
    "Id": 1,
    "name": "007: GoldenEye",
    "genres": "Action/First-Person Shooter",
    "date": "25-Aug-97",
    "images": "007: GoldenEye.png",
    "developer": "Rare",
    "publisher": "Nintendo",
    "description": "A video game released for the Nintendo 64.",
    "players": 4
  },
  {
    "Id": 2,
    "name": "007: The World Is Not Enough",
    "genres": "Action/First-Person Shooter",
    "date": "1-Nov-00",
    "images": "007: The World Is Not Enough.png",
    "developer": "Eurocom",
    "publisher": "Electronic Arts",
    "description": "A video game released for the Nintendo 64.",
    "players": 4
  },
...
...
...
 ]
}
</code>```

答:
if you use HttpClient you shouldn't use json();
The get() method on HttpClient makes accessing this data straightforward:

```<code>ngOnInit(): void {
    this.http.get('/assets/games.json').subscribe(data => {
      this.games = data.games;
    },
    (err: HttpErrorResponse) => {
        if (err.error instanceof Error) {
            console.log('An error occurred:', err.error.message);
        } else {
            console.log(`Backend returned code ${err.status}, body was: ${err.error}`);
        }
    })
}
</code>```

and then you can use:

```<code><div *ngFor="let game of games">{{game | json}}</div>
</code>```

Body:
I am trying to make a request to my local JSON file using Ionic typescript, and retrieve all of the game objects in my JSON file. Here is what I have so far:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { map } from 'rxjs/operators/map';
import { catchError } from 'rxjs/operators/catchError';
import { Observable } from "rxjs/Observable";
import { Game } from "../../models/Game";

import { Http, Response, RequestOptions, Headers } from '@angular/http';

/*
  Generated class for the GamesProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export class GamesProvider {
  constructor(public http: HttpClient) {

  }

  public getGames(): Observable<Array<Game>> {

      return this.http.get('/assets/games.json').pipe(
        map((res: Response) => res.json().games),
        catchError(this.handleError)
      );
  }

  public handleError(error: any) {
      // log error
      // could be something more sofisticated
      let errorMsg = error.message || `Yikes! There was a problem with our hyperdrive device and we couldn't retrieve your data!`
      console.error(errorMsg);

      // throw an application level error
      return Observable.throw(errorMsg);
  }
}

I am getting a result that looks like this when I call the getGames() function:

operator
    :CatchOperator {caught: Observable, selector: ƒ}
    source
    :Observable {_isScalar: false, source: Observable, operator: MapOperator}
    _isScalar
    :false
    __proto__
    :Object

What I am expecting is an Observable Array of Game objects.

Game.ts:

export class Game {
    gameid: number
    genres: string
    images: string
    name: string
    developer: string
    publisher: string
    date: string
    description: string
    players: number
}

This is what my JSON file looks like:

{
    "games":[
  {
    "Id": 1,
    "name": "007: GoldenEye",
    "genres": "Action/First-Person Shooter",
    "date": "25-Aug-97",
    "images": "007: GoldenEye.png",
    "developer": "Rare",
    "publisher": "Nintendo",
    "description": "A video game released for the Nintendo 64.",
    "players": 4
  },
  {
    "Id": 2,
    "name": "007: The World Is Not Enough",
    "genres": "Action/First-Person Shooter",
    "date": "1-Nov-00",
    "images": "007: The World Is Not Enough.png",
    "developer": "Eurocom",
    "publisher": "Electronic Arts",
    "description": "A video game released for the Nintendo 64.",
    "players": 4
  },
...
...
...
 ]
}

Body:
if you use HttpClient you shouldn't use json();
The get() method on HttpClient makes accessing this data straightforward:

ngOnInit(): void {
    this.http.get('/assets/games.json').subscribe(data => {
      this.games = data.games;
    },
    (err: HttpErrorResponse) => {
        if (err.error instanceof Error) {
            console.log('An error occurred:', err.error.message);
        } else {
            console.log(`Backend returned code ${err.status}, body was: ${err.error}`);
        }
    })
}

and then you can use:

<div *ngFor="let game of games">{{game | json}}</div>


问:
Detailed memory usage analysis of windows crash dump file?
We have received a native (full) crash dump file from a customer. Opening it in the Visual Studio (2005) debugger shows that we had a crash caused by a realloc call that tried to allocate a ~10MB block. The dump file was unusually large (1,5 GB -- normally they are more like 500 MB).

We therefore conclude that we have a memory "leak" or runaway allocations that either fully exhausted the memory of the process or at least fragmented it significantly enough for the realloc to fail. (Note that this realloc was for an operation that allocated a logging buffer and we are not surprised it failed here, because 10MB in one go would be one of the larger allocations that we do apart from some very large pretty unchangeable buffers -- the problem itself likely has nothing to do with this specific allocation.)

Edit: After the comments exchange wit Lex Li below, I should add: This is not reproducible for us (at the moment). It's just one customer dump clearly showing runaway memory consumption.

Main Question:

Now we have a dump file, but how can we locate what caused the excessive memory usage?

What we've done so far:

We have used the DebugDiag tool to analyze the dump file (the so called Memory Pressure Analyzer), and here's what we got:

```<code>Report for DumpFM...dmp

Virtual Memory Summary
----------------------
Size of largest free VM block   62,23 MBytes
Free memory fragmentation       81,30%
Free Memory                     332,87 MBytes   (16,25% of Total Memory)
Reserved Memory                 0 Bytes   (0,00% of Total Memory)
Committed Memory                1,67 GBytes   (83,75% of Total Memory)
Total Memory                    2,00 GBytes
Largest free block at           0x00000000`04bc4000

Loaded Module Summary
---------------------
Number of Modules       114 Modules
Total reserved memory   0 Bytes
Total committed memory  3,33 MBytes

Thread Summary
--------------
Number of Threads       56 Thread(s)
Total reserved memory   0 Bytes
Total committed memory  652,00 KBytes
</code>```

This was just to get a bit context. Whats more interesting I believe is:

```<code>Heap Summary
------------
Number of heaps         26 Heaps
Total reserved memory   1,64 GBytes
Total committed memory  1,61 GBytes

Top 10 heaps by reserved memory
-------------------------------
0x01040000           1,55 GBytes
0x00150000           64,06 MBytes
0x010d0000           15,31 MBytes
...

Top 10 heaps by committed memory
--------------------------------
0x01040000       1,54 GBytes
0x00150000       55,17 MBytes
0x010d0000       6,25 MBytes
...
</code>```

Now, looking at heap 0x01040000 (1,5 GB) we see:

```<code>Heap 5 - 0x01040000
-------------------
Heap Name          msvcr80!_crtheap
Heap Description   This heap is used by msvcr80
Reserved memory      1,55 GBytes
Committed memory     1,54 GBytes (99,46% of reserved)
Uncommitted memory   8,61 MBytes (0,54% of reserved)
Number of heap segments             39 segments
Number of uncommitted ranges        41 range(s)
Size of largest uncommitted range   8,33 MBytes
Calculated heap fragmentation       3,27%

Segment Information
-------------------
Base Address | Reserved Size   | Committed Size  | Uncommitted Size | Number of uncommitted ranges | Largest uncommitted block | Calculated heap fragmentation
0x01040640        64,00 KBytes      64,00 KBytes   0 Bytes            0                              0 Bytes                     0,00%
0x01350000     1.024,00 KBytes   1.024,00 KBytes   0 Bytes            0                              0 Bytes                     0,00%
0x02850000     2,00 MBytes       2,00 MBytes       0 Bytes            0                              0 Bytes                     0,00%
...
</code>```

What is this Segment Information anyway?

Looking at the allocations that are listed:

```<code>Top 5 allocations by size
-------------------------
Allocation Size - 336          1,18 GBytes
Allocation Size - 1120004      121,77 MBytes
...

Top 5 allocations by count
--------------------------
Allocation Size - 336    3760923 allocation(s)
Allocation Size - 32     1223794 allocation(s)
...
</code>```

We can see that apparently the MSVCR80 heap holds 3.760.923 allocations at 336 bytes. This makes it pretty clear that we mopped up our memory with lots of small allocations, but how can we get some more info regarding where these allocation came from?

If we somehow could sample some of these allocation addresses and then check where in the process image these addresses are in use, then -- assuming that a large portion of these allocations are responsible for our "leak" -- we could maybe find out where these runaway allocations came from.

Unfortunately, I have really no idea how to get more info out of the dump at the moment.

How could I inspect this heap to see some of the "336" allocation addresses?

How can I search the dump for these addresses and how do I then find out which pointer variable (if any) in the dump hold on tho these addresses?

Any tips regarding usage of DebugDiag, WinDbg or any other tool could really help! Also, if you disagree with any of my analysis above, let us know! Thanks!

答:
How many dumps do you have now?

The proper way to track memory leak is to make good use of DebugDiag's Memory and Handle Leak rule.

Then when DebugDiag works on the new dumps, it can tell more about the memory usage.

Body:
We have received a native (full) crash dump file from a customer. Opening it in the Visual Studio (2005) debugger shows that we had a crash caused by a realloc call that tried to allocate a ~10MB block. The dump file was unusually large (1,5 GB -- normally they are more like 500 MB).

We therefore conclude that we have a memory "leak" or runaway allocations that either fully exhausted the memory of the process or at least fragmented it significantly enough for the realloc to fail. (Note that this realloc was for an operation that allocated a logging buffer and we are not surprised it failed here, because 10MB in one go would be one of the larger allocations that we do apart from some very large pretty unchangeable buffers -- the problem itself likely has nothing to do with this specific allocation.)

Edit: After the comments exchange wit Lex Li below, I should add: This is not reproducible for us (at the moment). It's just one customer dump clearly showing runaway memory consumption.

Main Question:

Now we have a dump file, but how can we locate what caused the excessive memory usage?

What we've done so far:

We have used the DebugDiag tool to analyze the dump file (the so called Memory Pressure Analyzer), and here's what we got:

Report for DumpFM...dmp

Virtual Memory Summary
----------------------
Size of largest free VM block   62,23 MBytes
Free memory fragmentation       81,30%
Free Memory                     332,87 MBytes   (16,25% of Total Memory)
Reserved Memory                 0 Bytes   (0,00% of Total Memory)
Committed Memory                1,67 GBytes   (83,75% of Total Memory)
Total Memory                    2,00 GBytes
Largest free block at           0x00000000`04bc4000

Loaded Module Summary
---------------------
Number of Modules       114 Modules
Total reserved memory   0 Bytes
Total committed memory  3,33 MBytes

Thread Summary
--------------
Number of Threads       56 Thread(s)
Total reserved memory   0 Bytes
Total committed memory  652,00 KBytes

This was just to get a bit context. Whats more interesting I believe is:

Heap Summary
------------
Number of heaps         26 Heaps
Total reserved memory   1,64 GBytes
Total committed memory  1,61 GBytes

Top 10 heaps by reserved memory
-------------------------------
0x01040000           1,55 GBytes
0x00150000           64,06 MBytes
0x010d0000           15,31 MBytes
...

Top 10 heaps by committed memory
--------------------------------
0x01040000       1,54 GBytes
0x00150000       55,17 MBytes
0x010d0000       6,25 MBytes
...

Now, looking at heap 0x01040000 (1,5 GB) we see:

Heap 5 - 0x01040000
-------------------
Heap Name          msvcr80!_crtheap
Heap Description   This heap is used by msvcr80
Reserved memory      1,55 GBytes
Committed memory     1,54 GBytes (99,46% of reserved)
Uncommitted memory   8,61 MBytes (0,54% of reserved)
Number of heap segments             39 segments
Number of uncommitted ranges        41 range(s)
Size of largest uncommitted range   8,33 MBytes
Calculated heap fragmentation       3,27%

Segment Information
-------------------
Base Address | Reserved Size   | Committed Size  | Uncommitted Size | Number of uncommitted ranges | Largest uncommitted block | Calculated heap fragmentation
0x01040640        64,00 KBytes      64,00 KBytes   0 Bytes            0                              0 Bytes                     0,00%
0x01350000     1.024,00 KBytes   1.024,00 KBytes   0 Bytes            0                              0 Bytes                     0,00%
0x02850000     2,00 MBytes       2,00 MBytes       0 Bytes            0                              0 Bytes                     0,00%
...

What is this Segment Information anyway?

Looking at the allocations that are listed:

Top 5 allocations by size
-------------------------
Allocation Size - 336          1,18 GBytes
Allocation Size - 1120004      121,77 MBytes
...

Top 5 allocations by count
--------------------------
Allocation Size - 336    3760923 allocation(s)
Allocation Size - 32     1223794 allocation(s)
...

We can see that apparently the MSVCR80 heap holds 3.760.923 allocations at 336 bytes. This makes it pretty clear that we mopped up our memory with lots of small allocations, but how can we get some more info regarding where these allocation came from?

If we somehow could sample some of these allocation addresses and then check where in the process image these addresses are in use, then -- assuming that a large portion of these allocations are responsible for our "leak" -- we could maybe find out where these runaway allocations came from.

Unfortunately, I have really no idea how to get more info out of the dump at the moment.

How could I inspect this heap to see some of the "336" allocation addresses?

How can I search the dump for these addresses and how do I then find out which pointer variable (if any) in the dump hold on tho these addresses?

Any tips regarding usage of DebugDiag, WinDbg or any other tool could really help! Also, if you disagree with any of my analysis above, let us know! Thanks!


问:
WPF DataGrid - How detect if full row is selected?
I have DataGrid in my WPF application, and I want to run a function in the SelectedCellsChanged event, but only if the row is not fully selected, which happens if the user clicks at the header of the row.

My table has only one column.

I've tried the following code and always the value of rowContainer.IsSelected is false.

How can I do this?

Private Sub DataGridEx_SelectionChanged(sender As Object, e As SelectionChangedEventArgs) Handles Me.SelectionChanged

    If SelectedCells.Count <> 1 Then
        Exit Sub
    End If

    If Not SelectedCells.First.Item.ToString.Contains("NewItemPlaceholder") Then

            Me.TheDispatcher.BeginInvoke(
                Sub()
                    Dim cell = SelectedCells.First
                    Dim index = Items.IndexOf(cell.Item) + 1
                    Dim rowContainer As DataGridRow = ItemContainerGenerator.ContainerFromIndex(index)

                    If rowContainer IsNot Nothing Then
                        If Not rowContainer.IsSelected Then
                            ' run a function here
                        End If
                    End If
                End Sub,
                DispatcherPriority.Input)

     End If

End Sub
```

答:
Get the row container for the select cell and check its IsSelected property:

```<code>private void DataGrid_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
{
    DataGrid dg = sender as DataGrid;
    if (dg.SelectedCells != null && dg.SelectedCells.Count > 0)
    {
        var cell = dg.SelectedCells[0];
        var row = dg.ItemContainerGenerator.ContainerFromItem(cell.Item) as DataGridRow;
        if (row != null && row.IsSelected)
        {
            MessageBox.Show("row is selected...");
        }
    }
}
</code>```

This should work if you are using a SelectionUnit of CellOrRowHeader.

Body:
Get the row container for the select cell and check its IsSelected property:

private void DataGrid_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
{
    DataGrid dg = sender as DataGrid;
    if (dg.SelectedCells != null && dg.SelectedCells.Count > 0)
    {
        var cell = dg.SelectedCells[0];
        var row = dg.ItemContainerGenerator.ContainerFromItem(cell.Item) as DataGridRow;
        if (row != null && row.IsSelected)
        {
            MessageBox.Show("row is selected...");
        }
    }
}

This should work if you are using a SelectionUnit of CellOrRowHeader.


问:
Unknown PG numeric type 25
I am working on a project with Python-Flask, SQL Alchemy, & Postgres qith psycopg2 package.
The project's save the data in database successfully, but throws error "Unknown PG numeric type 25" while refreshing object.

```<code>        project.second_payment_percent = int(request.form.get("second_payment_percent", 0)) if request.form.get("second_payment_percent", 0) else 0
        project.second_payment_before = int(request.form.get("second_payment_before", 120))
        project.currency_id = int(request.form.get("currency_code"))
        project.security_deposit = int(request.form.get("security_deposit", 0))
        project.apa = int(request.form.get("apa", 0))
        project.vat_schema_id = request.form.get("vat_schema") if request.form.get("vat_schema", 0) else None

        if project.apa > 0:
            project.security_deposit = int(project.project_price) * int(project.apa) / 100

        db.session.add(project)
        db.session.commit()
        db.session.refresh(project)
        db.session.flush()
</code>```

The error I get is

```<code>File "<project directory>utils/app_views.py", line 56, in decorated
return f(*args, **kwargs)
File "<project directory>views/admin/project.py", line 347, in admin_products_save_accommodation
db.session.refresh(project)
File "<project directory>models/project.py", line 297, in serialize
reviews, avg_rating = self.reviews
File "<project directory>models/project.py", line 269, in reviews
robj = db.session.query(ProjectReviews).filter_by(product_id=self.id).order_by('time_created').all()
File "<venv path>lib/python2.7/site-packages/sqlalchemy/orm/attributes.py", line 237, in __get__
return self.impl.get(instance_state(instance), dict_)
File "<venv path>lib/python2.7/site-packages/sqlalchemy/orm/attributes.py", line 578, in get
value = state._load_expired(state, passive)
File "<venv path>lib/python2.7/site-packages/sqlalchemy/orm/state.py", line 474, in _load_expired
self.manager.deferred_scalar_loader(self, toload)
File "<venv path>lib/python2.7/site-packages/sqlalchemy/orm/loading.py", line 664, in load_scalar_attributes
only_load_props=attribute_names)
File "<venv path>lib/python2.7/site-packages/sqlalchemy/orm/loading.py", line 219, in load_on_ident
return q.one()
File "<venv path>lib/python2.7/site-packages/sqlalchemy/orm/query.py", line 2693, in one
ret = list(self)
File "<venv path>lib/python2.7/site-packages/sqlalchemy/orm/query.py", line 2736, in __iter__
return self._execute_and_instances(context)
File "<venv path>lib/python2.7/site-packages/sqlalchemy/orm/query.py", line 2751, in _execute_and_instances
result = conn.execute(querycontext.statement, self._params)
File "<venv path>lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 914, in execute
return meth(self, multiparams, params)
File "<venv path>lib/python2.7/site-packages/sqlalchemy/sql/elements.py", line 323, in _execute_on_connection
return connection._execute_clauseelement(self, multiparams, params)
File "<venv path>lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1010, in _execute_clauseelement
compiled_sql, distilled_params
File "<venv path>lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1161, in _execute_context
result = context.get_result_proxy()
File "<venv path>lib/python2.7/site-packages/sqlalchemy/dialects/postgresql/psycopg2.py", line 474, in get_result_proxy
return _result.ResultProxy(self)
File "<venv path>lib/python2.7/site-packages/sqlalchemy/engine/result.py", line 495, in __init__
self._init_metadata()
File "<venv path>lib/python2.7/site-packages/sqlalchemy/engine/result.py", line 524, in _init_metadata
self._metadata = ResultMetaData(self, metadata)
File "<venv path>lib/python2.7/site-packages/sqlalchemy/engine/result.py", line 221, in __init__
in enumerate(result_columns)
File "<venv path>lib/python2.7/site-packages/sqlalchemy/engine/default.py", line 764, in get_result_processor
return type_._cached_result_processor(self.dialect, coltype)
File "<venv path>lib/python2.7/site-packages/sqlalchemy/sql/type_api.py", line 392, in _cached_result_processor
d[coltype] = rp = d['impl'].result_processor(dialect, coltype)
File "<venv path>lib/python2.7/site-packages/sqlalchemy/dialects/postgresql/psycopg2.py", line 361, in result_processor
"Unknown PG numeric type: %d" % coltype)
InvalidRequestError: Unknown PG numeric type: 25
</code>```

I have tried many things, but failed.

答:
I guess one of the fields in your table is a text and you are trying to retrieve it as a number.</p>

```<code>postgres=# select * from pg_type where oid = 25;
-[ RECORD 1 ]--+---------
typname        | text
</code>```

Title: Unknown PG numeric type 25

Body:
I am working on a project with Python-Flask, SQL Alchemy, & Postgres qith psycopg2 package.
The project's save the data in database successfully, but throws error "Unknown PG numeric type 25" while refreshing object.

        project.second_payment_percent = int(request.form.get("second_payment_percent", 0)) if request.form.get("second_payment_percent", 0) else 0
        project.second_payment_before = int(request.form.get("second_payment_before", 120))
        project.currency_id = int(request.form.get("currency_code"))
        project.security_deposit = int(request.form.get("security_deposit", 0))
        project.apa = int(request.form.get("apa", 0))
        project.vat_schema_id = request.form.get("vat_schema") if request.form.get("vat_schema", 0) else None

        if project.apa > 0:
            project.security_deposit = int(project.project_price) * int(project.apa) / 100

        db.session.add(project)
        db.session.commit()
        db.session.refresh(project)
        db.session.flush()

The error I get is

File "<project directory>utils/app_views.py", line 56, in decorated
return f(*args, **kwargs)
File "<project directory>views/admin/project.py", line 347, in admin_products_save_accommodation
db.session.refresh(project)
File "<project directory>models/project.py", line 297, in serialize
reviews, avg_rating = self.reviews
File "<project directory>models/project.py", line 269, in reviews
robj = db.session.query(ProjectReviews).filter_by(product_id=self.id).order_by('time_created').all()
File "<venv path>lib/python2.7/site-packages/sqlalchemy/orm/attributes.py", line 237, in __get__
return self.impl.get(instance_state(instance), dict_)
File "<venv path>lib/python2.7/site-packages/sqlalchemy/orm/attributes.py", line 578, in get
value = state._load_expired(state, passive)
File "<venv path>lib/python2.7/site-packages/sqlalchemy/orm/state.py", line 474, in _load_expired
self.manager.deferred_scalar_loader(self, toload)
File "<venv path>lib/python2.7/site-packages/sqlalchemy/orm/loading.py", line 664, in load_scalar_attributes
only_load_props=attribute_names)
File "<venv path>lib/python2.7/site-packages/sqlalchemy/orm/loading.py", line 219, in load_on_ident
return q.one()
File "<venv path>lib/python2.7/site-packages/sqlalchemy/orm/query.py", line 2693, in one
ret = list(self)
File "<venv path>lib/python2.7/site-packages/sqlalchemy/orm/query.py", line 2736, in __iter__
return self._execute_and_instances(context)
File "<venv path>lib/python2.7/site-packages/sqlalchemy/orm/query.py", line 2751, in _execute_and_instances
result = conn.execute(querycontext.statement, self._params)
File "<venv path>lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 914, in execute
return meth(self, multiparams, params)
File "<venv path>lib/python2.7/site-packages/sqlalchemy/sql/elements.py", line 323, in _execute_on_connection
return connection._execute_clauseelement(self, multiparams, params)
File "<venv path>lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1010, in _execute_clauseelement
compiled_sql, distilled_params
File "<venv path>lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1161, in _execute_context
result = context.get_result_proxy()
File "<venv path>lib/python2.7/site-packages/sqlalchemy/dialects/postgresql/psycopg2.py", line 474, in get_result_proxy
return _result.ResultProxy(self)
File "<venv path>lib/python2.7/site-packages/sqlalchemy/engine/result.py", line 495, in __init__
self._init_metadata()
File "<venv path>lib/python2.7/site-packages/sqlalchemy/engine/result.py", line 524, in _init_metadata
self._metadata = ResultMetaData(self, metadata)
File "<venv path>lib/python2.7/site-packages/sqlalchemy/engine/result.py", line 221, in __init__
in enumerate(result_columns)
File "<venv path>lib/python2.7/site-packages/sqlalchemy/engine/default.py", line 764, in get_result_processor
return type_._cached_result_processor(self.dialect, coltype)
File "<venv path>lib/python2.7/site-packages/sqlalchemy/sql/type_api.py", line 392, in _cached_result_processor
d[coltype] = rp = d['impl'].result_processor(dialect, coltype)
File "<venv path>lib/python2.7/site-packages/sqlalchemy/dialects/postgresql/psycopg2.py", line 361, in result_processor
"Unknown PG numeric type: %d" % coltype)
InvalidRequestError: Unknown PG numeric type: 25

I have tried many things, but failed.

Body:
I guess one of the fields in your table is a text and you are trying to retrieve it as a number.

postgres=# select * from pg_type where oid = 25;
-[ RECORD 1 ]--+---------
typname        | text


问:
Css opacity one two div with negative margin
https://jsfiddle.net/1zj71an3/1/

```<code>html:
<div id="one">
aaaaaaaa
</div>
<div id="two">
bbbbbbbb
</div>
css:
#one{
  background-color:yellow;
  width:300px;
  height:300px;
  opacity: 0.5;
}

#two{
  background-color:blue;
  width:200px;
  height:200px;
  margin-top: -100px;
}
</code>```

I would like to set opacity 0.5 to bigger div and leave smaller div opacity 1. The problem is that the smaller div what overlay bigger div is also affected.

Is there a way with css to stop this behaviour?

Thanks!

答:
Just add:

```<code>  #one {
      position: relative;
      z-index: -1;
  }
</code>```

or

```<code>z-index: 1;
</code>```

to make other div above.

Body:
https://jsfiddle.net/1zj71an3/1/

html:

aaaaaaaa

bbbbbbbb

css:
#one{
  background-color:yellow;
  width:300px;
  height:300px;
  opacity: 0.5;
}

#two{
  background-color:blue;
  width:200px;
  height:200px;
  margin-top: -100px;
}

I would like to set opacity 0.5 to bigger div and leave smaller div opacity 1. The problem is that the smaller div what overlay bigger div is also affected.

Is there a way with css to stop this behaviour?

Thanks!

Body:
Just add:

  #one {
      position: relative;
      z-index: -1;
  }

or

z-index: 1;

to make other div above.


问:
Add-Migration fails with Dependency injection in console core 2.0 app
I try to use EF Core 2.0 in a console .net core 2.0 application. When i either use IDesignTimeDbContextFactory or override OnConfiguring method of a DbContext derived class CustomerDbContext, then Add-Migration is successfull in package manager console. But if i try to use AddDbContext like in an asp.net core application, i receive the message:

Unable to create an object of type 'CustomerDbContext'

The code snippet for console .net core application is:

```<code>class Program
{

    static void Main(string[] args)
    {
        var services = new ServiceCollection();
        IConfigurationRoot config = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("config.json")     //needs Microsoft.Extensions.Configuration.Json
            .Build();

        string conn = config.GetConnectionString("WarehouseConnection");
        services
            .AddDbContext<CustomerDbContext>(
            options => options.UseSqlServer(config.GetConnectionString("WarehouseConnection")));

        var provider = services.BuildServiceProvider();
        using(var context = provider.GetService<CustomerDbContext>())
        {
             ...
        }

    }

}
</code>```

the config.json contains the connection string:

```<code>{
  "ConnectionStrings": {
    "WarehouseConnection": "Server=(localdb)\\mssqllocaldb;Database=WAREHOUSE;Trusted_Connection=True;MultipleActiveResultSets=true"
}
</code>```

the CustomerDbContext class is:

```<code>class CustomerDbContext : DbContext
{
    public CustomerDbContext(DbContextOptions<CustomerDbContext> options) : base(options) { }
    public DbSet<Customer> Customers { get; set; }
}
</code>```

Any ideas why this approach fails?

答:
Starting from 2.0, the EF tool checks for a BuildWebHost() method and uses it to access application services if it exsits. Since you don't need a BuildWebHost() using IDesignTimeDbContextFactory is the right approach.

Check the announcement and this comment in the discussion for more information.

Body:
I try to use EF Core 2.0 in a console .net core 2.0 application. When i either use IDesignTimeDbContextFactory or override OnConfiguring method of a DbContext derived class CustomerDbContext, then Add-Migration is successfull in package manager console. But if i try to use AddDbContext like in an asp.net core application, i receive the message:

Unable to create an object of type 'CustomerDbContext'

The code snippet for console .net core application is:

class Program
{

    static void Main(string[] args)
    {
        var services = new ServiceCollection();
        IConfigurationRoot config = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("config.json")     //needs Microsoft.Extensions.Configuration.Json
            .Build();

        string conn = config.GetConnectionString("WarehouseConnection");
        services
            .AddDbContext<CustomerDbContext>(
            options => options.UseSqlServer(config.GetConnectionString("WarehouseConnection")));

        var provider = services.BuildServiceProvider();
        using(var context = provider.GetService<CustomerDbContext>())
        {
             ...
        }

    }

}

the config.json contains the connection string:

{
  "ConnectionStrings": {
    "WarehouseConnection": "Server=(localdb)\\mssqllocaldb;Database=WAREHOUSE;Trusted_Connection=True;MultipleActiveResultSets=true"
}

the CustomerDbContext class is:

class CustomerDbContext : DbContext
{
    public CustomerDbContext(DbContextOptions<CustomerDbContext> options) : base(options) { }
    public DbSet<Customer> Customers { get; set; }
}

Any ideas why this approach fails?


问:
Trying to replace all files in a directory and subdirectories with a source file without altering their name
let's say I have c:\test
and "test" has 100 png images that I want to replace with my own png image, but I don't want to change the name of the images in \test\ .

How would I do that with a batch file? I tried messing around with some FOR cycles but I'm not really experienced with them.

This is the code that I made, it will probably make you cry, but I'm quite a beginner so please forgive me.

```<code>@echo off
for /r %%f in (*) do (
set /a nmb=%random%
set /a name=%%~nxf
copy source.png D:\tobereplaced
rename D:\tobereplaced\%name% %nmb%
pause>nul
)
</code>```

line 2: for every file in the directory and subdirectories take the file name and do:
line3: assign to nmb a random number

line4: assign to name the file name --->Problem: if I try to do echo %name% all I get is "ECHO DISABLED" which means that what I'm trying to assign to "name" is wrong.

line5: copy the source to the folder where I want to replace the files.

line6: rename the source.png file to whatever name the original file had.

答:
found the solution

```<code>@echo off
for /r %%f in (*) do (
echo %%f
copy sorgente.png %%f
pause>nul
)
</code>```

First i set my source files to read only because it would replace them too.

ContentLicense: CC BY-SA 4.0

Body:
let's say I have c:\test
and "test" has 100 png images that I want to replace with my own png image, but I don't want to change the name of the images in \test\ .

How would I do that with a batch file? I tried messing around with some FOR cycles but I'm not really experienced with them.

This is the code that I made, it will probably make you cry, but I'm quite a beginner so please forgive me.

@echo off
for /r %%f in (*) do (
set /a nmb=%random%
set /a name=%%~nxf
copy source.png D:\tobereplaced
rename D:\tobereplaced\%name% %nmb%
pause>nul
)

line 2: for every file in the directory and subdirectories take the file name and do:
line3: assign to nmb a random number

line4: assign to name the file name --->Problem: if I try to do echo %name% all I get is "ECHO DISABLED" which means that what I'm trying to assign to "name" is wrong.

line5: copy the source to the folder where I want to replace the files.

line6: rename the source.png file to whatever name the original file had.

Body:
found the solution

@echo off
for /r %%f in (*) do (
echo %%f
copy sorgente.png %%f
pause>nul
)

First i set my source files to read only because it would replace them too.


问:
PHP Echo SUM session value & form select
I have a PHP echo statement of a session value like this:

<?php echo $userinfo['RenewAgreementAmount'] ;?>

I have a form select element like this:

```<code><select id="Lock" name="Lock">
                      <option value="1" selected="selected">1 Year</option>
                      <option value="2">2 Years</option>
                      <option value="3">3 Years</option>
                      <option value="4">4 Years</option>
                    </select>
</code>```

I'm trying to update the <?php echo $userinfo['RenewAgreementAmount'] ;?> output by taking what the user selects in the select value id Lock with this session value while interacting with the form?

I've tried <?php echo ($userinfo['RenewAgreementAmount'] * #Lock) ;?> with no luck.

What is the easiest way to update this value as the user interacts with the select form input in real time?

答:
Approach using some jQuery, would be something like this--

```<code><?php
session_start();

$_SESSION["RenewAgreementAmount"] = 50;

?>
<html>
    <head>
        <script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
    </head>
    <body>
        <select id="Lock" name="Lock">
            <option value="1" selected="selected">1 Year</option>
            <option value="2">2 Years</option>
            <option value="3">3 Years</option>
            <option value="4">4 Years</option>
        </select>

        <script>
            $(document).ready(function() {
                $("#Lock").bind("change", function(index){
                    var value = $(this).val();
                    //console.log("Changed to: " + value);
                    $.post("updateSessionValue.php". {"newVal": value});
                });
            });
        </script>
    </body>
</html>
</code>```

For updateSessionValue.php page:

```<code><?php
session_start();
$_SESSION["RenewAgreementAmount"] = $_POST["newVal"];
</code>```

Obviously, just an example code... make sure to take all the necessary security precautions!

Body:
I have a PHP echo statement of a session value like this:

<?php echo $userinfo['RenewAgreementAmount'] ;?>

I have a form select element like this:

<select id="Lock" name="Lock">
                      <option value="1" selected="selected">1 Year</option>
                      <option value="2">2 Years</option>
                      <option value="3">3 Years</option>
                      <option value="4">4 Years</option>
                    </select>

I'm trying to update the <?php echo $userinfo['RenewAgreementAmount'] ;?> output by taking what the user selects in the select value id Lock with this session value while interacting with the form?

I've tried <?php echo ($userinfo['RenewAgreementAmount'] * #Lock) ;?> with no luck.

What is the easiest way to update this value as the user interacts with the select form input in real time?

Body:
Approach using some jQuery, would be something like this--

<?php
session_start();

$_SESSION["RenewAgreementAmount"] = 50;

?>
<html>
    <head>
        <script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
    </head>
    <body>
        <select id="Lock" name="Lock">
            <option value="1" selected="selected">1 Year</option>
            <option value="2">2 Years</option>
            <option value="3">3 Years</option>
            <option value="4">4 Years</option>
        </select>

        <script>
            $(document).ready(function() {
                $("#Lock").bind("change", function(index){
                    var value = $(this).val();
                    //console.log("Changed to: " + value);
                    $.post("updateSessionValue.php". {"newVal": value});
                });
            });
        </script>
    </body>
</html>

For updateSessionValue.php page:

<?php
session_start();
$_SESSION["RenewAgreementAmount"] = $_POST["newVal"];

Obviously, just an example code... make sure to take all the necessary security precautions!


问:
How to add validators to a formModel in angular reactive forms
I'm following along the reactive form tutorial for angular and was wondering how to make a property as required or any other validator when using class model for the form group definition.

https://angular.io/guide/reactive-forms#the-data-model-and-the-form-model

I noticed that it creates a default empty string as the initial values.  Why can't I define the address model without default values - otherwise it throws an error?  e.g. I can't say street: string.  I suppose having a default value technically fulfills the required validation - but that is not the real-world use case.

Ideally I'd like to define my class models without default values and make the address and certain address fields required.  Is this possible using reactive forms and form models?

```<code>export class Address {
  street = '';
  city   = '';
  state  = '';
  zip    = '';
}

this.heroForm = this.fb.group({
  name: ['', Validators.required ],
  address: this.fb.group(new Address()), // <-- How to make address and certain address fields required?
  power: '',
  sidekick: ''
});
</code>```

答:
You can provider an extra object to add validator or async validator ( see doc here )

```<code>this.heroForm = this.fb.group({
  name: ['', Validators.required ],
  address: this.fb.group(new Address(), { validator: Validators.required }), // <-- How to make address required?
  power: '',
  sidekick: ''
});
</code>```

But in this case the required will not work as your "new Adress()" is an object, thus not null or undefined.

You well have to create a custom validator for you Adress class

```<code>    const adressValidator = (fg: FormGroup) => {
         test = fg.value;

         if (!test.street || !test.city || ... ) {
             return { adress: { valid : false }};
         }
    }

    and

   this.heroForm = this.fb.group({
      name: ['', Validators.required ],
      address: this.fb.group(new Address(), { validator: adressValidator}), // <-- How to make address required?
      power: '',
      sidekick: ''
    });
</code>```

Hope it helps

Body:
I'm following along the reactive form tutorial for angular and was wondering how to make a property as required or any other validator when using class model for the form group definition.

https://angular.io/guide/reactive-forms#the-data-model-and-the-form-model

I noticed that it creates a default empty string as the initial values.  Why can't I define the address model without default values - otherwise it throws an error?  e.g. I can't say street: string.  I suppose having a default value technically fulfills the required validation - but that is not the real-world use case.

Ideally I'd like to define my class models without default values and make the address and certain address fields required.  Is this possible using reactive forms and form models?

export class Address {
  street = '';
  city   = '';
  state  = '';
  zip    = '';
}

this.heroForm = this.fb.group({
  name: ['', Validators.required ],
  address: this.fb.group(new Address()), // <-- How to make address and certain address fields required?
  power: '',
  sidekick: ''
});

Body:
You can provider an extra object to add validator or async validator ( see doc here )

this.heroForm = this.fb.group({
  name: ['', Validators.required ],
  address: this.fb.group(new Address(), { validator: Validators.required }), // <-- How to make address required?
  power: '',
  sidekick: ''
});

But in this case the required will not work as your "new Adress()" is an object, thus not null or undefined.

You well have to create a custom validator for you Adress class

    const adressValidator = (fg: FormGroup) => {
         test = fg.value;

         if (!test.street || !test.city || ... ) {
             return { adress: { valid : false }};
         }
    }

    and

   this.heroForm = this.fb.group({
      name: ['', Validators.required ],
      address: this.fb.group(new Address(), { validator: adressValidator}), // <-- How to make address required?
      power: '',
      sidekick: ''
    });

Hope it helps


问:
Matching rows of the same dataframe in pandas python
I have a dataframe where the rows are coupled (they refer to the same event): I've created two key-variables (myKey_forMatch and myKey_toBeMatched), that should match in order to couple the observations in the dataframe:

original dataframe

My desiderata is to get a dataframe with only one row for each event:

resulting dataframe

Can anyone give me any hints? (just to avoid any misunderstanding, in the full dataframe the rows to be coupled do not always follow the pattern as in the example shared)

Thanks a lot for helping!

答:
I'm sure there are more elegant ways to solve this, but my personal approach would be to make a new dataframe with two columns, 'myKey_forMatch' and 'data' (which I would rename 'data_match'), and another dataframe with all of the other columns, including the original 'data'. Then I would join the two like this:

firstdf.set_index('myKey_forMatch').join(seconddf.set_index('myKey_toBeMatched'))

Hope this helps


问:
Cannot find symbol when already declared
Please someone help me on this error :

```<code>import java.util.*;
class Cinema
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        int cat;
        System.out.println("Choose your category : \n 1)Premium - Rs.150 \n 2)Gold - Rs.200 \n 3)Business Class - Rs.400");
        cat = sc.nextInt();
        switch(cat)
        {
            case 1:
            {
                System.out.println("You have selected Premium");
                int t = 150;   /* VARIABLE DECLARED */
                break;
            }
            case 2:
            {
                System.out.println("You have selected Gold");
                int t = 200;  /* VARIABLE DECLARED */
                break;
            }
            case 3:
            {
                System.out.println("You have selected Business Class");
                int t = 400;  /* VARIABLE DECLARED */
                break;
            }
            default:
            System.out.println("Invalid Option");
            break;
        }
        Scanner num = new Scanner(System.in);
        int n, amt;
        System.out.println("Choose number of tickets");
        n = num.nextInt();
        amt = t * n;      /* ERROR : cannot find symbol - variable t */
        System.out.println("You are buying " +n+ " tickets of " +cat+ " for Rs." +amt);
    }
}
</code>```

I have already declared the variable t in a case block but it cant find it.
I looked through many answers to similar questions but i cant seem to solve it

答:
You need to declare your variable before switch block for it to be accessible outside of the switch block ... please see the below </p>

```<code>import java.util.*;
public class Cinema {
public static void main(String args[])
{
    Scanner sc = new Scanner(System.in);
    int cat;
    System.out.println("Choose your category : \n 1)Premium - Rs.150 \n 2)Gold - Rs.200 \n 3)Business Class - Rs.400");
    cat = sc.nextInt();

    int t = 0;
    switch(cat)
    {
        case 1:
        {
            System.out.println("You have selected Premium");
             t = 150;   /* VARIABLE DECLARED */
            break;
        }
        case 2:
        {
            System.out.println("You have selected Gold");
            t = 200;  /* VARIABLE DECLARED */
            break;
        }
        case 3:
        {
            System.out.println("You have selected Business Class");
            t = 400;  /* VARIABLE DECLARED */
            break;
        }
        default:
            System.out.println("Invalid Option");
            break;
    }
    Scanner num = new Scanner(System.in);
    int n, amt;
    System.out.println("Choose number of tickets");
    n = num.nextInt();
    amt = t * n;      /* ERROR : cannot find symbol - variable t */
    System.out.println("You are buying " +n+ " tickets of " +cat+ " for Rs." +amt);
}
}
</code>```

Body:
Please someone help me on this error :

import java.util.*;
class Cinema
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        int cat;
        System.out.println("Choose your category : \n 1)Premium - Rs.150 \n 2)Gold - Rs.200 \n 3)Business Class - Rs.400");
        cat = sc.nextInt();
        switch(cat)
        {
            case 1:
            {
                System.out.println("You have selected Premium");
                int t = 150;   /* VARIABLE DECLARED */
                break;
            }
            case 2:
            {
                System.out.println("You have selected Gold");
                int t = 200;  /* VARIABLE DECLARED */
                break;
            }
            case 3:
            {
                System.out.println("You have selected Business Class");
                int t = 400;  /* VARIABLE DECLARED */
                break;
            }
            default:
            System.out.println("Invalid Option");
            break;
        }
        Scanner num = new Scanner(System.in);
        int n, amt;
        System.out.println("Choose number of tickets");
        n = num.nextInt();
        amt = t * n;      /* ERROR : cannot find symbol - variable t */
        System.out.println("You are buying " +n+ " tickets of " +cat+ " for Rs." +amt);
    }
}

I have already declared the variable t in a case block but it cant find it.
I looked through many answers to similar questions but i cant seem to solve it

Body:
You need to declare your variable before switch block for it to be accessible outside of the switch block ... please see the below

import java.util.*;
public class Cinema {
public static void main(String args[])
{
    Scanner sc = new Scanner(System.in);
    int cat;
    System.out.println("Choose your category : \n 1)Premium - Rs.150 \n 2)Gold - Rs.200 \n 3)Business Class - Rs.400");
    cat = sc.nextInt();

    int t = 0;
    switch(cat)
    {
        case 1:
        {
            System.out.println("You have selected Premium");
             t = 150;   /* VARIABLE DECLARED */
            break;
        }
        case 2:
        {
            System.out.println("You have selected Gold");
            t = 200;  /* VARIABLE DECLARED */
            break;
        }
        case 3:
        {
            System.out.println("You have selected Business Class");
            t = 400;  /* VARIABLE DECLARED */
            break;
        }
        default:
            System.out.println("Invalid Option");
            break;
    }
    Scanner num = new Scanner(System.in);
    int n, amt;
    System.out.println("Choose number of tickets");
    n = num.nextInt();
    amt = t * n;      /* ERROR : cannot find symbol - variable t */
    System.out.println("You are buying " +n+ " tickets of " +cat+ " for Rs." +amt);
}
}


问:
java.lang.RuntimeException: Uncompilable source code - what can cause this?
This error is just bizarre, my code compiles fine, I can see there are no problems with it, yet this error has just popped up. I have tried re-starting NetBeans and there is no additional exception information.

What can cause this?

答:
Recheck the package declarations in all your classes!

This behaviour has been observed in NetBeans, when the package declaration in one of the classes of the package refers to a non-existent or wrong package. NetBeans normally detects and highlights this error but has been known to fail and misleadingly report the package as free of errors when this is not the case.


问:
Bundle error, undefined method 'tsource'
Help, I can't get past this bundler error:

```<code>Gemfile:1:in `build': undefined method `tsource' for #<Bundler::Dsl:0xb73c9e04> (NoMethodError)
from /usr/lib/ruby/gems/1.8/gems/bundler-1.0.3/lib/bundler.rb:128:in `definition'
from /usr/lib/ruby/gems/1.8/gems/bundler-1.0.3/lib/bundler/cli.rb:101:in `check'
from /usr/lib/ruby/gems/1.8/gems/bundler-1.0.3/lib/bundler/vendor/thor/task.rb:22:in `send'
from /usr/lib/ruby/gems/1.8/gems/bundler-1.0.3/lib/bundler/vendor/thor/task.rb:22:in `run'
from /usr/lib/ruby/gems/1.8/gems/bundler-1.0.3/lib/bundler/vendor/thor/invocation.rb:118:in `invoke_task'
from /usr/lib/ruby/gems/1.8/gems/bundler-1.0.3/lib/bundler/vendor/thor.rb:246:in `dispatch'
from /usr/lib/ruby/gems/1.8/gems/bundler-1.0.3/lib/bundler/vendor/thor/base.rb:389:in `start'
from /usr/lib/ruby/gems/1.8/gems/bundler-1.0.3/bin/bundle:13
from /usr/bin/bundle:19:in `load'
from /usr/bin/bundle:19
</code>```

Gemfile:

```<code>tsource 'http://rubygems.org'

gem 'rails', '3.0.3'

# Bundle edge Rails instead:
# gem 'rails', :git => 'git://github.com/rails/rails.git'

gem 'mysql2', :git => 'http://github.com/brianmario/mysql2.git'
gem 'devise'
gem 'fastercsv'
gem 'nokogiri'
gem 'json'
</code>```

答:
You have a typo in your Gemfile:

```<code>tsource 'http://rubygems.org'
</code>```

Should be:

```<code>source 'http://rubygems.org'
</code>```

(Notice the missing t.)

Body:
Help, I can't get past this bundler error:

Gemfile:1:in `build': undefined method `tsource' for #<Bundler::Dsl:0xb73c9e04> (NoMethodError)
from /usr/lib/ruby/gems/1.8/gems/bundler-1.0.3/lib/bundler.rb:128:in `definition'
from /usr/lib/ruby/gems/1.8/gems/bundler-1.0.3/lib/bundler/cli.rb:101:in `check'
from /usr/lib/ruby/gems/1.8/gems/bundler-1.0.3/lib/bundler/vendor/thor/task.rb:22:in `send'
from /usr/lib/ruby/gems/1.8/gems/bundler-1.0.3/lib/bundler/vendor/thor/task.rb:22:in `run'
from /usr/lib/ruby/gems/1.8/gems/bundler-1.0.3/lib/bundler/vendor/thor/invocation.rb:118:in `invoke_task'
from /usr/lib/ruby/gems/1.8/gems/bundler-1.0.3/lib/bundler/vendor/thor.rb:246:in `dispatch'
from /usr/lib/ruby/gems/1.8/gems/bundler-1.0.3/lib/bundler/vendor/thor/base.rb:389:in `start'
from /usr/lib/ruby/gems/1.8/gems/bundler-1.0.3/bin/bundle:13
from /usr/bin/bundle:19:in `load'
from /usr/bin/bundle:19

Gemfile:

tsource 'http://rubygems.org'

gem 'rails', '3.0.3'

# Bundle edge Rails instead:
# gem 'rails', :git => 'git://github.com/rails/rails.git'

gem 'mysql2', :git => 'http://github.com/brianmario/mysql2.git'
gem 'devise'
gem 'fastercsv'
gem 'nokogiri'
gem 'json'

Body:
You have a typo in your Gemfile:

tsource 'http://rubygems.org'

Should be:

source 'http://rubygems.org'

(Notice the missing t.)