问:
Search and replace string and also put a counter in replacements
I have a bunch of files containing the exact same log message. One of them happens but as messages are identical I don't known which one. What I want to do is append a number after all these messages to distinguish them.

Now usually when I have a bunch search and replace to perform I just write a quick perl one-liner like:

```<code>perl -pi -e 's/searched/replacement/g' *.c
</code>```

But how can I insert a counter in replacement ?

答:
You can use the e regex modifier to append a running counter value to your replacement as:

```<code>perl -pi -e 's/searched/"replacement".++$i/ge' *.c
</code>```

Demo:

```<code>$ cat file
hi foo
hey foo
bye foo

$ perl -p -e 's/foo/"bar".++$i/ge' file
hi bar1
hey bar2
bye bar3
</code>```

Body:
I have a bunch of files containing the exact same log message. One of them happens but as messages are identical I don't known which one. What I want to do is append a number after all these messages to distinguish them.

Now usually when I have a bunch search and replace to perform I just write a quick perl one-liner like:

perl -pi -e 's/searched/replacement/g' *.c

But how can I insert a counter in replacement ?

Body:
You can use the e regex modifier to append a running counter value to your replacement as:

perl -pi -e 's/searched/"replacement".++$i/ge' *.c

Demo:

$ cat file
hi foo
hey foo
bye foo

$ perl -p -e 's/foo/"bar".++$i/ge' file
hi bar1
hey bar2
bye bar3


来源: stackexchange

问:
How can I autoflush a Perl 6 filehande?
There are a couple of answers for Perl 6 back in its Parrot days and they don't seem to work currently:

This is Rakudo version 2017.04.3 built on MoarVM version 2017.04-53-g66c6dda
  implementing Perl 6.c.

The answer to Does perl6 enable “autoflush” by default? says it's enabled by default (but that was 2011).

Here's a program I was playing with:

```<code>$*ERR.say: "1. This is an error";
$*OUT.say: "2. This is standard out";
</code>```

And its output, which is an unfortunate order:

```<code>2. This is standard out
1. This is an error
</code>```

So maybe I need to turn it on. There's How could I disable autoflush? which mentions an autoflush method:

```<code>$*ERR.autoflush = True;
$*ERR.say: "1. This is an error";
$*OUT.say: "2. This is standard out";
</code>```

But that doesn't work:

No such method 'autoflush' for invocant of type 'IO::Handle'

I guess I could fake this myself by making my IO class that flushes after every output. For what it's worth, it's the lack of this feature that prevented me from using Perl 6 for a particular task today.

As a secondary question, why doesn't Perl 6 have this now, especially when it looks like it used to have it? How would you persaude a Perl 5 person this isn't an issue?

答:
There was an output refactory very recently. With my local version of rakudo i can't get it to give the wrong order any more (2017.06-173-ga209082 built on MoarVM version 2017.06-48-g4bc916e)

There's now a :buffer argument to io handles that you can set to a number (or pass it as :!buffer) that will control this.

I assume the default if the output isatty is to not buffer.

ContentLicense: CC BY-SA 3.0

Title: How can I autoflush a Perl 6 filehande?

Body:
There are a couple of answers for Perl 6 back in its Parrot days and they don't seem to work currently:

This is Rakudo version 2017.04.3 built on MoarVM version 2017.04-53-g66c6dda
  implementing Perl 6.c.

The answer to Does perl6 enable “autoflush” by default? says it's enabled by default (but that was 2011).

Here's a program I was playing with:

$*ERR.say: "1. This is an error";
$*OUT.say: "2. This is standard out";

And its output, which is an unfortunate order:

2. This is standard out
1. This is an error

So maybe I need to turn it on. There's How could I disable autoflush? which mentions an autoflush method:

$*ERR.autoflush = True;
$*ERR.say: "1. This is an error";
$*OUT.say: "2. This is standard out";

But that doesn't work:

No such method 'autoflush' for invocant of type 'IO::Handle'

I guess I could fake this myself by making my IO class that flushes after every output. For what it's worth, it's the lack of this feature that prevented me from using Perl 6 for a particular task today.

As a secondary question, why doesn't Perl 6 have this now, especially when it looks like it used to have it? How would you persaude a Perl 5 person this isn't an issue?


问:
C Man or manual in text or other format to use in command line shell in linux
Im looking for some kind of C text manual or man pages for C syntax or cockbook
which i can check in command line shell mode .
Thanks </p>

答:
You could use pandoc (available here) to convert pretty much anything that you like the style of into manpages - whether that is HTML, MS-Word documents or ePUB books.

So, take the "GNU C Reference Manual" here, and convert that into manpages with pandoc as follows:

```<code>pandoc -V title="C Programming" -V section=1 -s -t man https://www.gnu.org/software/gnu-c-manual/gnu-c-manual.html -o C.1
</code>```

Then you could copy that to usr/local/share/man/man1 and access it with:

```<code>man C
</code>```

Or, don't mix it in with your system manpages, and instead change your MANPATH environment variable.

Or you could use the "GNU C Library" as your starting point (here), or heck, have them both!

Body:
You could use pandoc (available here) to convert pretty much anything that you like the style of into manpages - whether that is HTML, MS-Word documents or ePUB books.

So, take the "GNU C Reference Manual" here, and convert that into manpages with pandoc as follows:

pandoc -V title="C Programming" -V section=1 -s -t man https://www.gnu.org/software/gnu-c-manual/gnu-c-manual.html -o C.1

Then you could copy that to usr/local/share/man/man1 and access it with:

man C

Or, don't mix it in with your system manpages, and instead change your MANPATH environment variable.

Or you could use the "GNU C Library" as your starting point (here), or heck, have them both!


问:
The cursor focus stays on the Editor and does not switch to Console when I try to get the an input from the user in Eclipse
My main method intends to take a string from the user and print it.
However, I can only enter the input string when I manually click on the Console window.
Otherwise, the string I type gets typed in the Editor window.

Can we switch the cursor focus automatically on console when an input is expected from the user?

```<code>public static void main(String[] args) throws IOException {
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    String name = new String();
    System.out.println("Enter Name: ");
    name = br.readLine();
    System.out.println(name);

}
</code>```

答:
Eclipse IDE has different parts(views) : Editor, Package Explorer, Outline, Console etc. Each time one part is active. When you have an active part, all keyboard input will be going to that part.
Ofcourse, if you want to write on console, you need to make the console active.</p>

Body:
My main method intends to take a string from the user and print it.
However, I can only enter the input string when I manually click on the Console window.
Otherwise, the string I type gets typed in the Editor window.

Can we switch the cursor focus automatically on console when an input is expected from the user?

public static void main(String[] args) throws IOException {
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    String name = new String();
    System.out.println("Enter Name: ");
    name = br.readLine();
    System.out.println(name);

}


问:
i want that when the give input in employee_address is Banglore and salary is more than 25000,i get all the details of employee
I have written this code but when i am giving input Banglore and 26000 it is not returning desired condition.

I want to get all employee details when the employee address is Banglore and salary is more than 25000.

```<code>import java.util.Scanner;

public class ContactManager {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        @SuppressWarnings("resource")
        Scanner s=new Scanner(System.in);

        int employee_id;
        String employee_name;
        String address;
        int mobile;
        int salary;
        String q;

        System.out.println("empolyee_id:");
        employee_id=s.nextInt();

        System.out.println("employee_name:");
        employee_name=s.next();

        System.out.println("mobile:");
        mobile=s.nextInt();

        System.out.println("address:");
        address=s.next();

        System.out.println("salary:");
        salary=s.nextInt();

        q = "Banglore";

        if(address==q && salary > 25000) {
            System.out.println(employee_name);
            System.out.println(employee_id);
            System.out.println(address);
            System.out.println(mobile);
            System.out.println(salary);
        } else {
            System.out.println("Sorry");
        }
    }
}
</code>```

答: Instead of if(address==q && salary>25000) you can use if (address.equals(q) && salary > 25000) it should work then.

Body:
I have written this code but when i am giving input Banglore and 26000 it is not returning desired condition.

I want to get all employee details when the employee address is Banglore and salary is more than 25000.

import java.util.Scanner;

public class ContactManager {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        @SuppressWarnings("resource")
        Scanner s=new Scanner(System.in);

        int employee_id;
        String employee_name;
        String address;
        int mobile;
        int salary;
        String q;

        System.out.println("empolyee_id:");
        employee_id=s.nextInt();

        System.out.println("employee_name:");
        employee_name=s.next();

        System.out.println("mobile:");
        mobile=s.nextInt();

        System.out.println("address:");
        address=s.next();

        System.out.println("salary:");
        salary=s.nextInt();

        q = "Banglore";

        if(address==q && salary > 25000) {
            System.out.println(employee_name);
            System.out.println(employee_id);
            System.out.println(address);
            System.out.println(mobile);
            System.out.println(salary);
        } else {
            System.out.println("Sorry");
        }
    }
}


问:
cloudkit error no authToken received for asset
Why do I get this error when I run the following code? :

"Internal Error" (1/1000); "No authToken received for asset"

I think it has something to do with the setObject code in the last line.

```<code>let documentsDirectoryPath:NSString = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString
var imageURL: URL!

let imageData = UIImageJPEGRepresentation(self.newImage, 1.0)
let path:String = documentsDirectoryPath.appendingPathComponent(self.newImage.description)
try? UIImageJPEGRepresentation(self.newImage, 1.0)!.write(to: URL(fileURLWithPath: path), options: [.atomicWrite])
imageURL = URL(fileURLWithPath: path)
try? imageData?.write(to: imageURL, options: [.atomicWrite])

let imageAsset:CKAsset? = CKAsset(fileURL: URL(fileURLWithPath: path))

curImages = record["Images"] as! [CKAsset]
curImages.append(imageAsset!)

print("saving image")
record.setObject(curImages as CKRecordValue?, forKey: "Images")
</code>```

答:
I've encountered this, too. It appears to be a bug in cloudkit, and--from what I can tell--it happens when you try to re-use any part of the "asset creation chain."

In other words, you have some initial data, you create an image from that data, you write it to a file, you load that file into a CKAsset, then you load the CKAsset into the CKRecrod. In my experiments, if you re-use any of those components... or if they just happen to be the same (that is, you create an image, then you happen to create a new-but-identical image later) you'll see this error.

For example, the following code reliably recreates the "no auth token" error when saving a record. All it does is create an array of assets and places it into the record:

```<code>for (int i = 0; i <= maxPlayers; i++)
{
    int tempVal = 0xf;
    NSData *tempData = [[NSData alloc] initWithBytes:&tempVal length:sizeof(tempVal)];
    NSString *tempDataFilepath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"temp%d.dat",i]];
    [tempData writeToFile:tempDataFilepath atomically:YES];
    NSURL *tempDataURL = [NSURL fileURLWithPath:tempDataFilepath];
    someArray[i] = [[CKAsset alloc] initWithFileURL:tempDataURL ];
}

someRecord[SOME_FIELD_NAME] = someArray;
</code>```

Simply changing the third line to:

```<code>int tempVal = i; //force the temp value to be different every time
</code>```

Completely solves the error.

Furthermore, this error occurs even when I tried to use a value in a different CKAsset **that was already used in a prior CKAsset For example, using int tempVal = 0xf in the first asset, then using int secondTempVal = 0xf in another CKAsset also produces the "no auth token" error.

In my case, I was able to force the asset value to always be a unique value, and completely solved the problem. In your case, I suggest the following possible work arounds:

Check if you're using identical images for your assets. If you are, try slightly modifying the images for each new CKAsset.

If you must re-use identical images, try saving the record after you set each asset. I do not know if that will solve the issue, and it certainly increases your network traffic. But it's worth an experiment to see if it helps.

In this question Saving CKAsset to CKRecord in CloudKit produces error: "No authToken received for asset" the OP was able to create separate copies of the image file that ultimately solved the problem.

Open a bug with Apple. I didn't bother doing this, as I've grown jaded watching similar bug reports sit open for years without attention. But who knows, you might have better luck.

Body:
Why do I get this error when I run the following code? :

"Internal Error" (1/1000); "No authToken received for asset"

I think it has something to do with the setObject code in the last line.

let documentsDirectoryPath:NSString = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString
var imageURL: URL!

let imageData = UIImageJPEGRepresentation(self.newImage, 1.0)
let path:String = documentsDirectoryPath.appendingPathComponent(self.newImage.description)
try? UIImageJPEGRepresentation(self.newImage, 1.0)!.write(to: URL(fileURLWithPath: path), options: [.atomicWrite])
imageURL = URL(fileURLWithPath: path)
try? imageData?.write(to: imageURL, options: [.atomicWrite])

let imageAsset:CKAsset? = CKAsset(fileURL: URL(fileURLWithPath: path))

curImages = record["Images"] as! [CKAsset]
curImages.append(imageAsset!)

print("saving image")
record.setObject(curImages as CKRecordValue?, forKey: "Images")

Body:
I've encountered this, too. It appears to be a bug in cloudkit, and--from what I can tell--it happens when you try to re-use any part of the "asset creation chain."

In other words, you have some initial data, you create an image from that data, you write it to a file, you load that file into a CKAsset, then you load the CKAsset into the CKRecrod. In my experiments, if you re-use any of those components... or if they just happen to be the same (that is, you create an image, then you happen to create a new-but-identical image later) you'll see this error.

For example, the following code reliably recreates the "no auth token" error when saving a record. All it does is create an array of assets and places it into the record:

for (int i = 0; i <= maxPlayers; i++)
{
    int tempVal = 0xf;
    NSData *tempData = [[NSData alloc] initWithBytes:&tempVal length:sizeof(tempVal)];
    NSString *tempDataFilepath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"temp%d.dat",i]];
    [tempData writeToFile:tempDataFilepath atomically:YES];
    NSURL *tempDataURL = [NSURL fileURLWithPath:tempDataFilepath];
    someArray[i] = [[CKAsset alloc] initWithFileURL:tempDataURL ];
}

someRecord[SOME_FIELD_NAME] = someArray;

Simply changing the third line to:

int tempVal = i; //force the temp value to be different every time

Completely solves the error.

Furthermore, this error occurs even when I tried to use a value in a different CKAsset **that was already used in a prior CKAsset For example, using int tempVal = 0xf in the first asset, then using int secondTempVal = 0xf in another CKAsset also produces the "no auth token" error.

In my case, I was able to force the asset value to always be a unique value, and completely solved the problem. In your case, I suggest the following possible work arounds:

Check if you're using identical images for your assets. If you are, try slightly modifying the images for each new CKAsset.

If you must re-use identical images, try saving the record after you set each asset. I do not know if that will solve the issue, and it certainly increases your network traffic. But it's worth an experiment to see if it helps.

In this question Saving CKAsset to CKRecord in CloudKit produces error: "No authToken received for asset" the OP was able to create separate copies of the image file that ultimately solved the problem.

Open a bug with Apple. I didn't bother doing this, as I've grown jaded watching similar bug reports sit open for years without attention. But who knows, you might have better luck.


问:
How to change the color of text in text field by selecting color from a drop down menu in HTML
I want to select a value from

   Select Colour

 <button class = "btn _select_color dropdown-toggle"
type = "button"
id = "dropdownMenu1"
data - toggle = "dropdown"
aria - haspopup = "true"
aria - expanded = "false" > Green    < /button>

  <input type = "hidden"
name = "_color"
value = "Green" >

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

<p>and i want the color will be selected in</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><form name="myForm" action="#">
  <div class="form-group">
    <label for="message"> Text Here</label>
    <textarea name="txt1" id="message" cols="30" rows="9" class="form-control"></textarea>
    <input type="text" value="something" onclick="this.value='';this.style.color=_color;" /> </div>
</form></code>```

The color selected from the color list must be reflect in the textfile. I am new to HTML CSS and JS.

答:
I didn't read your code, but usually to change colors and accomplish changes to the UI, it's easiest to manipulate classes with the specific change. Here's some code and a link to codepen illustrating this:

HTML

```<code><div id="container">
  <div id="box"></div>
</div>

<select id="menu">
  <option value="red">Red</option>
  <option value="blue">Blue</option>
  <option value="black">Black</option>
  <option value="green">Green</option>
</select>
</code>```

CSS (Stylus)

```<code>#box
   width 100px
   height 100px

.red
  background red

.blue
  background blue

.black
  background black

.green
  background green
</code>```

JS

```<code>(function() {

  var box           = document.getElementById("box");
  var menu          = document.getElementById("menu");
  var currentValue  = menu.value            // grabs current menu selection

  box.classList.add(currentValue);          // adds class to element wanting to change color

  // event listener and function to handle change
  menu.addEventListener("change", function (e) {
    var color = menu.value;
    box.classList.remove(currentValue);     // removes current color class
    box.classList.add(color);               // adds new color
    currentValue = color;                   // resets current color variable for next change
  })

})()
</code>```

https://codepen.io/codyj/pen/Pjyzmz?editors=1111

Body:
I want to select a value from

   Select Colour

 <button class = "btn _select_color dropdown-toggle"
type = "button"
id = "dropdownMenu1"
data - toggle = "dropdown"
aria - haspopup = "true"
aria - expanded = "false" > Green    < /button>

  <input type = "hidden"
name = "_color"
value = "Green" >

and i want the color will be selected in

<form name="myForm" action="#">

     Text Here
    <textarea name="txt1" id="message" cols="30" rows="9" class="form-control"></textarea>
    <input type="text" value="something" onclick="this.value='';this.style.color=_color;" />

</form>

The color selected from the color list must be reflect in the textfile. I am new to HTML CSS and JS.

Body:
I didn't read your code, but usually to change colors and accomplish changes to the UI, it's easiest to manipulate classes with the specific change. Here's some code and a link to codepen illustrating this:

HTML

<div id="container">
  <div id="box"></div>
</div>

<select id="menu">
  <option value="red">Red</option>
  <option value="blue">Blue</option>
  <option value="black">Black</option>
  <option value="green">Green</option>
</select>

CSS (Stylus)

#box
   width 100px
   height 100px

.red
  background red

.blue
  background blue

.black
  background black

.green
  background green

JS

(function() {

  var box           = document.getElementById("box");
  var menu          = document.getElementById("menu");
  var currentValue  = menu.value            // grabs current menu selection

  box.classList.add(currentValue);          // adds class to element wanting to change color

  // event listener and function to handle change
  menu.addEventListener("change", function (e) {
    var color = menu.value;
    box.classList.remove(currentValue);     // removes current color class
    box.classList.add(color);               // adds new color
    currentValue = color;                   // resets current color variable for next change
  })

})()

https://codepen.io/codyj/pen/Pjyzmz?editors=1111


问:
regex to parse import statements in python
can someone help me writing single regex to get module(s) from python source line?

```<code>from abc.lmn import pqr
from abc.lmn import pqr as xyz
import abc
import abc as xyz
</code>```

it has 3 sub parts in it

```<code>[from(\s)<module>(\s)] --> get module if this part exist
import(\s)<module>     --> get module
[(\s)as(\s)<alias>]    --> ignore if this part exist
</code>```

something like this

```<code>:?[from(\s)<module>(\s)]import(\s)<module>:?[(\s)as(\s)<alias>]
</code>```

答:
Looks like you could make the from optional and the import required at

the same time ignoring the as.

(?m)^(?:from[ ]+(\S+)[ ]+)?import[ ]+(\S+)[ ]*$

https://regex101.com/r/fmoAuh/1

Explained

```<code> (?m)                          # Modifiers: multi-line
 ^                             # Beginning of line
 (?:                           # Optional from
      from [ ]+
      ( \S+ )                       # (1), from <module>
      [ ]+
 )?

 import [ ]+                   # Required import
 ( \S+ )                       # (2), import <module>
 [ ]*
 $                             # End of line
</code>```

Or, if you want to match the as but do not want to capture anything, use this.

(?m)^(?:from[ ]+(\S+)[ ]+)?import[ ]+(\S+)(?:[ ]+as[ ]+\S+)?[ ]*$

https://regex101.com/r/xFtey5/1

Expanded

```<code> (?m)                          # Modifiers: multi-line
 ^                             # Beginning of line
 (?:                           # Optional from
      from [ ]+
      ( \S+ )                       # (1), from <module>
      [ ]+
 )?

 import [ ]+                   # Required import
 ( \S+ )                       # (2), import <module>

 (?:                           # Optional as
      [ ]+
      as [ ]+
      \S+                          # <alias>
 )?
 [ ]*
 $
</code>```

Body:
can someone help me writing single regex to get module(s) from python source line?

from abc.lmn import pqr
from abc.lmn import pqr as xyz
import abc
import abc as xyz

it has 3 sub parts in it

[from(\s)<module>(\s)] --> get module if this part exist
import(\s)<module>     --> get module
[(\s)as(\s)<alias>]    --> ignore if this part exist

something like this

:?[from(\s)<module>(\s)]import(\s)<module>:?[(\s)as(\s)<alias>]

Body:
Looks like you could make the from optional and the import required at

the same time ignoring the as.

(?m)^(?:from[ ]+(\S+)[ ]+)?import[ ]+(\S+)[ ]*$

https://regex101.com/r/fmoAuh/1

Explained

 (?m)                          # Modifiers: multi-line
 ^                             # Beginning of line
 (?:                           # Optional from
      from [ ]+
      ( \S+ )                       # (1), from <module>
      [ ]+
 )?

 import [ ]+                   # Required import
 ( \S+ )                       # (2), import <module>
 [ ]*
 $                             # End of line

Or, if you want to match the as but do not want to capture anything, use this.

(?m)^(?:from[ ]+(\S+)[ ]+)?import[ ]+(\S+)(?:[ ]+as[ ]+\S+)?[ ]*$

https://regex101.com/r/xFtey5/1

Expanded

 (?m)                          # Modifiers: multi-line
 ^                             # Beginning of line
 (?:                           # Optional from
      from [ ]+
      ( \S+ )                       # (1), from <module>
      [ ]+
 )?

 import [ ]+                   # Required import
 ( \S+ )                       # (2), import <module>

 (?:                           # Optional as
      [ ]+
      as [ ]+
      \S+                          # <alias>
 )?
 [ ]*
 $


问:
Powershell button event to run a script
i have to make a graphic interface with powershell to display a list of PCs in a domain but i don't know how to set the script in the event button. The script is p1_compare.ps1. Actually the lists are in .csv files because i have no idea how to get them to display and set it in the interface</p>

答:
I have done in another way to get result when pressing a command button
for example: </p>

```<code>$Button.Add_Click({
      Get-DiskInfo | Out-GridView
})
</code>```

<p>     </p>

Title: Powershell button event to run a script

Body:
I have done in another way to get result when pressing a command button
for example:

$Button.Add_Click({
      Get-DiskInfo | Out-GridView
})


问:
Send message from server at specific time in php?
Is there any way to send mail at specific time in php?

Please give me hint for that file. I forget to that file which is used to send mail to specific time.

答: Look up CRON jobs. A CRON job runs a specific php file at a certain time. Other than that there's no way to schedule an email in PHP (afaik).</p>

ContentLicense: CC BY-SA 2.5


问:
Pass this to addEventListener() as parameter
I want to add change event to a group of checkboxes, how can I access this in my event function, so that when I do the event I can access value of the checkbox.

This is my current code:

var checkboxes = document.getElementsByClassName('cb');
Array.from(checkboxes).forEach(function(){
  this.addEventListener("change", cbChange(this), false);
});

function cbChange(ele){
  console.log(ele.value);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input class="cb" type="checkbox" name="candidate" value="1"/>
<input class="cb" type="checkbox" name="candidate" value="2"/>
<input class="cb" type="checkbox" name="candidate" value="3"/>
<input class="cb" type="checkbox" name="candidate" value="4"/></code>```

答:
you don't need to pass this to event handler. you can access event.target inside event handler. you can do something like this:

var checkboxes = document.getElementsByClassName('cb');
Array.from(checkboxes).forEach(function(){
  this.addEventListener("change", cbChange, false);
})

function cbChange(event){
  var ele = event.target;
  console.log(ele.value);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input class="cb" type="checkbox" name="candidate" value="1"/>
<input class="cb" type="checkbox" name="candidate" value="2"/>
<input class="cb" type="checkbox" name="candidate" value="3"/>
<input class="cb" type="checkbox" name="candidate" value="4"/></code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to add change event to a group of checkboxes, how can I access this in my event function, so that when I do the event I can access value of the checkbox.

This is my current code:

var checkboxes = document.getElementsByClassName('cb');
Array.from(checkboxes).forEach(function(){
  this.addEventListener("change", cbChange(this), false);
});

function cbChange(ele){
  console.log(ele.value);
}

<input class="cb" type="checkbox" name="candidate" value="1"/>
<input class="cb" type="checkbox" name="candidate" value="2"/>
<input class="cb" type="checkbox" name="candidate" value="3"/>
<input class="cb" type="checkbox" name="candidate" value="4"/>

Body:
you don't need to pass this to event handler. you can access event.target inside event handler. you can do something like this:

var checkboxes = document.getElementsByClassName('cb');
Array.from(checkboxes).forEach(function(){
  this.addEventListener("change", cbChange, false);
})

function cbChange(event){
  var ele = event.target;
  console.log(ele.value);
}

<input class="cb" type="checkbox" name="candidate" value="1"/>
<input class="cb" type="checkbox" name="candidate" value="2"/>
<input class="cb" type="checkbox" name="candidate" value="3"/>
<input class="cb" type="checkbox" name="candidate" value="4"/>


答:
Remove (this) from cbChange(this). This will immediately execute the function.

To get the value you need the target.target is the element on which event is executed.On consoling ele you will see all available options

var checkboxes = document.getElementsByClassName('cb');
Array.from(checkboxes).forEach(function() {
  this.addEventListener("change", cbChange, false);
});

function cbChange(ele) {
  console.log(ele.target.value);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input class="cb" type="checkbox" name="candidate" value="1" />
<input class="cb" type="checkbox" name="candidate" value="2" />
<input class="cb" type="checkbox" name="candidate" value="3" />
<input class="cb" type="checkbox" name="candidate" value="4" /></code>```

Title: Pass this to addEventListener() as parameter

Body:
Remove (this) from cbChange(this). This will immediately execute the function.

To get the value you need the target.target is the element on which event is executed.On consoling ele you will see all available options

var checkboxes = document.getElementsByClassName('cb');
Array.from(checkboxes).forEach(function() {
  this.addEventListener("change", cbChange, false);
});

function cbChange(ele) {
  console.log(ele.target.value);
}

<input class="cb" type="checkbox" name="candidate" value="1" />
<input class="cb" type="checkbox" name="candidate" value="2" />
<input class="cb" type="checkbox" name="candidate" value="3" />
<input class="cb" type="checkbox" name="candidate" value="4" />


问:
Bootstrap navbar transparent on mobile
I've set up my homepage the way I wanted it to look. However, when looking at it on a mobile device, the navbar, which on mobile changes to a dropdown menu, has no background color. I've been trying to change the color itself, but it doesn't do anything.</p>

答: you can use CSS media queries to set style for mobile view.</p>

Title: Bootstrap navbar transparent on mobile


问:
background-image property can't be changed by jquery
Like the title say, for some reason my function don't want to perform a change to the background-image property. I also made the function change the background-color to check if it is working and it does. So it seems that the problem is not in the syntax.

function feedSlide () {
  var x = [
    '../img/feed1.png',
    '../img/feed2.png',
    '../img/feed3.png',
    '../img/feed4.png'
  ];
  var y = ['green', 'red', 'blue', 'yellow'];
  for (var i = 0; i < x.length; i++) {
    setTimeout(function(z) { return function() {
      console.log(x[z]);
      $('#feedback').css({"background-image" : "url(" + x[z] + ")"});
      $('#feedback').css({"background-color" : y[z] });
    }; }(i), 1000*i);
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#feedback {
  width: 400px;
  text-align: justify;
  padding: 10px;
  height: 200px;
}</code>```

```

I'm on that for hours now and everything seems to be changeable but the background-image. Any information is very welcome.

答:
You could try the below code,</p>

```<code>function feedSlide () {
  var x = [
    'feed1.png',
    'feed2.png',
    'feed3.png',
    'feed4.png'
  ];
  var y = ['green', 'red', 'blue', 'yellow'];
  for (var i = 0; i < x.length; i++) {
    setTimeout(function(z) { return function() {
      console.log(x[z]);
      var element = document.getElementById('#feedback');
      element.style.backgroundImage = "url('img/" + x[z] + "')";
      element.style.backgroundColor = y[z];
    }; }(i), 1000*i);
  }
}
</code>```

Body:
Like the title say, for some reason my function don't want to perform a change to the background-image property. I also made the function change the background-color to check if it is working and it does. So it seems that the problem is not in the syntax.

function feedSlide () {
  var x = [
    '../img/feed1.png',
    '../img/feed2.png',
    '../img/feed3.png',
    '../img/feed4.png'
  ];
  var y = ['green', 'red', 'blue', 'yellow'];
  for (var i = 0; i < x.length; i++) {
    setTimeout(function(z) { return function() {
      console.log(x[z]);
      $('#feedback').css({"background-image" : "url(" + x[z] + ")"});
      $('#feedback').css({"background-color" : y[z] });
    }; }(i), 1000*i);
  }
}

#feedback {
  width: 400px;
  text-align: justify;
  padding: 10px;
  height: 200px;
}

I'm on that for hours now and everything seems to be changeable but the background-image. Any information is very welcome.

Body:
You could try the below code,

function feedSlide () {
  var x = [
    'feed1.png',
    'feed2.png',
    'feed3.png',
    'feed4.png'
  ];
  var y = ['green', 'red', 'blue', 'yellow'];
  for (var i = 0; i < x.length; i++) {
    setTimeout(function(z) { return function() {
      console.log(x[z]);
      var element = document.getElementById('#feedback');
      element.style.backgroundImage = "url('img/" + x[z] + "')";
      element.style.backgroundColor = y[z];
    }; }(i), 1000*i);
  }
}


问:
Designing function f(f(n)) == -n
A question I got on my last interview:

Design a function f, such that:

```<code>f(f(n)) == -n
</code>```

Where n is a 32 bit signed integer; you can't use complex numbers arithmetic.

If you can't design such a function for the whole range of numbers, design it for the largest range possible.

Any ideas?

答:
```<code>#include <cmath>

int f(int n)
{
    static int count = 0;
    return ::cos(M_PI * count++) * n;
}
</code>```

Title: Designing function f(f(n)) == -n

Body:
A question I got on my last interview:

Design a function f, such that:

f(f(n)) == -n

Where n is a 32 bit signed integer; you can't use complex numbers arithmetic.

If you can't design such a function for the whole range of numbers, design it for the largest range possible.

Any ideas?


答:
I think you should use map

const checkboxes = document.getElementsByClassName('cb');
const cbArr = Array.from(checkboxes)
cbArr.map((d) => {
  d.addEventListener("change", cbChange(d), false);
});

function cbChange(ele){
  console.log(ele.value);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input class="cb" type="checkbox" name="candidate" value="1"/>
<input class="cb" type="checkbox" name="candidate" value="2"/>
<input class="cb" type="checkbox" name="candidate" value="3"/>
<input class="cb" type="checkbox" name="candidate" value="4"/></code>```

Body:
I think you should use map

const checkboxes = document.getElementsByClassName('cb');
const cbArr = Array.from(checkboxes)
cbArr.map((d) => {
  d.addEventListener("change", cbChange(d), false);
});

function cbChange(ele){
  console.log(ele.value);
}

<input class="cb" type="checkbox" name="candidate" value="1"/>
<input class="cb" type="checkbox" name="candidate" value="2"/>
<input class="cb" type="checkbox" name="candidate" value="3"/>
<input class="cb" type="checkbox" name="candidate" value="4"/>


问:
Angular2 http.post: Create promise with subscribe
I´m trying do create a function, that returns a Promise as the code: (someprovider.ts)

```<code>postToPaymentApi(url:string, data:string, options:RequestOptions, order:Order):Promise<any>{
let result =  this.http.post(url, data, options).map(res => res.json())
  .subscribe(data => {
    // all my logic here!
    });
  }, error => {
    console.log(error)
  })

  return new Promise((resolve)=>{
    resolve(result)
  })
</code>```

}

The problem is, when I call this function, I do not get the data, because this post take a few seconds to finish and I get the promise before the post finish.

```<code>this.postToPaymentApi(url, data, options, order).then(data => {
    console.log(data);
  })
</code>```

What Am I doing wrong?

答:
Andre, you want to use the toPromise operator to transform the observable returned by .map() into a promise. Return the result of that operator

```<code>return http.post(...).map(...).toPromise()
</code>```

Now a proper promise is returned, so the calling code can use it as such:

```<code>postToPaymentApi(...).then(
    data => console.log(data)
)
</code>```

Body:
I´m trying do create a function, that returns a Promise as the code: (someprovider.ts)

postToPaymentApi(url:string, data:string, options:RequestOptions, order:Order):Promise<any>{
let result =  this.http.post(url, data, options).map(res => res.json())
  .subscribe(data => {
    // all my logic here!
    });
  }, error => {
    console.log(error)
  })

  return new Promise((resolve)=>{
    resolve(result)
  })

}

The problem is, when I call this function, I do not get the data, because this post take a few seconds to finish and I get the promise before the post finish.

this.postToPaymentApi(url, data, options, order).then(data => {
    console.log(data);
  })

What Am I doing wrong?

Body:
Andre, you want to use the toPromise operator to transform the observable returned by .map() into a promise. Return the result of that operator

return http.post(...).map(...).toPromise()

Now a proper promise is returned, so the calling code can use it as such:

postToPaymentApi(...).then(
    data => console.log(data)
)


问:
Dealing with Exception in Overridden Interface in Java
I have a Java interface that I am implementing (EdgeProvider from JGraphT) and which is not allowed to be null. However, I'm instantiating a generic type in an overridden method and can't figure out how to deal with either InstantiationException or IllegalAccessException in a way that I can detect and cleanly break out of the execution flow.

```<code>EdgeProvider<V, E> ep = new EdgeProvider<V, E>() {
      @Override
      public E buildEdge(V from, V to, String label, Map<String, String> attributes) {
        try {
          return eClass.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
          return null;
        }
      }
    };
</code>```

If I rethrow I just get a warning that I have unhandled exceptions. Any suggestions?

答:
You can throw a RuntimeException as only checked exception cannot be added to the declaration of an overrided method.

You could define a custom exception (subclass of RuntimeException) : MyBuildEdgeException that wraps the caught exception.

```<code>public class MyBuildEdgeException extends RuntimeException{
   public MyBuildEdgeException(Exception cause){
       super(cause);
   }
}
</code>```

And now you could throw the exception in this way :

```<code>EdgeProvider<V, E> ep = new EdgeProvider<V, E>() {
      @Override
      public E buildEdge(V from, V to, String label, Map<String, String> attributes) throws MyBuildEdgeException{
        try {
          return eClass.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
           throw new MyBuildEdgeException(e);
        }
      }
    };
</code>```

Body:
I have a Java interface that I am implementing (EdgeProvider from JGraphT) and which is not allowed to be null. However, I'm instantiating a generic type in an overridden method and can't figure out how to deal with either InstantiationException or IllegalAccessException in a way that I can detect and cleanly break out of the execution flow.

EdgeProvider<V, E> ep = new EdgeProvider<V, E>() {
      @Override
      public E buildEdge(V from, V to, String label, Map<String, String> attributes) {
        try {
          return eClass.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
          return null;
        }
      }
    };

If I rethrow I just get a warning that I have unhandled exceptions. Any suggestions?

Body:
You can throw a RuntimeException as only checked exception cannot be added to the declaration of an overrided method.

You could define a custom exception (subclass of RuntimeException) : MyBuildEdgeException that wraps the caught exception.

public class MyBuildEdgeException extends RuntimeException{
   public MyBuildEdgeException(Exception cause){
       super(cause);
   }
}

And now you could throw the exception in this way :

EdgeProvider<V, E> ep = new EdgeProvider<V, E>() {
      @Override
      public E buildEdge(V from, V to, String label, Map<String, String> attributes) throws MyBuildEdgeException{
        try {
          return eClass.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
           throw new MyBuildEdgeException(e);
        }
      }
    };


问:
display calendar when i hover the mouse in text box
I've been looking around for some time now and can't seem to find anything for what I'd like. I want it to be that when you hover over a text box named the month, my PHP calendar will appear. And then provides a manipulation on that calendar. I'm just a beginner and a student who doesn't have enough knowledge to program a system using javascript and jQuery so I suggest you to use PHP language :)
`

```<code>//to read the date today
$currentMonth = date ("m");

//timezone
date_default_timezone_set('Asia/Tokyo');

//Today
$today = date ('Y-m-d',time());

// For H3 Title
$html_title = date('m / Y', $timestamp);

//create prev & next month link  (hour,min,sec,mon,day,day,year

$prev = date('Y-m', mktime(0, 0, 0, date('m', $timestamp)-1, 1, date('Y', $timestamp)));
$next = date('Y-m', mktime(0, 0, 0, date('m', $timestamp)+1, 1, date('Y', $timestamp)));

//Number Of days in the month
$day_count = date('t' , $timestamp);

//0:Sun 1:Mon 2:tue
$str = date('w' , mktime(0, 0, 0, date('m', $timestamp), 1,date('Y',$timestamp)));

//create calendar
$weeks = array();
$week = '';

//add empty cellpadding
$week .= str_repeat('<td></td>', $str);
for ( $day = 1; $day <=$day_count; $day++, $str++) {

$date = $ym.'-'.$day;

if ($today == $date) {
    $week .= '<td class="today">'.$day;
    }
    else{
        $week .= '<td>'. $day;
        }
    $week .= '</td>';

    //end of the week or of the moth
    if ($str % 7 == 6 || $day == $day_count) {

        if($day == $day_count) {
        //add empty cell
        $week .= str_repeat ('<td></td>' , 6 - ($str % 7));
        }

        $weeks[] = '<tr>'.$week.'</tr>';

        //prepare for new week
        $week = '';

}

}

?>
<!DOCTYPE.html>
<html.lang"ja">
<head>
</head>
<body>

<div class="container">
<div id="c2">
<h3><div class="title"><a href="?ym=<?php echo $prev; ?>"><</a><?php echo $html_title; ?><a href="?ym=<?php echo $next; ?>">>  </a></div></h3>
<br>
<table class="table table-bordered" id = "calendar" >
    <tr>
    <th>Sun</th>
    <th>Mon</th>
    <th>Tues</th>
    <th>Wed</th>
    <th>Thur</th>
    <th>Fri</th>
    <th>Sat</th>
    </tr>
    <center>
    <?php
    foreach ($weeks as $week) {
            echo $week;
        }
        ?>
    </center>

</table>
</div>

<div id="booking">
        <center>
        <h1>This is your month</h1>
        <input  id="result" type="text" name="month" value="<?php echo $month ?>" readonly>
        <br>
        <h1>Check In </h1>
        <Input type="number" min="<?php echo $day_today; ?>" max="<?php echo $day_count; ?>" value = "<?php echo $day_today; ?>">
        <br>
        <h1>Adults</h1>
        <input type="number" name="adult" min="1" max="10">
        <br>
        <h1>Kids</h1>
        <input type="number" name="kid" min="1" max="10">
        <br>
        </center>
</div>
</div>
</body>
</html>
</code>```

<p>`</p>

答: you cannot do it on php.but you can possibly use javascript. put a onhover attribute on your textbox month and do something on that event</p>

Body:
I've been looking around for some time now and can't seem to find anything for what I'd like. I want it to be that when you hover over a text box named the month, my PHP calendar will appear. And then provides a manipulation on that calendar. I'm just a beginner and a student who doesn't have enough knowledge to program a system using javascript and jQuery so I suggest you to use PHP language :)
`

//to read the date today
$currentMonth = date ("m");

//timezone
date_default_timezone_set('Asia/Tokyo');

//Today
$today = date ('Y-m-d',time());

// For H3 Title
$html_title = date('m / Y', $timestamp);

//create prev & next month link  (hour,min,sec,mon,day,day,year

$prev = date('Y-m', mktime(0, 0, 0, date('m', $timestamp)-1, 1, date('Y', $timestamp)));
$next = date('Y-m', mktime(0, 0, 0, date('m', $timestamp)+1, 1, date('Y', $timestamp)));

//Number Of days in the month
$day_count = date('t' , $timestamp);

//0:Sun 1:Mon 2:tue
$str = date('w' , mktime(0, 0, 0, date('m', $timestamp), 1,date('Y',$timestamp)));

//create calendar
$weeks = array();
$week = '';

//add empty cellpadding
$week .= str_repeat('	', $str);
for ( $day = 1; $day <=$day_count; $day++, $str++) {

$date = $ym.'-'.$day;

if ($today == $date) {
    $week .= ''.$day;
    }
    else{
        $week .= ''. $day;
        }
    $week .= '	';

    //end of the week or of the moth
    if ($str % 7 == 6 || $day == $day_count) {

        if($day == $day_count) {
        //add empty cell
        $week .= str_repeat ('	' , 6 - ($str % 7));
        }

        $weeks[] = '
'.$week.'
';

        //prepare for new week
        $week = '';

}

}

?>
<!DOCTYPE.html>

<a href="?ym=<?php echo $prev; ?>"><<?php echo $html_title; ?><a href="?ym=<?php echo $next; ?>">>

    Sun
    Mon
    Tues
    Wed
    Thur
    Fri
    Sat

    <?php
    foreach ($weeks as $week) {
            echo $week;
        }
        ?>

This is your month

        <input  id="result" type="text" name="month" value="<?php echo $month ?>" readonly>

Check In

        <Input type="number" min="<?php echo $day_today; ?>" max="<?php echo $day_count; ?>" value = "<?php echo $day_today; ?>">

Adults

        <input type="number" name="adult" min="1" max="10">

Kids

        <input type="number" name="kid" min="1" max="10">

`


问:
jquery validator addMethod question
Working with JQuery Validator and just have a quick question.
I'm using addMethod to define a custom validation for Australian phone numbers based on a regex. This is a method that I'd like to use in multiple pages, so I want to define the function in an external .js file, and pop it into the addMethod call.

If I use:

```<code>$.validator.addMethod('phone', regexPhone(value), 'Please enter a valid phone number');
</code>```

I get a reference error: can't find value, but if you build the function straight into the addMethod call, you use the parameter value.

Is there any way to add a reusable function into the call for addMethod?

Ta,
Ryan.

答:
Try

```<code>$.validator.addMethod('phone', regexPhone, 'Please enter a valid phone number');
</code>```

The second parameter in addMethod is a callback, This will call the function regexPhone.

The way you did called the regexPhone function before appending in the callback.

Title: jquery validator addMethod question

Body:
Working with JQuery Validator and just have a quick question.
I'm using addMethod to define a custom validation for Australian phone numbers based on a regex. This is a method that I'd like to use in multiple pages, so I want to define the function in an external .js file, and pop it into the addMethod call.

If I use:

$.validator.addMethod('phone', regexPhone(value), 'Please enter a valid phone number');

I get a reference error: can't find value, but if you build the function straight into the addMethod call, you use the parameter value.

Is there any way to add a reusable function into the call for addMethod?

Ta,
Ryan.

Body:
Try

$.validator.addMethod('phone', regexPhone, 'Please enter a valid phone number');

The second parameter in addMethod is a callback, This will call the function regexPhone.

The way you did called the regexPhone function before appending in the callback.


问:
Using goto statement
```<code>static void Main(string[] args)
{
    double i, j;
    Console.WriteLine("Enter fnum");
    i = Convert.ToDouble(Console.ReadLine());
    start:
    Console.WriteLine("Enter snum");
    j = Convert.ToDouble(Console.ReadLine());

    if(j==0)
    {
        goto start;
    }

    Console.ReadLine();
    Console.WriteLine("Div result is {0}/{1}={2}", i, j, i / j);
}
</code>```

I'm trying to implement Divide by zero using GOTO in c#. I got the result but here I would like to first calculate fnum/snum and print the result and then if I enter snum zero it should ask me enter snum other than zero.Then the goto start label should start working. But here in this case I was only able to execute fnum/snum by default.

```<code>Console.WriteLine("Enter fnum");
i = Convert.ToDouble(Console.ReadLine());
start:
Console.WriteLine("Enter snum");
j = Convert.ToDouble(Console.ReadLine());
</code>```

Here if I enter snum zero it should take me to start label and ask me "enter second number other zero"

Can any one help me?

答:
You absolutely should NOT be using goto. Use a simple while loop instead:

```<code>static void Main(string[] args)
{
    double i, j = 0;
    Console.Write("Enter fnum: ");
    double.TryParse(Console.ReadLine(), out i);

    Console.Write("Enter snum: ");
    while (j == 0)
    {
        double.TryParse(Console.ReadLine(), out j);

        if(j==0)
            Console.WriteLine("Enter a number that is not 0");
    }

    Console.ReadLine();
    Console.WriteLine("Div result is {0}/{1}={2}", i, j, i / j);
}
</code>```

Additionally, I have modified your code to use Double.TryParse instead of Convert.ToDouble(), as is generally recommended. With it, you can implement a check to make sure that the user has actually entered a number. I have also changed Console.WriteLine to Console.Write for the inputs, which doesn't affect the flow of the program at all, but to me makes it better aesthetically.

Title: Using goto statement

Body:
static void Main(string[] args)
{
    double i, j;
    Console.WriteLine("Enter fnum");
    i = Convert.ToDouble(Console.ReadLine());
    start:
    Console.WriteLine("Enter snum");
    j = Convert.ToDouble(Console.ReadLine());

    if(j==0)
    {
        goto start;
    }

    Console.ReadLine();
    Console.WriteLine("Div result is {0}/{1}={2}", i, j, i / j);
}

I'm trying to implement Divide by zero using GOTO in c#. I got the result but here I would like to first calculate fnum/snum and print the result and then if I enter snum zero it should ask me enter snum other than zero.Then the goto start label should start working. But here in this case I was only able to execute fnum/snum by default.

Console.WriteLine("Enter fnum");
i = Convert.ToDouble(Console.ReadLine());
start:
Console.WriteLine("Enter snum");
j = Convert.ToDouble(Console.ReadLine());

Here if I enter snum zero it should take me to start label and ask me "enter second number other zero"

Can any one help me?

Body:
You absolutely should NOT be using goto. Use a simple while loop instead:

static void Main(string[] args)
{
    double i, j = 0;
    Console.Write("Enter fnum: ");
    double.TryParse(Console.ReadLine(), out i);

    Console.Write("Enter snum: ");
    while (j == 0)
    {
        double.TryParse(Console.ReadLine(), out j);

        if(j==0)
            Console.WriteLine("Enter a number that is not 0");
    }

    Console.ReadLine();
    Console.WriteLine("Div result is {0}/{1}={2}", i, j, i / j);
}

Additionally, I have modified your code to use Double.TryParse instead of Convert.ToDouble(), as is generally recommended. With it, you can implement a check to make sure that the user has actually entered a number. I have also changed Console.WriteLine to Console.Write for the inputs, which doesn't affect the flow of the program at all, but to me makes it better aesthetically.


问:
How to make color picker stick/snap to certain values
I will be creating a circular color picker something like this.
There will be 12 colors to pick from (30 degrees per color), and the pointer will be draggable.

I don't need detailed solution, just a guide on how to make the pointer draggable in that way, that if it is set between first and second colors (say 32 degrees) it should slide to 45 degrees (the middle of the second color) and so on.

Thanks!

答:
Here is an example function that I've mentioned in the comment:

```<code>function roundAngle(angle)
{
    return Math.round((angle-15)/30) * 30 + 15;
}
</code>```

And here is an example in practice:
https://jsfiddle.net/JacobDesight/k58z44kb/3/

Body:
Here is an example function that I've mentioned in the comment:

function roundAngle(angle)
{
    return Math.round((angle-15)/30) * 30 + 15;
}

And here is an example in practice:
https://jsfiddle.net/JacobDesight/k58z44kb/3/


问:
AVIdemux python script not working
I have this AVIdemux python script but i don't know how to say where to save my files.

I don't know what i should put in the adm.save() field. i want to save it with source filename

```<code>gui=Gui()
adm=Avidemux()

ext="mp4"
sep = "\\"
dir = "C:\\result\\"

inputFolder = gui.dirSelect("Select the source folder")
#
def convert(filein):
    adm.loadVideo("C:\\doc\\Intro 1080p pfr.mp4")
    if(0 == adm.appendVideo(filein)):
        ui.displayError("oops","cannot load "+filein)
        raise

    adm.videoCodec("copy")
    adm.audioClearTracks()
    adm.setSourceTrackLanguage(0,"unknown")
    adm.audioAddTrack(0)
    adm.audioCodec(0, "copy")
    adm.audioSetDrc(0, 0)
    adm.audioSetShift(0, 0,0)
    adm.setContainer("MP4V2", "optimize=0", "add_itunes_metadata=0")
    adm.save(dir + basename)
    print("Done")

#
# Main
#

list=get_folder_content(inputFolder,ext)

if(list is None):
    raise
for i in list:
        convert(i)
print("Done")
</code>```

答:
You need to put :

```<code>adm.save(dir + "/" + basename(filein))
</code>```

This will save the video in %dir%/video_name.mp4 whatever your dir is. If you want your dir not to be static, you can put :

```<code>destinationFolder = gui.dirSelect("Select the source folder")
</code>```

next your inputFolder and then use :

```<code>adm.save(destinationFolder + "/" + basename(filein))
</code>```

This was your destinationFolder will be whatever you select.

Title: AVIdemux python script not working

Body:
I have this AVIdemux python script but i don't know how to say where to save my files.

I don't know what i should put in the adm.save() field. i want to save it with source filename

gui=Gui()
adm=Avidemux()

ext="mp4"
sep = "\\"
dir = "C:\\result\\"

inputFolder = gui.dirSelect("Select the source folder")
#
def convert(filein):
    adm.loadVideo("C:\\doc\\Intro 1080p pfr.mp4")
    if(0 == adm.appendVideo(filein)):
        ui.displayError("oops","cannot load "+filein)
        raise

    adm.videoCodec("copy")
    adm.audioClearTracks()
    adm.setSourceTrackLanguage(0,"unknown")
    adm.audioAddTrack(0)
    adm.audioCodec(0, "copy")
    adm.audioSetDrc(0, 0)
    adm.audioSetShift(0, 0,0)
    adm.setContainer("MP4V2", "optimize=0", "add_itunes_metadata=0")
    adm.save(dir + basename)
    print("Done")

#
# Main
#

list=get_folder_content(inputFolder,ext)

if(list is None):
    raise
for i in list:
        convert(i)
print("Done")

Body:
You need to put :

adm.save(dir + "/" + basename(filein))

This will save the video in %dir%/video_name.mp4 whatever your dir is. If you want your dir not to be static, you can put :

destinationFolder = gui.dirSelect("Select the source folder")

next your inputFolder and then use :

adm.save(destinationFolder + "/" + basename(filein))

This was your destinationFolder will be whatever you select.


问:
How can I sum up or collect the data on the same field?
Hi ABAP users I would like to ask if what process I can make to COLLECT the data on the same field? all I want to do is to sum up or collect the data in dmbtr that belongs to same date, (date field monat) (werks to plant codes)

```<code>it_zfi_vbrp_bseg_1-num3 = it_zfi_vbrp_bseg_1-werks.

it_zfi_vbrp_bseg_1-num2 = it_zfi_vbrp_bseg_1-dmbtr.

COLLECT it_zfi_vbrp_bseg_1.

DELETE ADJACENT DUPLICATES FROM it_zfi_vbrp_bseg_1 COMPARING ALL FIELDS.

Sort it_zfi_vbrp_bseg_1 by werks.

LOOP AT it_zfi_vbrp_bseg_1 into wa_zfi_vbrp_bseg_1 WHERE monat = '01'.

    IF wa_zfi_vbrp_bseg_1-werks EQ '4030'.

        WRITE:/, AT pos wa_zfi_vbrp_bseg_1-dmbtr.

    ENDIF.

ENDLOOP.
</code>```

Any configuration in my codes guys?

答:
Suppose, you already extended standard bseg table with monat field, then you should do like this:

```<code>TYPES: BEGIN OF ty_zfi_vbrp_bseg_1,
        werks TYPE bseg-werks,
        monat TYPE monat,
        dmbtr TYPE bseg-dmbtr,
       END OF ty_zfi_vbrp_bseg_1.

DATA: it_zfi_vbrp_bseg_1 TYPE TABLE OF ty_zfi_vbrp_bseg_1,
      is_zfi_vbrp_bseg_1 TYPE ty_zfi_vbrp_bseg_1.

SELECT werks, monat, dmbtr
INTO TABLE @DATA(lt_bseg)
FROM bseg
WHERE werks = '4030'.

* summation of months
LOOP AT lt_bseg ASSIGNING FIELD-SYMBOL(<fs_line>).
  CLEAR: is_zfi_vbrp_bseg_1.
  MOVE-CORRESPONDING <fs_line> TO is_zfi_vbrp_bseg_1.
  COLLECT is_zfi_vbrp_bseg_1 INTO it_zfi_vbrp_bseg_1.
ENDLOOP.

* output the results
LOOP AT it_zfi_vbrp_bseg_1 ASSIGNING FIELD-SYMBOL(<zfi_line>).
    IF <zfi_line>-werks EQ '4030'.
        WRITE: / <zfi_line>-werks, <zfi_line>-monat, <zfi_line>-dmbtr.
    ENDIF.
ENDLOOP.
</code>```

Couple of notes to your incorrect code:

COLLECT doesn't work like single statement and should be executed in loop.

To sum with COLLECT statement you should declare work area so that all non-key fields would be numeric. Key fields (even if it is implicit key) can be of any type, as opposed to what Ray said. N type is also OK.

DELETE ADJACENT DUPLICATES is redundant here, because after COLLECT (which makes summation by primary key) you won't have any dups.

Body:
Hi ABAP users I would like to ask if what process I can make to COLLECT the data on the same field? all I want to do is to sum up or collect the data in dmbtr that belongs to same date, (date field monat) (werks to plant codes)

it_zfi_vbrp_bseg_1-num3 = it_zfi_vbrp_bseg_1-werks.

it_zfi_vbrp_bseg_1-num2 = it_zfi_vbrp_bseg_1-dmbtr.

COLLECT it_zfi_vbrp_bseg_1.

DELETE ADJACENT DUPLICATES FROM it_zfi_vbrp_bseg_1 COMPARING ALL FIELDS.

Sort it_zfi_vbrp_bseg_1 by werks.

LOOP AT it_zfi_vbrp_bseg_1 into wa_zfi_vbrp_bseg_1 WHERE monat = '01'.

    IF wa_zfi_vbrp_bseg_1-werks EQ '4030'.

        WRITE:/, AT pos wa_zfi_vbrp_bseg_1-dmbtr.

    ENDIF.

ENDLOOP.

Any configuration in my codes guys?

Body:
Suppose, you already extended standard bseg table with monat field, then you should do like this:

TYPES: BEGIN OF ty_zfi_vbrp_bseg_1,
        werks TYPE bseg-werks,
        monat TYPE monat,
        dmbtr TYPE bseg-dmbtr,
       END OF ty_zfi_vbrp_bseg_1.

DATA: it_zfi_vbrp_bseg_1 TYPE TABLE OF ty_zfi_vbrp_bseg_1,
      is_zfi_vbrp_bseg_1 TYPE ty_zfi_vbrp_bseg_1.

SELECT werks, monat, dmbtr
INTO TABLE @DATA(lt_bseg)
FROM bseg
WHERE werks = '4030'.

* summation of months
LOOP AT lt_bseg ASSIGNING FIELD-SYMBOL(<fs_line>).
  CLEAR: is_zfi_vbrp_bseg_1.
  MOVE-CORRESPONDING <fs_line> TO is_zfi_vbrp_bseg_1.
  COLLECT is_zfi_vbrp_bseg_1 INTO it_zfi_vbrp_bseg_1.
ENDLOOP.

* output the results
LOOP AT it_zfi_vbrp_bseg_1 ASSIGNING FIELD-SYMBOL(<zfi_line>).
    IF <zfi_line>-werks EQ '4030'.
        WRITE: / <zfi_line>-werks, <zfi_line>-monat, <zfi_line>-dmbtr.
    ENDIF.
ENDLOOP.

Couple of notes to your incorrect code:

COLLECT doesn't work like single statement and should be executed in loop.

To sum with COLLECT statement you should declare work area so that all non-key fields would be numeric. Key fields (even if it is implicit key) can be of any type, as opposed to what Ray said. N type is also OK.

DELETE ADJACENT DUPLICATES is redundant here, because after COLLECT (which makes summation by primary key) you won't have any dups.


问:
Could not load file or assembly 'Newtonsoft.Json' or one of its dependencies. Manifest definition does not match the assembly reference
Things I've tried after searching:

in Web.Config put a binding on the old version:

```<code><dependentAssembly>
    <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.1.0" />
</dependentAssembly>
</code>```

Edit my .csproj file to make sure there is only one Newtonsoft reference

```<code><Reference Include="Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
   <HintPath>..\packages\Newtonsoft.Json.6.0.1\lib\net45\Newtonsoft.Json.dll</HintPath>
   <SpecificVersion>False</SpecificVersion>
   <Private>True</Private>
</Reference>
</code>```

Search my computer for every Newtonsoft.Json.dll and delete every non 6.0.1 version and delete the contents of my temp folder

Repair/Reinstall the package in nuget manager console

It succeeds on building, but gets the error when going to the site.

EDIT

ok, so then I tried to reinstall like every nuget package, and it seems to have added back the 4.5 version of the newtonsoft.json.dll, but I'm getting the same error. My project's Target freamework is .NET 4.5.1 and here is the stack trace I'm getting now:

Server Error in '/' Application.

Could not load file or assembly Newtonsoft.Json or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.IO.FileLoadException: Could not load file or assembly Newtonsoft.Json or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Assembly Load Trace: The following information can be helpful to determine why the assembly Newtonsoft.Json could not be loaded.

```<code>=== Pre-bind state information ===
LOG: DisplayName = Newtonsoft.Json
(Partial)
WRN: Partial binding information was supplied for an assembly:
WRN: Assembly Name: Newtonsoft.Json | Domain ID: 2
WRN: A partial bind occurs when only part of the assembly display name is provided.
WRN: This might result in the binder loading an incorrect assembly.
WRN: It is recommended to provide a fully specified textual identity for the assembly,
WRN: that consists of the simple name, version, culture, and public key token.
WRN: See whitepaper http://go.microsoft.com/fwlink/?LinkId=109270 for more information and common solutions to this issue.
LOG: Appbase = file:///c:/users/user/documents/visual studio 2013/Projects/foo/bar/
LOG: Initial PrivatePath = c:\users\user\documents\visual studio 2013\Projects\foo\bar\bin
Calling assembly : (Unknown).
 ===
LOG: This bind starts in default load context.
LOG: Using application configuration file: c:\users\user\documents\visual studio 2013\Projects\foo\bar\web.config
LOG: Using host configuration file: C:\Users\user\Documents\IISExpress\config\aspnet.config
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind).
LOG: Attempting download of new URL file:///C:/Users/user/AppData/Local/Temp/1/Temporary ASP.NET Files/root/48686d37/9d7a6572/Newtonsoft.Json.DLL.
LOG: Attempting download of new URL file:///C:/Users/user/AppData/Local/Temp/1/Temporary ASP.NET Files/root/48686d37/9d7a6572/Newtonsoft.Json/Newtonsoft.Json.DLL.
LOG: Attempting download of new URL file:///c:/users/user/documents/visual studio 2013/Projects/foo/bar/bin/Newtonsoft.Json.DLL.
LOG: Using application configuration file: c:\users\user\documents\visual studio 2013\Projects\foo\bar\web.config
LOG: Using host configuration file: C:\Users\user\Documents\IISExpress\config\aspnet.config
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
LOG: Redirect found in application configuration file: 4.5.0.0 redirected to 6.0.1.0.
LOG: Post-policy reference: Newtonsoft.Json, Version=6.0.1.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed
LOG: Attempting download of new URL file:///C:/Users/user/AppData/Local/Temp/1/Temporary ASP.NET Files/root/48686d37/9d7a6572/Newtonsoft.Json.DLL.
LOG: Attempting download of new URL file:///C:/Users/user/AppData/Local/Temp/1/Temporary ASP.NET Files/root/48686d37/9d7a6572/Newtonsoft.Json/Newtonsoft.Json.DLL.
LOG: Attempting download of new URL file:///c:/users/user/documents/visual studio 2013/Projects/foo/bar/bin/Newtonsoft.Json.DLL.
WRN: Comparing the assembly name resulted in the mismatch: Major Version
ERR: Failed to complete setup of assembly (hr = 0x80131040). Probing terminated.
</code>```

Stack Trace:

```<code>[FileLoadException: Could not load file or assembly 'Newtonsoft.Json' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)]

[FileLoadException: Could not load file or assembly 'Newtonsoft.Json, Version=6.0.1.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)]
       System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +0
       System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +34
       System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +152
       System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean forIntrospection) +77
       System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) +16
       System.Reflection.Assembly.Load(String assemblyString) +28
       System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +38

[ConfigurationErrorsException: Could not load file or assembly 'Newtonsoft.Json, Version=6.0.1.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)]
       System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +752
       System.Web.Configuration.CompilationSection.LoadAllAssembliesFromAppDomainBinDirectory() +218
       System.Web.Configuration.CompilationSection.LoadAssembly(AssemblyInfo ai) +130
        System.Web.Compilation.BuildManager.GetReferencedAssemblies(CompilationSection compConfig) +170
       System.Web.Compilation.BuildManager.GetPreStartInitMethodsFromReferencedAssemblies() +91
       System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath, Boolean& isRefAssemblyLoaded) +285
       System.Web.Compilation.BuildManager.ExecutePreAppStart() +153
       System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +516

[HttpException (0x80004005): Could not load file or assembly 'Newtonsoft.Json, Version=6.0.1.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)]
       System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9913572
       System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +101
       System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +254

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18408
</code>```

答:
I resolved it by remove lower version of Newtonsoft.json.dll in bin folder and added Newtonsoft.json.dll V6.0.0.0 and removed the following web.config elements</p>

```<code><dependentAssembly>
    <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed"/>
    <bindingRedirect oldVersion="0.0.0.0-4.5.0.0" newVersion="5.0.8"/>
</dependentAssembly>
</code>```

Body:
Things I've tried after searching:

in Web.Config put a binding on the old version:

<dependentAssembly>
    <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.1.0" />
</dependentAssembly>

Edit my .csproj file to make sure there is only one Newtonsoft reference

<Reference Include="Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
   <HintPath>..\packages\Newtonsoft.Json.6.0.1\lib\net45\Newtonsoft.Json.dll</HintPath>
   <SpecificVersion>False</SpecificVersion>
   <Private>True</Private>
</Reference>

Search my computer for every Newtonsoft.Json.dll and delete every non 6.0.1 version and delete the contents of my temp folder

Repair/Reinstall the package in nuget manager console

It succeeds on building, but gets the error when going to the site.

EDIT

ok, so then I tried to reinstall like every nuget package, and it seems to have added back the 4.5 version of the newtonsoft.json.dll, but I'm getting the same error. My project's Target freamework is .NET 4.5.1 and here is the stack trace I'm getting now:

Server Error in '/' Application.

Could not load file or assembly Newtonsoft.Json or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.IO.FileLoadException: Could not load file or assembly Newtonsoft.Json or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Assembly Load Trace: The following information can be helpful to determine why the assembly Newtonsoft.Json could not be loaded.

=== Pre-bind state information ===
LOG: DisplayName = Newtonsoft.Json
(Partial)
WRN: Partial binding information was supplied for an assembly:
WRN: Assembly Name: Newtonsoft.Json | Domain ID: 2
WRN: A partial bind occurs when only part of the assembly display name is provided.
WRN: This might result in the binder loading an incorrect assembly.
WRN: It is recommended to provide a fully specified textual identity for the assembly,
WRN: that consists of the simple name, version, culture, and public key token.
WRN: See whitepaper http://go.microsoft.com/fwlink/?LinkId=109270 for more information and common solutions to this issue.
LOG: Appbase = file:///c:/users/user/documents/visual studio 2013/Projects/foo/bar/
LOG: Initial PrivatePath = c:\users\user\documents\visual studio 2013\Projects\foo\bar\bin
Calling assembly : (Unknown).
 ===
LOG: This bind starts in default load context.
LOG: Using application configuration file: c:\users\user\documents\visual studio 2013\Projects\foo\bar\web.config
LOG: Using host configuration file: C:\Users\user\Documents\IISExpress\config\aspnet.config
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind).
LOG: Attempting download of new URL file:///C:/Users/user/AppData/Local/Temp/1/Temporary ASP.NET Files/root/48686d37/9d7a6572/Newtonsoft.Json.DLL.
LOG: Attempting download of new URL file:///C:/Users/user/AppData/Local/Temp/1/Temporary ASP.NET Files/root/48686d37/9d7a6572/Newtonsoft.Json/Newtonsoft.Json.DLL.
LOG: Attempting download of new URL file:///c:/users/user/documents/visual studio 2013/Projects/foo/bar/bin/Newtonsoft.Json.DLL.
LOG: Using application configuration file: c:\users\user\documents\visual studio 2013\Projects\foo\bar\web.config
LOG: Using host configuration file: C:\Users\user\Documents\IISExpress\config\aspnet.config
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
LOG: Redirect found in application configuration file: 4.5.0.0 redirected to 6.0.1.0.
LOG: Post-policy reference: Newtonsoft.Json, Version=6.0.1.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed
LOG: Attempting download of new URL file:///C:/Users/user/AppData/Local/Temp/1/Temporary ASP.NET Files/root/48686d37/9d7a6572/Newtonsoft.Json.DLL.
LOG: Attempting download of new URL file:///C:/Users/user/AppData/Local/Temp/1/Temporary ASP.NET Files/root/48686d37/9d7a6572/Newtonsoft.Json/Newtonsoft.Json.DLL.
LOG: Attempting download of new URL file:///c:/users/user/documents/visual studio 2013/Projects/foo/bar/bin/Newtonsoft.Json.DLL.
WRN: Comparing the assembly name resulted in the mismatch: Major Version
ERR: Failed to complete setup of assembly (hr = 0x80131040). Probing terminated.

Stack Trace:

[FileLoadException: Could not load file or assembly 'Newtonsoft.Json' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)]

[FileLoadException: Could not load file or assembly 'Newtonsoft.Json, Version=6.0.1.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)]
       System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +0
       System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +34
       System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +152
       System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean forIntrospection) +77
       System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) +16
       System.Reflection.Assembly.Load(String assemblyString) +28
       System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +38

[ConfigurationErrorsException: Could not load file or assembly 'Newtonsoft.Json, Version=6.0.1.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)]
       System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +752
       System.Web.Configuration.CompilationSection.LoadAllAssembliesFromAppDomainBinDirectory() +218
       System.Web.Configuration.CompilationSection.LoadAssembly(AssemblyInfo ai) +130
        System.Web.Compilation.BuildManager.GetReferencedAssemblies(CompilationSection compConfig) +170
       System.Web.Compilation.BuildManager.GetPreStartInitMethodsFromReferencedAssemblies() +91
       System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath, Boolean& isRefAssemblyLoaded) +285
       System.Web.Compilation.BuildManager.ExecutePreAppStart() +153
       System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +516

[HttpException (0x80004005): Could not load file or assembly 'Newtonsoft.Json, Version=6.0.1.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)]
       System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9913572
       System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +101
       System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +254

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18408

Body:
I resolved it by remove lower version of Newtonsoft.json.dll in bin folder and added Newtonsoft.json.dll V6.0.0.0 and removed the following web.config elements

<dependentAssembly>
    <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed"/>
    <bindingRedirect oldVersion="0.0.0.0-4.5.0.0" newVersion="5.0.8"/>
</dependentAssembly>


问:
How to properly use onError+Throwable in RxJava on Android?
The ObservableEmitter's onError needs a Throwable instance to be passed in, but what is the best practice if I just have some error data? Like below:

```<code>    Observable<JSONObject> o1 = Observable.create(new ObservableOnSubscribe<JSONObject>() {
    @Override
    public void subscribe(final ObservableEmitter<JSONObject> e) throws Exception {
    RemoteApi.getInstance().addR(context, tag, new AsyncCallback<JSONObject, Error>() {
        @Override
        public void onSuccess(JSONObject result) {
        if(e.isDisposed()) {
            return;
        }
        e.onNext(result);
         e.onComplete();
        }

        @Override
        public void onFailure(Error error) {
        if(e.isDisposed()) {
            return;
        }
        e.onError(new Throwable(error.getCode() + " " + error.getMessage()));
        }
    });
    }
});
</code>```

How to pass the error data properly out? I just create a wrapper class for this kind of exception:

```<code>    private static class RxJavaExceptionError extends Exception {
    private Object object;
    public RxJavaExceptionError(Object object) {
        this.object = object;
    }
    public Object get() {
        return object;
    }
}
</code>```

I use the object member to pass data. But I found out I need to many use instanceof to determine if it's RxJavaExceptionError, which is not very delightful. So what the best practice in this case? I don't think this is an unusual case.

Did I express it clearly? My English is not so good.

答:
Sorry I dont quite understand your use case. In case you want the throwable of the error and propagate through the pipeline, did you try the operator onErrorResumeNext?

```<code>/**
 * Here we can see how onErrorResumeNext works and emit an item in case that an error occur in the pipeline and an exception is propagated
 */
@Test
public void observableOnErrorResumeNext() {
    Subscription subscription = Observable.just(null)
            .map(Object::toString)
            .doOnError(failure -> System.out.println("Error:" + failure.getCause()))
            .retryWhen(errors -> errors.doOnNext(o -> count++)
                            .flatMap(t -> count > 3 ? Observable.error(t) :
                                    Observable.just(null).delay(100, TimeUnit.MILLISECONDS)),
                    Schedulers.newThread())
            .onErrorResumeNext(t -> {
                System.out.println("Error after all retries:" + t.getCause());
                return Observable.just("I save the world for extinction!");
            })
            .subscribe(s -> System.out.println(s));
    new TestSubscriber((Observer) subscription).awaitTerminalEvent(500, TimeUnit.MILLISECONDS);
}
</code>```

If you want to see more example take a look here

https://github.com/politrons/reactive/blob/master/src/test/java/rx/observables/errors/ObservableExceptions.java

Body:
The ObservableEmitter's onError needs a Throwable instance to be passed in, but what is the best practice if I just have some error data? Like below:

    Observable<JSONObject> o1 = Observable.create(new ObservableOnSubscribe<JSONObject>() {
    @Override
    public void subscribe(final ObservableEmitter<JSONObject> e) throws Exception {
    RemoteApi.getInstance().addR(context, tag, new AsyncCallback<JSONObject, Error>() {
        @Override
        public void onSuccess(JSONObject result) {
        if(e.isDisposed()) {
            return;
        }
        e.onNext(result);
         e.onComplete();
        }

        @Override
        public void onFailure(Error error) {
        if(e.isDisposed()) {
            return;
        }
        e.onError(new Throwable(error.getCode() + " " + error.getMessage()));
        }
    });
    }
});

How to pass the error data properly out? I just create a wrapper class for this kind of exception:

    private static class RxJavaExceptionError extends Exception {
    private Object object;
    public RxJavaExceptionError(Object object) {
        this.object = object;
    }
    public Object get() {
        return object;
    }
}

I use the object member to pass data. But I found out I need to many use instanceof to determine if it's RxJavaExceptionError, which is not very delightful. So what the best practice in this case? I don't think this is an unusual case.

Did I express it clearly? My English is not so good.

Body:
Sorry I dont quite understand your use case. In case you want the throwable of the error and propagate through the pipeline, did you try the operator onErrorResumeNext?

/**
 * Here we can see how onErrorResumeNext works and emit an item in case that an error occur in the pipeline and an exception is propagated
 */
@Test
public void observableOnErrorResumeNext() {
    Subscription subscription = Observable.just(null)
            .map(Object::toString)
            .doOnError(failure -> System.out.println("Error:" + failure.getCause()))
            .retryWhen(errors -> errors.doOnNext(o -> count++)
                            .flatMap(t -> count > 3 ? Observable.error(t) :
                                    Observable.just(null).delay(100, TimeUnit.MILLISECONDS)),
                    Schedulers.newThread())
            .onErrorResumeNext(t -> {
                System.out.println("Error after all retries:" + t.getCause());
                return Observable.just("I save the world for extinction!");
            })
            .subscribe(s -> System.out.println(s));
    new TestSubscriber((Observer) subscription).awaitTerminalEvent(500, TimeUnit.MILLISECONDS);
}

If you want to see more example take a look here

https://github.com/politrons/reactive/blob/master/src/test/java/rx/observables/errors/ObservableExceptions.java