问:
Error in string index out of range: maf file to fasta file
Context: I am trying to convert a maf file (multiple alignment file) to individual fasta file. I keep running into the same error that I'm not sure how to fix and this may be because I'm relatively new to python. My code is below:

```<code>open_file = open('C:/Users/Danielle/Desktop/Maf_file.maf','r')
for record in open_file:
    print(record[2:7])
    if (record[2] == 'Z'):
        new_file = open(record[2:7]+".fasta",'w')
        header = ">"+record[2:7]+"\n"
        sequence = record[46:len(record)]
        new_file.write(header)
        new_file.write(sequence)
        new_file.close()
    else:
        print("Not correct isolate.")
open_file.close()
</code>```

The error I get is:

```<code>IndexError
Traceback (most recent call last)
      2 for record in open_file:
      3     print(record[2:7])
----> 4     if (record[2] == 'Z'):
      5         new_file = open(record[2:7]+".fasta",'w')
      6         header = ">"+record[2:7]+"\n"
IndexError: string index out of range
</code>```

If I remove the if, else statement it works as I expect but I would like to filter for specific species that start with the character Z.

If anyone could help explain why I can't select for only strings that start with the character Z this way, that would be great! Thanks in advance.

答:
A better answer

This way, we can fix the problem you had and also make it a bit more efficient. You're slicing multiple time the record for [2:7] you should store that in a variable. If the index 2 isn't present in the resulting filename, we can assume the filename is empty. If the filename is empty it will be falsy, if not we can check index 0 because it's certainly will be there and index 0 of filename is index 2 of record.

Second problem is to use the format string instead of + operator. It will convert anything you pass to the format string to a string as the format passed is %s. If you'd pass a False or None value, the program will crash as arithmetic operation are only allowed for str + str.

```<code>open_file = open('C:/Users/Danielle/Desktop/Maf_file.maf','r')

for record in open_file:
    filename = record[2:7]
    print(filename)

    if (filename and filename[0] == 'Z'):
        with open("%s.fasta" % filename,'w') as newfile:
            header = ">%s\n" % filename
            sequence = record[46:len(record)]
            new_file.write(header)
            new_file.write(sequence)
    else:
        print("Not correct isolate.")

open_file.close()
</code>```

A bit of reformat and we'd end up with this:

```<code>def write_fasta(record):
    filename = record[2:7]
    print(filename)

    if (filename and filename[0] == 'Z'):
        with open("%s.fasta" % filename,'w') as new_file:
            header = ">%s\n" % filename
            sequence = record[46:len(record)]
            new_file.write(header)
            new_file.write(sequence)
    else:
        print("Not correct isolate.")

maf_filename = 'C:/Users/Danielle/Desktop/Maf_file.maf'
with open(maf_filename, 'r') as maf:
    for record in maf:
        write_fasta(record)
</code>```

Use the context manager whenever possible as they'll handle the file closing themselves. So no need to explicitly call the close() method.

Body:
Context: I am trying to convert a maf file (multiple alignment file) to individual fasta file. I keep running into the same error that I'm not sure how to fix and this may be because I'm relatively new to python. My code is below:

open_file = open('C:/Users/Danielle/Desktop/Maf_file.maf','r')
for record in open_file:
    print(record[2:7])
    if (record[2] == 'Z'):
        new_file = open(record[2:7]+".fasta",'w')
        header = ">"+record[2:7]+"\n"
        sequence = record[46:len(record)]
        new_file.write(header)
        new_file.write(sequence)
        new_file.close()
    else:
        print("Not correct isolate.")
open_file.close()

The error I get is:

IndexError
Traceback (most recent call last)
      2 for record in open_file:
      3     print(record[2:7])
----> 4     if (record[2] == 'Z'):
      5         new_file = open(record[2:7]+".fasta",'w')
      6         header = ">"+record[2:7]+"\n"
IndexError: string index out of range

If I remove the if, else statement it works as I expect but I would like to filter for specific species that start with the character Z.

If anyone could help explain why I can't select for only strings that start with the character Z this way, that would be great! Thanks in advance.

Body:
A better answer

This way, we can fix the problem you had and also make it a bit more efficient. You're slicing multiple time the record for [2:7] you should store that in a variable. If the index 2 isn't present in the resulting filename, we can assume the filename is empty. If the filename is empty it will be falsy, if not we can check index 0 because it's certainly will be there and index 0 of filename is index 2 of record.

Second problem is to use the format string instead of + operator. It will convert anything you pass to the format string to a string as the format passed is %s. If you'd pass a False or None value, the program will crash as arithmetic operation are only allowed for str + str.

open_file = open('C:/Users/Danielle/Desktop/Maf_file.maf','r')

for record in open_file:
    filename = record[2:7]
    print(filename)

    if (filename and filename[0] == 'Z'):
        with open("%s.fasta" % filename,'w') as newfile:
            header = ">%s\n" % filename
            sequence = record[46:len(record)]
            new_file.write(header)
            new_file.write(sequence)
    else:
        print("Not correct isolate.")

open_file.close()

A bit of reformat and we'd end up with this:

def write_fasta(record):
    filename = record[2:7]
    print(filename)

    if (filename and filename[0] == 'Z'):
        with open("%s.fasta" % filename,'w') as new_file:
            header = ">%s\n" % filename
            sequence = record[46:len(record)]
            new_file.write(header)
            new_file.write(sequence)
    else:
        print("Not correct isolate.")

maf_filename = 'C:/Users/Danielle/Desktop/Maf_file.maf'
with open(maf_filename, 'r') as maf:
    for record in maf:
        write_fasta(record)

Use the context manager whenever possible as they'll handle the file closing themselves. So no need to explicitly call the close() method.


来源: stackexchange

问:
The test Junit and Mockito gives me errors when analyzing the dates with hours
I'm having trouble validating if everything jsonPath is doing is right for my controller. I am new to the testing area and I have taken a referral site, but there are many things in the design that are very characteristic, so it is difficult to find some answers. If anyone can help me, I would be grateful. Code:

```<code>package test

public class FormControllerTest {

  private MockMvc mockMvc;

  @Mock
  private FormServiceImpl formService;

  @Mock
  private UserServiceImpl userService;

  @InjectMocks
  private FormController formController;

  @Before
  public void init() {
    MockitoAnnotations.initMocks(this);

    mockMvc = MockMvcBuilders
            .standaloneSetup(formController)
            .build();
  }
</code>```

Test:

```<code>@Test
public void test_get_Form_success() throws Exception {

    SimpleDateFormat formato = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");

    Date data = formato.parse("2017-01-03 02:00:02");
    Date data2 = formato.parse("2017-01-05 02:00:02");

    Form form = new Form().id(1).name("formTest")
            .active(true).description("Formtesting")
            .dateInit(data).dateEnd(data2);

    //List<Form> forms = Arrays.asList(form.dateInit(data).dateEnd(data2));
    //System.out.println(form.getDateEnd());

    when(formService.findOneForm(form.getId())).thenReturn(form);

    mockMvc.perform(get("/form/{id}",form.getId()))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
            .andExpect(jsonPath("$.id", is(1)))
            .andExpect(jsonPath("$.name", is("formTest")))
            .andExpect(jsonPath("$.active", is(true)))
            .andExpect(jsonPath("$.description", is("Formtesting")))
            .andExpect(jsonPath("$.dateInit", is(form.getDateInit())))
            .andExpect(jsonPath("$.dateEnd", is(form.getDateEnd())));

    verify(formService, times(2)).findOneForm(form.getId());
    verifyNoMoreInteractions(formService);

}
</code>```

Error

java.lang.AssertionError: JSON path "$.dateInit" Expected: is Tue (Jan
  03 02:00:02 BRST 2017)
       but: was "2017-01-03 04:00:02"

Then it adds 2 hours at the end of the execution, how to solve this problem?

答:
```<code>SimpleDateFormat formato = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
</code>```

is not correct. Should probably be yyyy-MM-dd.

See: https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

ContentLicense: CC BY-SA 3.0

Body:
I'm having trouble validating if everything jsonPath is doing is right for my controller. I am new to the testing area and I have taken a referral site, but there are many things in the design that are very characteristic, so it is difficult to find some answers. If anyone can help me, I would be grateful. Code:

package test

public class FormControllerTest {

  private MockMvc mockMvc;

  @Mock
  private FormServiceImpl formService;

  @Mock
  private UserServiceImpl userService;

  @InjectMocks
  private FormController formController;

  @Before
  public void init() {
    MockitoAnnotations.initMocks(this);

    mockMvc = MockMvcBuilders
            .standaloneSetup(formController)
            .build();
  }

Test:

@Test
public void test_get_Form_success() throws Exception {

    SimpleDateFormat formato = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");

    Date data = formato.parse("2017-01-03 02:00:02");
    Date data2 = formato.parse("2017-01-05 02:00:02");

    Form form = new Form().id(1).name("formTest")
            .active(true).description("Formtesting")
            .dateInit(data).dateEnd(data2);

    //List<Form> forms = Arrays.asList(form.dateInit(data).dateEnd(data2));
    //System.out.println(form.getDateEnd());

    when(formService.findOneForm(form.getId())).thenReturn(form);

    mockMvc.perform(get("/form/{id}",form.getId()))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
            .andExpect(jsonPath("$.id", is(1)))
            .andExpect(jsonPath("$.name", is("formTest")))
            .andExpect(jsonPath("$.active", is(true)))
            .andExpect(jsonPath("$.description", is("Formtesting")))
            .andExpect(jsonPath("$.dateInit", is(form.getDateInit())))
            .andExpect(jsonPath("$.dateEnd", is(form.getDateEnd())));

    verify(formService, times(2)).findOneForm(form.getId());
    verifyNoMoreInteractions(formService);

}

Error

java.lang.AssertionError: JSON path "$.dateInit" Expected: is Tue (Jan
  03 02:00:02 BRST 2017)
       but: was "2017-01-03 04:00:02"

Then it adds 2 hours at the end of the execution, how to solve this problem?

Body:
SimpleDateFormat formato = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");

is not correct. Should probably be yyyy-MM-dd.

See: https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html


问:
Removing MS Word XML tags that split text
I am trying to edit text using python regex that originates from an MS Word document that has been created by someone else. The document has specific formatting and equations that need to be preserved. I save the .docx file as a .xml and edit with python. Unfortunately, Word adds XML tags that split the words and messes with my regular expressions. Example(this is the format that Word outputs):

awe</w:t></w:r><w:r w:rsidRPr="00106B67"><w:rPr><w:rFonts w:ascii="Arial" w:hAnsi="Arial" w:cs="Arial"/><w:sz w:val="21"/><w:szCs w:val="21"/></w:rPr><w:t>some

I have attempted to remove the tags with regular expressions and have had little success. Any help is appreciated.

EDIT: The solution does not have to incorporate Python or regex

答:
This isn't really a regex, but try this on for size:</p>

```<code>s = """awe</w:t></w:r><w:r w:rsidRPr="00106B67"><w:rPr><w:rFonts w:ascii="Arial" w:hAnsi="Arial" w:cs="Arial"/><w:sz w:val="21"/><w:szCs w:val="21"/></w:rPr><w:t>some"""

answer = []
depth = 0
for char in s:
    if char == "<": depth += 1
    elif char == ">": depth -= 1

    if depth: continue
    if char == ">": continue

    answer.append(char)

print(''.join(answer))
</code>```

Body:
This isn't really a regex, but try this on for size:

s = """awe</w:t></w:r><w:r w:rsidRPr="00106B67"><w:rPr><w:rFonts w:ascii="Arial" w:hAnsi="Arial" w:cs="Arial"/><w:sz w:val="21"/><w:szCs w:val="21"/></w:rPr><w:t>some"""

answer = []
depth = 0
for char in s:
    if char == "<": depth += 1
    elif char == ">": depth -= 1

    if depth: continue
    if char == ">": continue

    answer.append(char)

print(''.join(answer))


问:
PHP: Simple and universal way to secure uploads: how about XORing with a random number?
I'm trying to implement a simple, universal way to allow file uploads and downloads via a php-script without having to worry about the security of my server.

There are many questions and answers dealing with this, but from what I have seen, they are mostly combinations of several methods (checking the file extension, checking the MIME-type, saving to a protected directory, changing the file name, etc.) that each have their flaws and/or vulnerabilities.

I was thinking of a php-upload-script that creates a random 4-byte-number for each uploaded file, then XORs the content of the file with it (repeating the 4 bytes as often as necessary), and finally attaches the 4 bytes to the file before saving it.

For downloading, the 4 bytes have to be cut off of the file again, the contents will be XORed with them and the result is sent to the client.

This way, I can be sure that the files I save on the server will not be executable or have any potential meaning for any application. Plus I don't need any extra database to store filenames in.

What do you think of this solution with regard to security and performance?
I am a bit concerned about the performance and required processing power on the server side, but then again XOR is generally fast and simple.

答:
Here is the code I'm using for this now, if anyone is interested. It works for me. So far it looks like a rather foolproof solution to me.
I'm still interested, if anyone has an opinion on this.

Upload:

```<code>            <?php
                $outputfilename = $_POST['filename'];
                $inputfile = $_FILES["myblob"]["tmp_name"];
                $tempfilename="temp.tmp";

                if( move_uploaded_file($inputfile, $tempfilename) ) {
                    $XORstring = random_bytes(4);

                    $tempfile=fopen($tempfilename, "r");
                    $outputfile=fopen($outputfilename, "w+");
                    flock($outputfilename, LOCK_EX);

                    fwrite($outputfilename, $XORbytes1);

                    while ( $buffer = fread($tempfile, 4) ) {
                        $buffer = $buffer ^ $XORstring;
                        fwrite($outputfilename, $buffer);
                    }

                    flock($outputfilename, LOCK_UN);

                    fclose($tempfile);
                    fclose($outputfile);

                    unlink($tempfilename);
                }

                exit(0);
            ?>
</code>```

Download:

```<code>            <?php
                $inputfilename = $_POST['filename'];
                $tempfilename = "temp.tmp";

                $inputfile=fopen($inputfilename, "r");
                $tempfile=fopen($tempfilename, "w+");
                flock($tempfile, LOCK_EX);

                $XORstring = fread($inputfile, 4);

                while ( $buffer = fread($inputfile, 4) ) {
                    $buffer = $buffer ^ $XORstring;
                    fwrite($tempfile, $buffer);
                }

                flock($tempfile, LOCK_UN);

                fclose($inputfile);
                fclose($tempfile);

                readfile($tempfile);
                unlink($tempfile);

                exit(0);
            ?>
</code>```

Body:
Here is the code I'm using for this now, if anyone is interested. It works for me. So far it looks like a rather foolproof solution to me.
I'm still interested, if anyone has an opinion on this.

Upload:

            <?php
                $outputfilename = $_POST['filename'];
                $inputfile = $_FILES["myblob"]["tmp_name"];
                $tempfilename="temp.tmp";

                if( move_uploaded_file($inputfile, $tempfilename) ) {
                    $XORstring = random_bytes(4);

                    $tempfile=fopen($tempfilename, "r");
                    $outputfile=fopen($outputfilename, "w+");
                    flock($outputfilename, LOCK_EX);

                    fwrite($outputfilename, $XORbytes1);

                    while ( $buffer = fread($tempfile, 4) ) {
                        $buffer = $buffer ^ $XORstring;
                        fwrite($outputfilename, $buffer);
                    }

                    flock($outputfilename, LOCK_UN);

                    fclose($tempfile);
                    fclose($outputfile);

                    unlink($tempfilename);
                }

                exit(0);
            ?>

Download:

            <?php
                $inputfilename = $_POST['filename'];
                $tempfilename = "temp.tmp";

                $inputfile=fopen($inputfilename, "r");
                $tempfile=fopen($tempfilename, "w+");
                flock($tempfile, LOCK_EX);

                $XORstring = fread($inputfile, 4);

                while ( $buffer = fread($inputfile, 4) ) {
                    $buffer = $buffer ^ $XORstring;
                    fwrite($tempfile, $buffer);
                }

                flock($tempfile, LOCK_UN);

                fclose($inputfile);
                fclose($tempfile);

                readfile($tempfile);
                unlink($tempfile);

                exit(0);
            ?>


问:
Laravel Database Query returns collection of objects - how do I get the values to display?
I guess there is a simple solution to my problem, I'm just a beginner :D

On one of my controllers I have a fairly complex DB request (see below) that returns a collection of objects and not an array (and I think I cannot perform the request with Eloquent?). Now I don't know how I get these values to actually display inside my blade page? Do I have to somehow convert it to an array to do that?

Thank you very much!

Part of TagsController.php:

```<code>$tags = DB::table('tags AS ta')
        ->select('ta.name')
        ->join('tag_thread AS tt', 'tt.tag_id', '=', 'ta.id')
        ->join(DB::raw('(select * from threads order by id desc limit 2000) th'), 'tt.thread_id', '=', 'th.id')
        ->groupBy('ta.name')
        ->orderBy(DB::raw('count(ta.name)'), 'DESC')
        ->limit(5)
        ->get();
</code>```

return $tags:

```<code>[
    {
        "name": "javascript"
    },
    {
        "name": "jquery"
    },
    {
        "name": "php"
    }
]
</code>```

答:
Inside your blade template, you can just loop through them with:</p>

```<code>@foreach ($tags as $tag)
    <div>{{ $tag->name }}</div>
@endforeach
</code>```

Body:
I guess there is a simple solution to my problem, I'm just a beginner :D

On one of my controllers I have a fairly complex DB request (see below) that returns a collection of objects and not an array (and I think I cannot perform the request with Eloquent?). Now I don't know how I get these values to actually display inside my blade page? Do I have to somehow convert it to an array to do that?

Thank you very much!

Part of TagsController.php:

$tags = DB::table('tags AS ta')
        ->select('ta.name')
        ->join('tag_thread AS tt', 'tt.tag_id', '=', 'ta.id')
        ->join(DB::raw('(select * from threads order by id desc limit 2000) th'), 'tt.thread_id', '=', 'th.id')
        ->groupBy('ta.name')
        ->orderBy(DB::raw('count(ta.name)'), 'DESC')
        ->limit(5)
        ->get();

return $tags:

[
    {
        "name": "javascript"
    },
    {
        "name": "jquery"
    },
    {
        "name": "php"
    }
]

Body:
Inside your blade template, you can just loop through them with:

@foreach ($tags as $tag)
    <div>{{ $tag->name }}</div>
@endforeach


问:
PHP - Old session variable on previous page (IE works fine!)
I have a session variable $_SESSION['name']. I set in a php file which is called with ajax inside a keyup event. It works well. Until a user uses the previous page button.

When a user uses this button (or mouse button), the last set session variable value is basically not set. It will return to an older set value (the one before the last one). I wonder how/why and what I can do about it.

I've read quite a lot stackoverflow (and other) solutions, but nothing so far seems to work.

HTML:

```<code>if(isset($_SESSION['name'])) {
    echo '<input type="text" name="name" value="'.$_SESSION['name'].'">'
}

<script type="text/javascript" defer>
    $(function() {
        var name = $('input[name="name"]').val();

        $('input').on('keyup', function() {

            $.ajax({
                url: 'example.php?name=' + name,
                type: 'GET',
                dataType: 'json',
                success: function(data) {
                    // blablabal more code
                }
        });
    });
</script>
</code>```

example.php:

```<code>$_SESSION['name'] = 'test';
</code>```

Please note I'm starting the session on all of my pages with session_start(); and please note that I also tried to regenerate my session id with any hope that would do the trick.

答:
You cannot achieve this you have to reload your page to see the changes.
although here is a suggestion to do this what you want to achieve.

```<code>if(isset($_SESSION['name'])) {
echo '<input type="text" name="name" value="'.$_SESSION['name'].'">'
 }

   <script type="text/javascript" defer>
    $(function() {
    var name = $('input[name="name"]').val();

    $('input').on('keyup', function() {

        $.ajax({
            url: 'example.php?name=' + name,
            type: 'GET',
            dataType: 'json',
            success: function(data) {
               $("[name='name']").val('Your response');
            }
    });
});
</code>```

By doing this you can achieve what you are looking for. also if you load the page it will get the value from session

Body:
I have a session variable $_SESSION['name']. I set in a php file which is called with ajax inside a keyup event. It works well. Until a user uses the previous page button.

When a user uses this button (or mouse button), the last set session variable value is basically not set. It will return to an older set value (the one before the last one). I wonder how/why and what I can do about it.

I've read quite a lot stackoverflow (and other) solutions, but nothing so far seems to work.

HTML:

if(isset($_SESSION['name'])) {
    echo '<input type="text" name="name" value="'.$_SESSION['name'].'">'
}

example.php:

$_SESSION['name'] = 'test';

Please note I'm starting the session on all of my pages with session_start(); and please note that I also tried to regenerate my session id with any hope that would do the trick.

Body:
You cannot achieve this you have to reload your page to see the changes.
although here is a suggestion to do this what you want to achieve.

if(isset($_SESSION['name'])) {
echo '<input type="text" name="name" value="'.$_SESSION['name'].'">'
 }

   <script type="text/javascript" defer>
    $(function() {
    var name = $('input[name="name"]').val();

    $('input').on('keyup', function() {

        $.ajax({
            url: 'example.php?name=' + name,
            type: 'GET',
            dataType: 'json',
            success: function(data) {
               $("[name='name']").val('Your response');
            }
    });
});

By doing this you can achieve what you are looking for. also if you load the page it will get the value from session


问:
how to dynamically add options to an existing select in vanilla javascript
I'd like to add option to a select dynamically using plain javascript.  Everything I could find involves JQuery or tries to create the select dynamically as well.  The closest thing I could find was Dynamically add input type select with options in Javascript which does the latter and was the only I found that doesn't involve JQuery.  Although I did try and use it like so:

```<code>daySelect = document.getElementById('daySelect');
daySelect.innerHTML += "<option'>Hello world</option'>";
alert(daySelect.innerHTML)
</code>```

After I did this there was no change to the select and the alert gave me

```<code>HELLO WORLD</option'>
</code>```

I apologize if this is simple but I'm very new at javascript and web programming in general.  Thank you for any assistance.

EDIT: So I tried the given suggestions like so.

```<code>daySelect = document.getElementById('daySelect');
myOption = document.createElement("option");
myOption.text = "Hello World";
myOption.value = "Hello World";
daySelect.appendChild(myOption);
</code>```

This has not changed the select in the page at all.  Any idea why?  And I did check that the code was being run with an alert.

EDIT: The idea did work, it just turned out that it wasn't displaying a value in the dropdown.  I don't know why but I can figure that one out I think.

答:
.add() also works.

```<code>var daySelect = document.getElementById("myDaySelect");
var myOption = document.createElement("option");
myOption.text = "test";
myOption.value = "value";
daySelect.add(myOption);
</code>```

W3 School - try

Body:
I'd like to add option to a select dynamically using plain javascript.  Everything I could find involves JQuery or tries to create the select dynamically as well.  The closest thing I could find was Dynamically add input type select with options in Javascript which does the latter and was the only I found that doesn't involve JQuery.  Although I did try and use it like so:

daySelect = document.getElementById('daySelect');
daySelect.innerHTML += "<option'>Hello world</option'>";
alert(daySelect.innerHTML)

After I did this there was no change to the select and the alert gave me

HELLO WORLD</option'>

I apologize if this is simple but I'm very new at javascript and web programming in general.  Thank you for any assistance.

EDIT: So I tried the given suggestions like so.

daySelect = document.getElementById('daySelect');
myOption = document.createElement("option");
myOption.text = "Hello World";
myOption.value = "Hello World";
daySelect.appendChild(myOption);

This has not changed the select in the page at all.  Any idea why?  And I did check that the code was being run with an alert.

EDIT: The idea did work, it just turned out that it wasn't displaying a value in the dropdown.  I don't know why but I can figure that one out I think.

Body:
.add() also works.

var daySelect = document.getElementById("myDaySelect");
var myOption = document.createElement("option");
myOption.text = "test";
myOption.value = "value";
daySelect.add(myOption);

W3 School - try

ContentLicense: CC BY-SA 4.0


问:
c# string that has to contain quote "
```<code>string aniPattern=@"(?si:<option value=\\\"(?<year>.*?)\\)";
</code>```

This breakes because the " in the middle. But I need that because I use it in a regex.

I tried to use string aniPattern="(?si:<option value=\\\"(?<year>.*?)\\\\)";(without @) but it isnot a valid regex.

答:
important - it isn't entirely clear what you want to match; I've answered on the premise that only the " is being a problem - but see also Mike Caron's answer which assumes everything is escaped incorrectly.

With a verbatim string literal (i.e. @"..."), " is escaped to "" - so your string becomes:

```<code>string aniPattern=@"(?si:<option value=\\\""(?<year>.*?)\\)";
</code>```

With a regular string literal (without the leading @), you would need a lot worse:

```<code>string aniPattern="(?si:<option value=\\\\\\\"(?<year>.*?)\\\\)";
</code>```

ContentLicense: CC BY-SA 2.5

Title: c# string that has to contain quote "

Body:
string aniPattern=@"(?si:<option value=\\\"(?<year>.*?)\\)";

This breakes because the " in the middle. But I need that because I use it in a regex.

I tried to use string aniPattern="(?si:<option value=\\\"(?<year>.*?)\\\\)";(without @) but it isnot a valid regex.

Body:
important - it isn't entirely clear what you want to match; I've answered on the premise that only the " is being a problem - but see also Mike Caron's answer which assumes everything is escaped incorrectly.

With a verbatim string literal (i.e. @"..."), " is escaped to "" - so your string becomes:

string aniPattern=@"(?si:<option value=\\\""(?<year>.*?)\\)";

With a regular string literal (without the leading @), you would need a lot worse:

string aniPattern="(?si:<option value=\\\\\\\"(?<year>.*?)\\\\)";


答:
You can use @foreach statement in your views to iterate the Collection

```<code>@foreach($tags as $tag)
    <li>{{ $tag->name }}</li>
@endforeach
</code>```

Title: Laravel Database Query returns collection of objects - how do I get the values to display?

Body:
You can use @foreach statement in your views to iterate the Collection

@foreach($tags as $tag)
    <li>{{ $tag->name }}</li>
@endforeach


问:
Generating SpecFlow Reports with the CakeBuild Specflow plugin possible?
Is it possible to generate SpecFlow Reports with the CakeBuild Specflow plugin (CakeBuild SpecFlow) ?

答:
Yes it's possible to create Test Execution report with Cake build. Here's a quick example using NUnit3 as test runner (other supported runners are MSTest, XUnit and NUnit2).

```<code>#tool "nuget:?package=NUnit.ConsoleRunner"
#tool "nuget:?package=SpecFlow"

var target = Argument("target", "Default");

Task("Default")
    .Does(() =>
{
    SpecFlowTestExecutionReport(tool => {
        tool.NUnit3("/path/to/your/tests.dll",
            new NUnit3Settings {
                Results = "/path/to/testresults.xml",
                ResultFormat = "nunit2",
                Labels = NUnit3Labels.All,
                OutputFile = "/path/to/testoutput.txt"
            });
        }, "/path/to/your/test/project.csproj",
        new SpecFlowTestExecutionReportSettings {
            Out = "/path/to/specflow/execution/report.html",
            XsltFile = "/path/to/optional/transform/file.xslt"
        });
});

RunTarget(target);
</code>```

But as Andreas Willich answered, the example output you posted is a SpecFlow+Runner report. Honestly I can't say if the SpecFlow aliases are compatible with that runner. It's only tested with the default SpecFlow runner.

Body:
Yes it's possible to create Test Execution report with Cake build. Here's a quick example using NUnit3 as test runner (other supported runners are MSTest, XUnit and NUnit2).

#tool "nuget:?package=NUnit.ConsoleRunner"
#tool "nuget:?package=SpecFlow"

var target = Argument("target", "Default");

Task("Default")
    .Does(() =>
{
    SpecFlowTestExecutionReport(tool => {
        tool.NUnit3("/path/to/your/tests.dll",
            new NUnit3Settings {
                Results = "/path/to/testresults.xml",
                ResultFormat = "nunit2",
                Labels = NUnit3Labels.All,
                OutputFile = "/path/to/testoutput.txt"
            });
        }, "/path/to/your/test/project.csproj",
        new SpecFlowTestExecutionReportSettings {
            Out = "/path/to/specflow/execution/report.html",
            XsltFile = "/path/to/optional/transform/file.xslt"
        });
});

RunTarget(target);

But as Andreas Willich answered, the example output you posted is a SpecFlow+Runner report. Honestly I can't say if the SpecFlow aliases are compatible with that runner. It's only tested with the default SpecFlow runner.


答:
Use pluck() to get specific columns in array.

```<code>$tags = DB::table('tags AS ta')
        ->select('ta.name')
        ->join('tag_thread AS tt', 'tt.tag_id', '=', 'ta.id')
        ->join(DB::raw('(select * from threads order by id desc limit 2000) th'), 'tt.thread_id', '=', 'th.id')
        ->groupBy('ta.name')
        ->orderBy(DB::raw('count(ta.name)'), 'DESC')
        ->limit(5)
        ->pluck('name');
</code>```

This will output like below and simply use @foreach () in blade

```<code>[
    "name1",
    "name2",
    "name3",
]
</code>```

Body:
Use pluck() to get specific columns in array.

$tags = DB::table('tags AS ta')
        ->select('ta.name')
        ->join('tag_thread AS tt', 'tt.tag_id', '=', 'ta.id')
        ->join(DB::raw('(select * from threads order by id desc limit 2000) th'), 'tt.thread_id', '=', 'th.id')
        ->groupBy('ta.name')
        ->orderBy(DB::raw('count(ta.name)'), 'DESC')
        ->limit(5)
        ->pluck('name');

This will output like below and simply use @foreach () in blade

[
    "name1",
    "name2",
    "name3",
]


问:
Use js function variable in route
I want to pass ID to my route via ajax but cant do that:

```<code>function test(id){
   $('#items').DataTable({
      ajax: {
      url: '{!!  route('routename', ['menu_id' => id]) !!}',
          type: 'POST'
      },
</code>```

It says Use of undefined constant id.
How can i use javascript variables to pass through route?

答:
I think you can do this :</p>

```<code>function test(id){
   var Link = "{!! route('routename',['menu_id' => '']) !!}"+"/"+id;
   $('#items').DataTable({
      ajax: {
      url: Link,
      type: 'POST'
},
</code>```

Title: Use js function variable in route

Body:
I want to pass ID to my route via ajax but cant do that:

function test(id){
   $('#items').DataTable({
      ajax: {
      url: '{!!  route('routename', ['menu_id' => id]) !!}',
          type: 'POST'
      },

It says Use of undefined constant id.
How can i use javascript variables to pass through route?

Body:
I think you can do this :

function test(id){
   var Link = "{!! route('routename',['menu_id' => '']) !!}"+"/"+id;
   $('#items').DataTable({
      ajax: {
      url: Link,
      type: 'POST'
},


问:
Speeding up while loop in R
I am trying to get some statistical information using the code below:

```<code>library(data.table)

df <- fread("input.xyz", header=F, sep = " ", stringsAsFactors = F)
df2 <- read.table("input2.xyz", header=F, sep = " ", stringsAsFactors = F)

df2 <- df2[-which(df2$V3 == 0),]

long <- df2$V1
lat <- df2$V2
fin_mtx <- matrix(NA, nrow=18976, ncol=8)
colnames(fin_mtx) <- c("Longitude", "Latitude", "Mean", "Median", "Std Dev",
                       "Max", "Min", "No. of NA")
fin_mtx <- as.data.frame(fin_mtx)

i = 1
while (i < 18976)
{
  px_vl <- subset(df$V3, (df$V1 > long[i] - 0.125/2) & (df$V1 < long[i] + 0.125/2) &
                         (df$V2 < lat[i] + 0.125/2) & (df$V2 > lat[i] - 0.125/2))
  frq <- as.data.frame(table(px_vl))

  if (frq[1,1] == -32768) {
     fin_mtx[i,8] <- frq[which(frq$px_vl==-32768),2]
     px_vl[px_vl == -32768] <- NA
  }

  fin_mtx[i,1] <- long[i]
  fin_mtx[i,2] <- lat[i]
  fin_mtx[i,3] <- mean(px_vl, na.rm = T)
  fin_mtx[i,4] <- median(px_vl, na.rm = T)
  fin_mtx[i,5] <- sd(px_vl, na.rm = T)
  fin_mtx[i,6] <- max(px_vl, na.rm = T)
  fin_mtx[i,7] <- min(px_vl, na.rm = T)
  i = i + 1
}
</code>```

The df has close to 172 million rows and three columns whereas the df2 has 18,976 rows. Running the code takes a very long time (I mean days). Also, a lot of memory is used. I wanted to reduce this time and computation load. I went through some suggestions like defining the vector beforehand and using data.table in different tutorials, but they aren't helping much.

答:
Try calculating longHigh <- long + 0.125/2 and longLow <- long - 0.125/2 and the same for latHigh and latLow outside of the loop, since that's a fixed calculation, and you're just calling elements out of each list with i.

That way you can reduce

```<code> px_vl <- subset(df$V3, (df$V1 > long[i] - 0.125/2) & (df$V1 < long[i] + 0.125/2) &
                         (df$V2 < lat[i] + 0.125/2) & (df$V2 > lat[i] - 0.125/2))
</code>```

to

```<code>px_vl <- subset(df$V3, (df$V1 > longLow[i]) & (df$V1 < longHigh[i]) &
                        (df$V2 < latHigh[i]) & df$V2 > latLow[i]))
</code>```

That removes four calculations from each iteration of the loop.

Also, I think you can simplify

```<code> if (frq[1,1] == -32768) {
     fin_mtx[i,8] <- frq[which(frq$px_vl==-32768),2]
     px_vl[px_vl == -32768] <- NA
  }
</code>```

by adding the na.strings argument to fread(..., na.strings = "-32768"), and at least skip having to assign NAs with  px_vl[px_vl == -32768] <- NA

Title: Speeding up while loop in R

Body:
I am trying to get some statistical information using the code below:

library(data.table)

df <- fread("input.xyz", header=F, sep = " ", stringsAsFactors = F)
df2 <- read.table("input2.xyz", header=F, sep = " ", stringsAsFactors = F)

df2 <- df2[-which(df2$V3 == 0),]

long <- df2$V1
lat <- df2$V2
fin_mtx <- matrix(NA, nrow=18976, ncol=8)
colnames(fin_mtx) <- c("Longitude", "Latitude", "Mean", "Median", "Std Dev",
                       "Max", "Min", "No. of NA")
fin_mtx <- as.data.frame(fin_mtx)

i = 1
while (i < 18976)
{
  px_vl <- subset(df$V3, (df$V1 > long[i] - 0.125/2) & (df$V1 < long[i] + 0.125/2) &
                         (df$V2 < lat[i] + 0.125/2) & (df$V2 > lat[i] - 0.125/2))
  frq <- as.data.frame(table(px_vl))

  if (frq[1,1] == -32768) {
     fin_mtx[i,8] <- frq[which(frq$px_vl==-32768),2]
     px_vl[px_vl == -32768] <- NA
  }

  fin_mtx[i,1] <- long[i]
  fin_mtx[i,2] <- lat[i]
  fin_mtx[i,3] <- mean(px_vl, na.rm = T)
  fin_mtx[i,4] <- median(px_vl, na.rm = T)
  fin_mtx[i,5] <- sd(px_vl, na.rm = T)
  fin_mtx[i,6] <- max(px_vl, na.rm = T)
  fin_mtx[i,7] <- min(px_vl, na.rm = T)
  i = i + 1
}

The df has close to 172 million rows and three columns whereas the df2 has 18,976 rows. Running the code takes a very long time (I mean days). Also, a lot of memory is used. I wanted to reduce this time and computation load. I went through some suggestions like defining the vector beforehand and using data.table in different tutorials, but they aren't helping much.

Body:
Try calculating longHigh <- long + 0.125/2 and longLow <- long - 0.125/2 and the same for latHigh and latLow outside of the loop, since that's a fixed calculation, and you're just calling elements out of each list with i.

That way you can reduce

 px_vl <- subset(df$V3, (df$V1 > long[i] - 0.125/2) & (df$V1 < long[i] + 0.125/2) &
                         (df$V2 < lat[i] + 0.125/2) & (df$V2 > lat[i] - 0.125/2))

to

px_vl <- subset(df$V3, (df$V1 > longLow[i]) & (df$V1 < longHigh[i]) &
                        (df$V2 < latHigh[i]) & df$V2 > latLow[i]))

That removes four calculations from each iteration of the loop.

Also, I think you can simplify

 if (frq[1,1] == -32768) {
     fin_mtx[i,8] <- frq[which(frq$px_vl==-32768),2]
     px_vl[px_vl == -32768] <- NA
  }

by adding the na.strings argument to fread(..., na.strings = "-32768"), and at least skip having to assign NAs with  px_vl[px_vl == -32768] <- NA


问:
Todo list app using notifications/reminder
I have been teaching myself how to make iOS apps using Swift through a udemy course. I learned how to build a basic To Do list app but I wanted to build more to it by adding weekly reminders/notification setting.

I want the app to count how many times one has completed an item on the list and to send a notification every weekend telling the user the number of times that the item has been completed. For example, if "go to the gym" is on the list, the user is able to check it off every time he "goes to the gym". Then, throughout the week, the app will keep count of how many times "go to the gym" has been checked off and will alert the user at the end of the week "you completed 'go to the gym' x amount of times"

I've been trying to google how to build this function in the app but I am thoroughly confused as to how to approach this issue. Is this even possible? I want the app to send reminders even if the app is closed.

答:
You should do some research about integrating some server side logic with your app.

When it comes to recall a user with some features like notification I think you should start to manage Users in your app.

So that user can signup, you can recognise the user that subscribe to your notification logic and recall him with a routine you will enable on your server.

I think you should do some research on this topics:

Creating a basic server with a simple architecture like Firebase

Handle User Signup

Ask for Notification

Create a routine (basically a function that is ran every day/week) on your server that checks for user activities and send notification based on your rules

There is a chance you can build that without using a server side logic, but I really advise you to learn how to create a dynamic app that integrates with API ( Server Side Logic ) that you build for your future projects.

Hope it helps,

Have a nice day


答: Sure. But the only way you can access that parameter though is through server-side. So, make twitter.js a PHP page (using mod_rewrite or whatever) that grabs $_GET['handle'] and then serves itself as Content-Type: text/javascript and just dump the contents of the js.

Title: In Javascript, is it possible to pass a variable into <script> "src" parameter?

Body: Is it possible in Javascript to pass a variable through the src parameter? ie.


问:
VBA String Normalization (via WinAPI)
I'm new to attempting to write code in VBA to use WinAPI functions.  What encoding does the WinAPI Normalize() function work with?  UTF-16 is what I would expect, but the following does not work.  The number of characters seems like it's not calculated right, and then the attempt to actually create a normalized string will just crash Access.</p>

```<code>'normFormEnum
'not random numbers, but from ...
'https://msdn.microsoft.com/en-us/library/windows/desktop/dd319094(v=vs.85).aspx
'for use in calling the Win API Function NormalizeString()
Public Enum normFormEnum
    normFOther = 0
    normFC = 1      'the W3C (Internet) required normalization format
    normFD = 2
    normFKC = 5
    normFKD = 6
End Enum

'https://msdn.microsoft.com/en-us/library/windows/desktop/dd319093(v=vs.85).aspx
Private Declare Function NormalizeString Lib "Normaliz" ( _
    ByVal normForm As normFormEnum, _
    ByVal lpSrcString As LongPtr, _
    ByVal cwSrcLength As Long, _
    ByRef lpDstString As LongPtr, _
    ByVal cwDstLength As Long _
    ) As Long

Public Function stringNormalize( _
    ByVal theString As String, _
    Optional ByVal normForm As normFormEnum = normFC _
    ) As String

    Dim nChars As Long
    Dim newString As String

    nChars = NormalizeString(normForm, StrPtr(theString), Len(theString), 0&, 0)

    'prefill the string buffer so it can be altered shortly...
    newString = String(nChars, " ")

Debug.Print nChars
'prints nChars, showing that it 3x the amount of characters.

'The following will crash the application....

'    NormalizeString normForm, StrPtr(theString), Len(theString), StrPtr(newString), nChars

    stringNormalize = newString

End Function
</code>```

答:
The function NormalizeString returns an estimated size in bytes when cwDstLength is 0, but you are using it as the number of characters.

So take half the result from the first call and truncate the buffer with the result from the second call:

```<code>Private Declare PtrSafe Function NormalizeString Lib "Normaliz" ( _
  ByVal normForm As Long, _
  ByVal lpSrcString As LongPtr, _
  ByVal cwSrcLength As Long, _
  ByVal lpDstString As LongPtr, _
  ByVal cwDstLength As Long _
) As Long

Public Enum NormalizationForm
  NormOther = 0
  NormC = 1
  NormD = 2
  NormKC = 5
  NormKD = 6
End Enum

Public Function NormalizeStr(source As String, ByVal normForm As NormalizationForm) As String
  Dim buffer As String, size As Long, i As Long

  For i = 1 To 5
    size = NormalizeString(normForm, StrPtr(source), Len(source), StrPtr(buffer), Len(buffer))

    If size >= 0 And size < Len(buffer) Then
      NormalizeStr = Left$(buffer, size)
      Exit Function
    End If

    buffer = String$(Abs(size) + 1, 0)
  Next

  Err.Raise 9, , "NormalizeString failed"
End Function

Public Sub Usage()
  Debug.Print NormalizeStr(ChrW(196), NormD)
  Debug.Print NormalizeStr("A" & ChrW(776), NormC)
End Sub
</code>```

Title: VBA String Normalization (via WinAPI)

Body:
I'm new to attempting to write code in VBA to use WinAPI functions.  What encoding does the WinAPI Normalize() function work with?  UTF-16 is what I would expect, but the following does not work.  The number of characters seems like it's not calculated right, and then the attempt to actually create a normalized string will just crash Access.

'normFormEnum
'not random numbers, but from ...
'https://msdn.microsoft.com/en-us/library/windows/desktop/dd319094(v=vs.85).aspx
'for use in calling the Win API Function NormalizeString()
Public Enum normFormEnum
    normFOther = 0
    normFC = 1      'the W3C (Internet) required normalization format
    normFD = 2
    normFKC = 5
    normFKD = 6
End Enum

'https://msdn.microsoft.com/en-us/library/windows/desktop/dd319093(v=vs.85).aspx
Private Declare Function NormalizeString Lib "Normaliz" ( _
    ByVal normForm As normFormEnum, _
    ByVal lpSrcString As LongPtr, _
    ByVal cwSrcLength As Long, _
    ByRef lpDstString As LongPtr, _
    ByVal cwDstLength As Long _
    ) As Long

Public Function stringNormalize( _
    ByVal theString As String, _
    Optional ByVal normForm As normFormEnum = normFC _
    ) As String

    Dim nChars As Long
    Dim newString As String

    nChars = NormalizeString(normForm, StrPtr(theString), Len(theString), 0&, 0)

    'prefill the string buffer so it can be altered shortly...
    newString = String(nChars, " ")

Debug.Print nChars
'prints nChars, showing that it 3x the amount of characters.

'The following will crash the application....

'    NormalizeString normForm, StrPtr(theString), Len(theString), StrPtr(newString), nChars

    stringNormalize = newString

End Function

Body:
The function NormalizeString returns an estimated size in bytes when cwDstLength is 0, but you are using it as the number of characters.

So take half the result from the first call and truncate the buffer with the result from the second call:

Private Declare PtrSafe Function NormalizeString Lib "Normaliz" ( _
  ByVal normForm As Long, _
  ByVal lpSrcString As LongPtr, _
  ByVal cwSrcLength As Long, _
  ByVal lpDstString As LongPtr, _
  ByVal cwDstLength As Long _
) As Long

Public Enum NormalizationForm
  NormOther = 0
  NormC = 1
  NormD = 2
  NormKC = 5
  NormKD = 6
End Enum

Public Function NormalizeStr(source As String, ByVal normForm As NormalizationForm) As String
  Dim buffer As String, size As Long, i As Long

  For i = 1 To 5
    size = NormalizeString(normForm, StrPtr(source), Len(source), StrPtr(buffer), Len(buffer))

    If size >= 0 And size < Len(buffer) Then
      NormalizeStr = Left$(buffer, size)
      Exit Function
    End If

    buffer = String$(Abs(size) + 1, 0)
  Next

  Err.Raise 9, , "NormalizeString failed"
End Function

Public Sub Usage()
  Debug.Print NormalizeStr(ChrW(196), NormD)
  Debug.Print NormalizeStr("A" & ChrW(776), NormC)
End Sub


问:
Read mnist images into Tensorflow
I was looking at this Tensorflow tutorial.

In the tutorial the images are magically read like this:

```<code>mnist = learn.datasets.load_dataset("mnist")
train_data = mnist.train.images
</code>```

My images are placed in two directories:

```<code>../input/test/
../input/train/
</code>```

They all have a *.jpg ending.

So how can read them into my program?

I don't think I can use learn.datasets.load_dataset because this seems to take in a specialized dataset structure, while I only have folders with images.

答: You can check the answers given in How do I convert a directory of jpeg images to TFRecords file in tensorflow?. Easiest way is to use the utility provided by tensor flow :build_image_data.py, which does exactly the thing you want to do.</p>

Title: Read mnist images into Tensorflow

Body:
I was looking at this Tensorflow tutorial.

In the tutorial the images are magically read like this:

mnist = learn.datasets.load_dataset("mnist")
train_data = mnist.train.images

My images are placed in two directories:

../input/test/
../input/train/

They all have a *.jpg ending.

So how can read them into my program?

I don't think I can use learn.datasets.load_dataset because this seems to take in a specialized dataset structure, while I only have folders with images.


问:
MySQL JSON_SEARCH and JSON_REPLACE don't escape quotes
I have a JSON column in a MySQL DB. I'm trying to replace a JSON object with another using

```<code>UPDATE table SET ColName = JSON_REPLACE(ColName, '{"sample": "sample"}');
</code>```

It seems after executing this statement, MySQL is inserting \" escaped quotes around my JSON properties like so:

{\"sample\": \"sample\"}

This is causing my JSON_SEARCH query to fail in finding "sample" due to the escaped quotes. Is there a way I can use JSON_REPLACE without having it add escapes to the double quotes?

I tried wrapping JSON_UNQUOTE around JSON_REPLACE in my update statement, this did don't resolve the issue.

答:
wchiquito's answer worked

"Try ... CAST('{"sample": "sample"}' AS JSON) ..."

wchiquito, I can change the accepted answer to your comment if you post an answer.

Body:
I have a JSON column in a MySQL DB. I'm trying to replace a JSON object with another using

UPDATE table SET ColName = JSON_REPLACE(ColName, '{"sample": "sample"}');

It seems after executing this statement, MySQL is inserting \" escaped quotes around my JSON properties like so:

{\"sample\": \"sample\"}

This is causing my JSON_SEARCH query to fail in finding "sample" due to the escaped quotes. Is there a way I can use JSON_REPLACE without having it add escapes to the double quotes?

I tried wrapping JSON_UNQUOTE around JSON_REPLACE in my update statement, this did don't resolve the issue.


问:
xslt, how to 'flatten' the tag structure for unknown number of child tags
My source file looks like this:

```<code><x>
<names>
         <name>name1</name>
         <name>name2</name>
</names>
<codes>
         <code>code1</code>
         <code>code2</code>
</codes>
<stuff> stuff </stuff>
</x>
</code>```

And I'd like to transform it to get this output:

```<code><out>
<y>
    <name>name1</name>
    <code>code1</code>
    <stuff> stuff </stuff>
</y>
<y>
    <name>name2</name>
    <code>code2</code>
    <stuff> stuff </stuff>
</y>
</out>
</code>```

I don't know the number of name and code tags in source file, but I do know the numer of names equals number of codes.

Please share some tips, how to do it.

答:
This transformation:

```<code><xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:template match="/*">
  <out>
   <xsl:apply-templates select="names/name"/>
  </out>
 </xsl:template>

 <xsl:template match="name">
  <xsl:variable name="vPos" select="position()"/>
  <y>
   <xsl:copy-of select="."/>
   <xsl:copy-of select=
     "../../codes/code[position()=$vPos]"/>
   <xsl:copy-of select="/*/stuff"/>
  </y>
 </xsl:template>
</xsl:stylesheet>
</code>```

when applied on the provided XML document:

```<code><x>
    <names>
        <name>name1</name>
        <name>name2</name>
    </names>
    <codes>
        <code>code1</code>
        <code>code2</code>
    </codes>
    <stuff> stuff </stuff>
</x>
</code>```

produces the wanted, correct result:

```<code><out>
   <y>
      <name>name1</name>
      <code>code1</code>
      <stuff> stuff </stuff>
   </y>
   <y>
      <name>name2</name>
      <code>code2</code>
      <stuff> stuff </stuff>
   </y>
</out>
</code>```

Body:
My source file looks like this:

<x>
<names>
         <name>name1</name>
         <name>name2</name>
</names>
<codes>
         code1
         code2
</codes>
<stuff> stuff </stuff>
</x>

And I'd like to transform it to get this output:

<out>
<y>
    <name>name1</name>
    code1
    <stuff> stuff </stuff>
</y>
<y>
    <name>name2</name>
    code2
    <stuff> stuff </stuff>
</y>
</out>

I don't know the number of name and code tags in source file, but I do know the numer of names equals number of codes.

Please share some tips, how to do it.

Body:
This transformation:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:template match="/*">
  <out>
   <xsl:apply-templates select="names/name"/>
  </out>
 </xsl:template>

 <xsl:template match="name">
  <xsl:variable name="vPos" select="position()"/>
  <y>
   <xsl:copy-of select="."/>
   <xsl:copy-of select=
     "../../codes/code[position()=$vPos]"/>
   <xsl:copy-of select="/*/stuff"/>
  </y>
 </xsl:template>
</xsl:stylesheet>

when applied on the provided XML document:

<x>
    <names>
        <name>name1</name>
        <name>name2</name>
    </names>
    <codes>
        <code>code1</code>
        <code>code2</code>
    </codes>
    <stuff> stuff </stuff>
</x>

produces the wanted, correct result:

<out>
   <y>
      <name>name1</name>
      <code>code1</code>
      <stuff> stuff </stuff>
   </y>
   <y>
      <name>name2</name>
      <code>code2</code>
      <stuff> stuff </stuff>
   </y>
</out>


问:
Starting tomcat failed
Starting of Tomcat failed, check whether the C:\Program Files\Apache Software Foundation\Apache Tomcat 8.0.27\bin\catalina.bat and related scripts are executable.

Been having this problem in netbeans. How to solve the problem? Please help.

答:
Try one of the solutions posted here:
https://forums.netbeans.org/topic62626.html
It worked for me.</p>

Title: Starting tomcat failed


问:
How to remove RunTimeWarning Errors from code?
I keep getting RuntimeWarning when I run the regression code at the very bottom. I am not sure how to fix them. I believe it may be the attencoef list because there is some nan values in it. Any suggestions?

These are the errors I am getting:

```<code>C:\Users\MTM User\Anaconda3\lib\site-packages\scipy\stats\_stats_mstats_common.py:106: RuntimeWarning: invalid value encountered in double_scalars
  slope = r_num / ssxm
C:\Users\MTM User\Anaconda3\lib\site-packages\scipy\stats\_stats_mstats_common.py:116: RuntimeWarning: invalid value encountered in sqrt
  t = r * np.sqrt(df / ((1.0 - r + TINY)*(1.0 + r + TINY)))
C:\Users\MTM User\Anaconda3\lib\site-packages\scipy\stats\_distn_infrastructure.py:879: RuntimeWarning: invalid value encountered in greater
  return (self.a < x) & (x < self.b)
C:\Users\MTM User\Anaconda3\lib\site-packages\scipy\stats\_distn_infrastructure.py:879: RuntimeWarning: invalid value encountered in less
  return (self.a < x) & (x < self.b)
C:\Users\MTM User\Anaconda3\lib\site-packages\scipy\stats\_distn_infrastructure.py:1818: RuntimeWarning: invalid value encountered in less_equal
  cond2 = cond0 & (x <= self.a)
C:\Users\MTM User\Anaconda3\lib\site-packages\scipy\stats\_stats_mstats_common.py:118: RuntimeWarning: invalid value encountered in double_scalars
  sterrest = np.sqrt((1 - r**2) * ssym / ssxm / df)
</code>```

The code:

```<code>for depthvalues in split_depth.values(): # only takes the values (separated lists), removes keys

    # takes into account the number of yows
    count+=1

    depthlst = depthvalues
    depthfirst = depthlst[0] #find my first depth or deepest depth
    depthlast = depthlst[-1] # find my last depth, or shallowest

    depthfirst_index = depth.index(depthfirst) #finds the index of my deepest depth for this segment in the filtered lists
    depthlast_index = depth.index(depthlast) #finds the index of my shallowest depth for this segment in the filtered lists

    irradlst = irrad[depthfirst_index:depthlast_index+1]

    irrad_first = irradlst[0] #finds the corresponding irradiance
    irrad_last = irradlst[-1]
    irrad_last = float(irrad_last)

    irradlst = np.array(irradlst).astype(np.float)
    depthlst = np.array(depthlst).astype(np.float)

    attencoef = [np.log(i/irrad_last) for i in irradlst]

    #whenever I use this line of code(below) I get a bunch of errors
    regress = linregress(attencoef,depthlst)
</code>```

答:
You should filter the warning with:

```<code>import warnings
warnings.filterwarnings("ignore", category=RuntimeWarning)
</code>```

The category is the type of warning you want to silence.

Body:
I keep getting RuntimeWarning when I run the regression code at the very bottom. I am not sure how to fix them. I believe it may be the attencoef list because there is some nan values in it. Any suggestions?

These are the errors I am getting:

C:\Users\MTM User\Anaconda3\lib\site-packages\scipy\stats\_stats_mstats_common.py:106: RuntimeWarning: invalid value encountered in double_scalars
  slope = r_num / ssxm
C:\Users\MTM User\Anaconda3\lib\site-packages\scipy\stats\_stats_mstats_common.py:116: RuntimeWarning: invalid value encountered in sqrt
  t = r * np.sqrt(df / ((1.0 - r + TINY)*(1.0 + r + TINY)))
C:\Users\MTM User\Anaconda3\lib\site-packages\scipy\stats\_distn_infrastructure.py:879: RuntimeWarning: invalid value encountered in greater
  return (self.a < x) & (x < self.b)
C:\Users\MTM User\Anaconda3\lib\site-packages\scipy\stats\_distn_infrastructure.py:879: RuntimeWarning: invalid value encountered in less
  return (self.a < x) & (x < self.b)
C:\Users\MTM User\Anaconda3\lib\site-packages\scipy\stats\_distn_infrastructure.py:1818: RuntimeWarning: invalid value encountered in less_equal
  cond2 = cond0 & (x <= self.a)
C:\Users\MTM User\Anaconda3\lib\site-packages\scipy\stats\_stats_mstats_common.py:118: RuntimeWarning: invalid value encountered in double_scalars
  sterrest = np.sqrt((1 - r**2) * ssym / ssxm / df)

The code:

for depthvalues in split_depth.values(): # only takes the values (separated lists), removes keys

    # takes into account the number of yows
    count+=1

    depthlst = depthvalues
    depthfirst = depthlst[0] #find my first depth or deepest depth
    depthlast = depthlst[-1] # find my last depth, or shallowest

    depthfirst_index = depth.index(depthfirst) #finds the index of my deepest depth for this segment in the filtered lists
    depthlast_index = depth.index(depthlast) #finds the index of my shallowest depth for this segment in the filtered lists

    irradlst = irrad[depthfirst_index:depthlast_index+1]

    irrad_first = irradlst[0] #finds the corresponding irradiance
    irrad_last = irradlst[-1]
    irrad_last = float(irrad_last)

    irradlst = np.array(irradlst).astype(np.float)
    depthlst = np.array(depthlst).astype(np.float)

    attencoef = [np.log(i/irrad_last) for i in irradlst]

    #whenever I use this line of code(below) I get a bunch of errors
    regress = linregress(attencoef,depthlst)

Body:
You should filter the warning with:

import warnings
warnings.filterwarnings("ignore", category=RuntimeWarning)

The category is the type of warning you want to silence.


问:
Data column(s) for axis #0 cannot be of type string in Google Charts with ASP.NET and SQL Server?
I'm trying to display some data in Google Charts but get this error:

Data column(s) for axis #0 cannot be of type string..

This is my first time to use Google Chart in general and I am trying to use with ASP.NET Webforms and SQL Server. I have a WebMethod that returns the data from the database in a format of an array that is bound with Google Chart.

Here's the code of the script:

```<code><script>
    var chartData; // globar variable for hold chart data
    google.load("visualization", "1", { packages: ["corechart"] });

    // Here We will fill chartData

    $(document).ready(function () {

        $.ajax({
            url: "../../Pages/Test.aspx/GetSentimentData",
            data: "",
            dataType: "json",
            type: "POST",
            contentType: "application/json; chartset=utf-8",
            success: function (data) {
                chartData = data.d;
            },
            error: function () {
                alert("Error loading data! Please try again.");
            }
        }).done(function () {
            // after complete loading data
            google.setOnLoadCallback(drawChart3);
            drawChart3();
        });
    });

    function drawChart3() {
        var data = google.visualization.arrayToDataTable(chartData);

        var options = {
            title: "Distribution of Sentiment Analysis Results",
            hAxis: { title: 'University'},
            vAxis: { title: 'Number of Tweets' },
            pointSize: 5
        };

        var columnChart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
        columnChart.draw(data, options);

    }
</script>
</code>```

So could you please tell me how I can create a Google Column Chart where each item in x-axis will have three series?

答:
once the data table is built,

use a data view to create a new column for each unique sentiment label

then aggregate the data view to remove duplicates and total each column

see following snippet...

```<code>function drawChart3() {
  var data = google.visualization.arrayToDataTable(chartData);

  // create data view
  var view = new google.visualization.DataView(data);

  // init column arrays
  var aggColumns = [];
  var viewColumns = [0];

  // build view & agg column for each sentiment label
  data.getDistinctValues(1).forEach(function (label, index) {
    // add view column
    viewColumns.push({
      calc: function (dt, row) {
        if (dt.getValue(row, 1) === label) {
          return dt.getValue(row, 2);
        }
        return null;
      },
      label: label,
      type: 'number'
    });

    // add agg column
    aggColumns.push({
      aggregation: google.visualization.data.sum,
      column: index + 1,
      label: label,
      type: 'number'
    });
  });

  // set view columns
  view.setColumns(viewColumns);

  // agg view by university
  var group = google.visualization.data.group(
    view,
    [0],
    aggColumns
  );

  var options = {
    title: "Distribution of Stanford CoreNLP Sentiment Analysis Results by University",
    hAxis: { title: 'University'},
    vAxis: { title: 'Number of Tweets' },
    pointSize: 5
  };

  var columnChart = new google.visualization.ColumnChart(document.getElementById('stanfrod_sentiment_by_uni_chart_div'));
  columnChart.draw(group, options);  // <-- use agg data table
}
</code>```

note

recommend not using jsapi to load the library, according to release notes...

The version of Google Charts that remains available via the jsapi loader is no longer being updated consistently. Please use the new gstatic loader (loader.js) from now on.

this will also change the load statement to...

```<code>google.charts.load('current', {
  callback: drawChart,
  packages: ['corechart']
});
</code>```

also

you shouldn't be calling setOnLoadCallback more than once

you can depend on google's callback to know when the document is ready

no need for --> $(document).ready

once the callback fires, you can draw as many charts as needed

load google, then use ajax to get data, see setup here --> Javascript ajax get data from C#

Body:
I'm trying to display some data in Google Charts but get this error:

Data column(s) for axis #0 cannot be of type string..

This is my first time to use Google Chart in general and I am trying to use with ASP.NET Webforms and SQL Server. I have a WebMethod that returns the data from the database in a format of an array that is bound with Google Chart.

Here's the code of the script:

So could you please tell me how I can create a Google Column Chart where each item in x-axis will have three series?

Body:
once the data table is built,

use a data view to create a new column for each unique sentiment label

then aggregate the data view to remove duplicates and total each column

see following snippet...

function drawChart3() {
  var data = google.visualization.arrayToDataTable(chartData);

  // create data view
  var view = new google.visualization.DataView(data);

  // init column arrays
  var aggColumns = [];
  var viewColumns = [0];

  // build view & agg column for each sentiment label
  data.getDistinctValues(1).forEach(function (label, index) {
    // add view column
    viewColumns.push({
      calc: function (dt, row) {
        if (dt.getValue(row, 1) === label) {
          return dt.getValue(row, 2);
        }
        return null;
      },
      label: label,
      type: 'number'
    });

    // add agg column
    aggColumns.push({
      aggregation: google.visualization.data.sum,
      column: index + 1,
      label: label,
      type: 'number'
    });
  });

  // set view columns
  view.setColumns(viewColumns);

  // agg view by university
  var group = google.visualization.data.group(
    view,
    [0],
    aggColumns
  );

  var options = {
    title: "Distribution of Stanford CoreNLP Sentiment Analysis Results by University",
    hAxis: { title: 'University'},
    vAxis: { title: 'Number of Tweets' },
    pointSize: 5
  };

  var columnChart = new google.visualization.ColumnChart(document.getElementById('stanfrod_sentiment_by_uni_chart_div'));
  columnChart.draw(group, options);  // <-- use agg data table
}

note

recommend not using jsapi to load the library, according to release notes...

The version of Google Charts that remains available via the jsapi loader is no longer being updated consistently. Please use the new gstatic loader (loader.js) from now on.

<script src="https://www.gstatic.com/charts/loader.js"></script>

this will also change the load statement to...

google.charts.load('current', {
  callback: drawChart,
  packages: ['corechart']
});

also

you shouldn't be calling setOnLoadCallback more than once

you can depend on google's callback to know when the document is ready

no need for --> $(document).ready

once the callback fires, you can draw as many charts as needed

load google, then use ajax to get data, see setup here --> Javascript ajax get data from C#


问:
Who can configure endorsement policy in Hyper Ledger Fabric?
I am learning Hyper-ledger fabric and I would like to know more about how to configure Endorsement policies.</p>

答:
Endorsement policies are configured at chaincode instantiation time, and they are configured as logical gate predicates in the following grammer rules:
EXPR(E[, E...])
while EXPR is AND or OR and E is either a principal (i.e Org1.Admin, Org1.Member) or a nested expression EXPR(..)

Example: "AND('Org1.member', 'Org2.member')"

When you do "peer instantiate chaincodeName" you pass -P policyString
and the policyString is an expression such as above.

Example:
 peer chaincode instantiate -C testchainid -n mycc -p github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example02 -c '{"Args":["init","a","100","b","200"]}' -P "AND('Org1.member', 'Org2.member')"


问:
Searching files filtering by extension returns too many results
I'm developing a C++ console application that has to manage files on Windows OS. I need to obtain a 'list' of file names which have a specific extension. I've found a lot of solutions, the most suggested one is the following one:

```<code>HANDLE hFind;
WIN32_FIND_DATA data;

hFind = FindFirstFile("C:\\PWS\\*.sda", &data);
if (hFind != INVALID_HANDLE_VALUE) {
    do {
        cout << data.cFileName << endl;

    } while (FindNextFile(hFind, &data));
    FindClose(hFind);
}
</code>```

Suppose I have these files inside the C:\\PWS folder:

f001.sdac

f002.sda

f003.sdab

f004.sda

The above code prints all of them, while I only need f002.sda and f004.sda.

Any hint?

NB: I don't want to use boost library.

答:
The code also finds "f001.sdac" and "f003.sdab" because FindFirstFile() and FindFirstFileEx() match both the short (8.3) and long file names. For instance, the short file name for "f001.sdac" may be something like "f~1.sda".

The reason for that is backwards compatibility with 16-bit (sigh!) programs.

To work around this issue, call FindFirstFile() with the * wildcard to match all files and then do your own filtering, for instance by calling the PathMatchSpec() function. PathMatchSpec() does string matching only so it doesn't have the weird behaviour of FindFirstFile().

```<code>WIN32_FIND_DATAW data;
HANDLE hFind = FindFirstFileW( L"C:\\PWS\\*", &data );
if( hFind != INVALID_HANDLE_VALUE )
{
    do
    {
        if( ( data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) == 0 &&
            PathMatchSpecW( data.cFileName, L"*.sda" ) )
        {
            std::wcout << data.cFileName << std::endl;
        }
    }
    while( FindNextFileW( hFind, &data ) );

    FindClose( hFind );
}
</code>```

Side note: Calling FindFirstFileEx() with the value of FindExInfoBasic for the fInfoLevelId parameter, which supposedly "does not query the short file name", is not a valid solution for this issue because it will still match short (8.3) file names.

Body:
I'm developing a C++ console application that has to manage files on Windows OS. I need to obtain a 'list' of file names which have a specific extension. I've found a lot of solutions, the most suggested one is the following one:

HANDLE hFind;
WIN32_FIND_DATA data;

hFind = FindFirstFile("C:\\PWS\\*.sda", &data);
if (hFind != INVALID_HANDLE_VALUE) {
    do {
        cout << data.cFileName << endl;

    } while (FindNextFile(hFind, &data));
    FindClose(hFind);
}

Suppose I have these files inside the C:\\PWS folder:

f001.sdac

f002.sda

f003.sdab

f004.sda

The above code prints all of them, while I only need f002.sda and f004.sda.

Any hint?

NB: I don't want to use boost library.

Body:
The code also finds "f001.sdac" and "f003.sdab" because FindFirstFile() and FindFirstFileEx() match both the short (8.3) and long file names. For instance, the short file name for "f001.sdac" may be something like "f~1.sda".

The reason for that is backwards compatibility with 16-bit (sigh!) programs.

To work around this issue, call FindFirstFile() with the * wildcard to match all files and then do your own filtering, for instance by calling the PathMatchSpec() function. PathMatchSpec() does string matching only so it doesn't have the weird behaviour of FindFirstFile().

WIN32_FIND_DATAW data;
HANDLE hFind = FindFirstFileW( L"C:\\PWS\\*", &data );
if( hFind != INVALID_HANDLE_VALUE )
{
    do
    {
        if( ( data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) == 0 &&
            PathMatchSpecW( data.cFileName, L"*.sda" ) )
        {
            std::wcout << data.cFileName << std::endl;
        }
    }
    while( FindNextFileW( hFind, &data ) );

    FindClose( hFind );
}

Side note: Calling FindFirstFileEx() with the value of FindExInfoBasic for the fInfoLevelId parameter, which supposedly "does not query the short file name", is not a valid solution for this issue because it will still match short (8.3) file names.


问:
Convert unsigned char to char* and Concatenate them in C
I want to convert a value unsigned char to one of type char* passing values through a function.

This is my program:

```<code>int my_function(unsigned char param1, unsigned char param2)
{
    char* buffer_char;

    const char* mss_part_1 = "Value 1: ";
    const char* mss_part_2 = " Value 2: ";

    buffer_char = malloc(240);

    strcpy(buffer_char, mss_part_1);    //OK
    strcat(buffer_char, param1);        //ERROR
    strcat(buffer_char, mss_part_2);    //OK
    strcat(buffer_char, param2);        //ERROR

    //Desire Output: "Value 1: 1234 Value 2: 5678"
    printf("%s", buffer_char);

    free(buffer_char);
}

int main(int argc, char const *argv[])
{
    unsigned char value1[10];
    unsigned char value2[10];

    strncpy(value1, "1234", 4);
    strncpy(value2, "5678", 4);

    my_function(value1, value2);

    return 0;
}
</code>```

The problem is in the strcat() function when I try to concatenate the value as "unsigned char" but I have not found the way to convert it so I can concatenate it.

I am trying to use the strcat() function but if there was a more efficient form I would like to know.

Note: I have no problem displaying the output value.

答:
First of all, strncpy doesn't automatically add the terminating NUL character '\0', so you'll have to add it manually. Secondly, your function parameters are unsigned char, which is a single unsigned character, when they should be either unsigned char* or unsigned char[], which is a pointer to unsigned character (a string).

This will work:

```<code>int my_function(unsigned char* param1, unsigned char* param2)
{
    char* buffer_char;

    const char* mss_part_1 = "Value 1: ";
    const char* mss_part_2 = " Value 2: ";

    buffer_char = malloc(240);

    strcpy(buffer_char, mss_part_1);
    strcat(buffer_char, param1);
    strcat(buffer_char, mss_part_2);
    strcat(buffer_char, param2);

    printf("%s", buffer_char);

    free(buffer_char);
}

int main(int argc, char const *argv[])
{
    unsigned char value1[10];
    unsigned char value2[10];

    strncpy(value1, "1234", 4);
    strncpy(value2, "5678", 4);

    value1[4] = '\0';
    value2[4] = '\0';

    my_function(value1, value2);

    return 0;
}
</code>```

Body:
I want to convert a value unsigned char to one of type char* passing values through a function.

This is my program:

int my_function(unsigned char param1, unsigned char param2)
{
    char* buffer_char;

    const char* mss_part_1 = "Value 1: ";
    const char* mss_part_2 = " Value 2: ";

    buffer_char = malloc(240);

    strcpy(buffer_char, mss_part_1);    //OK
    strcat(buffer_char, param1);        //ERROR
    strcat(buffer_char, mss_part_2);    //OK
    strcat(buffer_char, param2);        //ERROR

    //Desire Output: "Value 1: 1234 Value 2: 5678"
    printf("%s", buffer_char);

    free(buffer_char);
}

int main(int argc, char const *argv[])
{
    unsigned char value1[10];
    unsigned char value2[10];

    strncpy(value1, "1234", 4);
    strncpy(value2, "5678", 4);

    my_function(value1, value2);

    return 0;
}

The problem is in the strcat() function when I try to concatenate the value as "unsigned char" but I have not found the way to convert it so I can concatenate it.

I am trying to use the strcat() function but if there was a more efficient form I would like to know.

Note: I have no problem displaying the output value.

Body:
First of all, strncpy doesn't automatically add the terminating NUL character '\0', so you'll have to add it manually. Secondly, your function parameters are unsigned char, which is a single unsigned character, when they should be either unsigned char* or unsigned char[], which is a pointer to unsigned character (a string).

This will work:

int my_function(unsigned char* param1, unsigned char* param2)
{
    char* buffer_char;

    const char* mss_part_1 = "Value 1: ";
    const char* mss_part_2 = " Value 2: ";

    buffer_char = malloc(240);

    strcpy(buffer_char, mss_part_1);
    strcat(buffer_char, param1);
    strcat(buffer_char, mss_part_2);
    strcat(buffer_char, param2);

    printf("%s", buffer_char);

    free(buffer_char);
}

int main(int argc, char const *argv[])
{
    unsigned char value1[10];
    unsigned char value2[10];

    strncpy(value1, "1234", 4);
    strncpy(value2, "5678", 4);

    value1[4] = '\0';
    value2[4] = '\0';

    my_function(value1, value2);

    return 0;
}


问:
How to pull specific object from Json String
I am new to Json Parsing issue I have the below Json object and I need to get the User object from the below Json

```<code>{
  "aud": "RoomyClinetApps",
  "sub": "AAAA",
  "User": {
    "firtsName": "Godavarthi",
    "LastName": "chaitanya"
  },
  "iss": "Roomy",
  "iat": 1499279510
}
</code>```

The below is the code I am trying to pull the User object where the the above json is in jsonInString variable when i trying t print I am getting null

```<code>ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            User user= mapper.readValue(jsonInString.toString(), User.class);

 System.out.println(user.getFirtsName()); --> Null

public class User {
    @JsonProperty
    private String firtsName;
    @JsonProperty
    private String LastName;
}
</code>```

Could some one please Provide me a working code which is more appreciable.

Thanks
Chaitanya

答:
```<code>public class User {
    @JsonProperty
    private String firtsName;
    @JsonProperty
    private String LastName;
}

public class JsonObject{
public string aud;
public String sub;
public User user;
public String iss;
public long iat;

}

ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            JsonObject user= mapper.readValue(jsonInString.toString(), JsonObject.class);
</code>```

Body:
I am new to Json Parsing issue I have the below Json object and I need to get the User object from the below Json

{
  "aud": "RoomyClinetApps",
  "sub": "AAAA",
  "User": {
    "firtsName": "Godavarthi",
    "LastName": "chaitanya"
  },
  "iss": "Roomy",
  "iat": 1499279510
}

The below is the code I am trying to pull the User object where the the above json is in jsonInString variable when i trying t print I am getting null

ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            User user= mapper.readValue(jsonInString.toString(), User.class);

 System.out.println(user.getFirtsName()); --> Null

public class User {
    @JsonProperty
    private String firtsName;
    @JsonProperty
    private String LastName;
}

Could some one please Provide me a working code which is more appreciable.

Thanks
Chaitanya


答: Use two double quotes next to each other, like so: ""

Title: c# string that has to contain quote "

Body:
string aniPattern=@"(?si:<option value=\\\"(?<year>.*?)\\)";

This breakes because the " in the middle. But I need that because I use it in a regex.

I tried to use string aniPattern="(?si:<option value=\\\"(?<year>.*?)\\\\)";(without @) but it isnot a valid regex.


问:
Start up Fabric Composer REST API server
I am trying to use the composer-rest-server package after completing the Fabric Composer quick start, but I failed.

Please give me a hint.

The composer-rest-server package was successfully installed.

npm install -g composer-rest-server

Composer-rest-server started.

composer-rest-server

I was asked to enter simple information about the business network.
After that, I failed to load the connector module 'composer-connector-hlf'.

```? Enter your Fabric Connection Profile Name: defaultProfile
? Enter your Business Network Identifier : digitalproperty-network
? Enter your Fabric username : WebAppAdmin
? Enter your secret: DJY27pEnl16d
? Specify if you want namespaces in the generated REST API: always use namespace
s
? Specify if you want the generated REST API to be secured: Yes

To restart the REST server using the same options, issue the following command:
   composer-rest-server -p defaultProfile -n digitalproperty-network -i WebAppAdmin -s DJY27pEnl16d -N always -S true

Discovering types from business network definition ...
Connection fails: Error: Failed to load connector module "composer-connector-hlf" for connection profile "defaultProfile"
It will be retried for the next request.
Error: Failed to load connector module "composer-connector-hlf" for connection profile "defaultProfile"
    at connectionProfileStore.load.then.e (/home/user1/.nvm/versions/node/v6.9.5/lib/node_modules/composer-rest-server/node_modules/composer-common/lib/connectionprofilemanager.js:148:27)```

How can I solve the problem?

答:
Which version of npm are you using? I faced similar issue on ubuntu 16.4. When I retinstall evberything with lower version of npm it worked perfectly.

npm version when things worked:

```<code>npm --version
3.10.10
</code>```

when I was getting problem as you have mentioned it was 5.x

Body:
I am trying to use the composer-rest-server package after completing the Fabric Composer quick start, but I failed.

Please give me a hint.

The composer-rest-server package was successfully installed.

npm install -g composer-rest-server

Composer-rest-server started.

composer-rest-server

I was asked to enter simple information about the business network.
After that, I failed to load the connector module 'composer-connector-hlf'.

? Enter your Fabric Connection Profile Name: defaultProfile
? Enter your Business Network Identifier : digitalproperty-network
? Enter your Fabric username : WebAppAdmin
? Enter your secret: DJY27pEnl16d
? Specify if you want namespaces in the generated REST API: always use namespace
s
? Specify if you want the generated REST API to be secured: Yes

To restart the REST server using the same options, issue the following command:
   composer-rest-server -p defaultProfile -n digitalproperty-network -i WebAppAdmin -s DJY27pEnl16d -N always -S true

Discovering types from business network definition ...
Connection fails: Error: Failed to load connector module "composer-connector-hlf" for connection profile "defaultProfile"
It will be retried for the next request.
Error: Failed to load connector module "composer-connector-hlf" for connection profile "defaultProfile"
    at connectionProfileStore.load.then.e (/home/user1/.nvm/versions/node/v6.9.5/lib/node_modules/composer-rest-server/node_modules/composer-common/lib/connectionprofilemanager.js:148:27)

How can I solve the problem?

Body:
Which version of npm are you using? I faced similar issue on ubuntu 16.4. When I retinstall evberything with lower version of npm it worked perfectly.

npm version when things worked:

npm --version
3.10.10

when I was getting problem as you have mentioned it was 5.x


问:
InvalidOperationException while trying to modify UI from another thread
I have a checkbox binded to a property that wraps timer.Enabled state.

MainForm:

```<code>chbTimer.DataBindings.Add(new Binding("Checked", _inactividadController, "TimerEnabled")
            {
                DataSourceUpdateMode = DataSourceUpdateMode.OnPropertyChanged,
                ControlUpdateMode = ControlUpdateMode.OnPropertyChanged
            });
</code>```

_inactividadController:

```<code>public bool TimerEnabled
    {
        get { return _timer.Enabled; }
        set
        {
            _timer.Enabled = value;
            InvokePropertyChanged(new PropertyChangedEventArgs("TimerEnabled"));
        }
    }
</code>```

_timer.Elapsed:

```<code>private void Test(object sender, ElapsedEventArgs e)
    {
        TimerEnabled = false;
    }
</code>```

Exception occurs here:

```<code>public event PropertyChangedEventHandler PropertyChanged;

    public void InvokePropertyChanged(PropertyChangedEventArgs e)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
                  handler(this, e); //<-- BOOM
    }
</code>```

I fully understand whats going on here: Timer works on another thread and tries to update chbTimer which is on main thread and this is an illegal operation. But I got no idea on how to fix this issue.

Tried this approach but doesn't work since changes from the UI are not reflected on the binding (when the user checks the the checkbox the timer doesn't change state).

Any suggestions? thanks

答:
Modified the constructor of InactividadController so it receives a SynchronizationContext

on Form.cs

```<code>_inactividadController = new InactividadController(SynchronizationContext.Current);
</code>```

and modified Implementation of INotifyPropertyChanged

```<code>public void InvokePropertyChanged(PropertyChangedEventArgs e)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            _originalContext.Post(delegate
            {
                handler(this, e);
            }, null);
        }
    }
</code>```

Body:
I have a checkbox binded to a property that wraps timer.Enabled state.

MainForm:

chbTimer.DataBindings.Add(new Binding("Checked", _inactividadController, "TimerEnabled")
            {
                DataSourceUpdateMode = DataSourceUpdateMode.OnPropertyChanged,
                ControlUpdateMode = ControlUpdateMode.OnPropertyChanged
            });

_inactividadController:

public bool TimerEnabled
    {
        get { return _timer.Enabled; }
        set
        {
            _timer.Enabled = value;
            InvokePropertyChanged(new PropertyChangedEventArgs("TimerEnabled"));
        }
    }

_timer.Elapsed:

private void Test(object sender, ElapsedEventArgs e)
    {
        TimerEnabled = false;
    }

Exception occurs here:

public event PropertyChangedEventHandler PropertyChanged;

    public void InvokePropertyChanged(PropertyChangedEventArgs e)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
                  handler(this, e); //<-- BOOM
    }

I fully understand whats going on here: Timer works on another thread and tries to update chbTimer which is on main thread and this is an illegal operation. But I got no idea on how to fix this issue.

Tried this approach but doesn't work since changes from the UI are not reflected on the binding (when the user checks the the checkbox the timer doesn't change state).

Any suggestions? thanks

Body:
Modified the constructor of InactividadController so it receives a SynchronizationContext

on Form.cs

_inactividadController = new InactividadController(SynchronizationContext.Current);

and modified Implementation of INotifyPropertyChanged

public void InvokePropertyChanged(PropertyChangedEventArgs e)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            _originalContext.Post(delegate
            {
                handler(this, e);
            }, null);
        }
    }


问:
Blurring an image via CSS?
On many smartphones (Samsung Galaxy II being an example) when you browse through a photo gallery, its blurred copy is laid out in the background. Can this be achieved by CSS dynamically (ie. without the copy of the photo being prepared upfront saved)? Is there any kind of complex CSS image filter to blur an image? </p>

答:
```<code>img {
  filter: blur(var(--blur));
}
</code>```

Title: Blurring an image via CSS?

Body:
img {
  filter: blur(var(--blur));
}


问:
Same method with two different names?
I wold like to use same method but two different names.

For example:

```<code>def func(a):
    print a

def func2(a):
    print a

n= "yes"
func(n)
func2(n)
</code>```

answer should be:

```<code>"yes"
"yes"
</code>```

Would there be any way I can do:

```<code>def fun(a) or func2(a):
    print a
</code>```

or something like this?

答:
Python functions are just objects, you can assign one to another name:

```<code>def fun(a):
    print a

func2 = fun
</code>```

Now the names func2 and fun reference the same function object, you can call it through either name.

Title: Same method with two different names?

Body:
I wold like to use same method but two different names.

For example:

def func(a):
    print a

def func2(a):
    print a

n= "yes"
func(n)
func2(n)

answer should be:

"yes"
"yes"

Would there be any way I can do:

def fun(a) or func2(a):
    print a

or something like this?

Body:
Python functions are just objects, you can assign one to another name:

def fun(a):
    print a

func2 = fun

Now the names func2 and fun reference the same function object, you can call it through either name.


问:
Naming convention for web projects
It is typical in web projects to have multiple solutions work together to produce the desired outcome. In my case, I am currently working on a project that uses the following: HTML, CSS, JavaScript, jQuery, AJAX, JSON, PHP, MySQL, and some other libraries. This is a typical set of technologies for the average project.

At one point throughout the project, and as you might expect, you would need to interact with data that goes across from HTML to PHP via an AJAX call as a JSON object after being processed by either JavaScript or jQuery, and of course this input data is styled via CSS when displayed to the user.

An example of such HTML element is the following:

```<code><input type="text" name="my-input-name" id="my-input-name" />
</code>```

Note that the name and id are hyphenated. This could also be written as

```<code><input type="text" name="my_input_name" id="my_input_name" />
</code>```

Or

```<code><input type="text" name="myInputName" id="myInputName" />
</code>```

That name and id is what could be used by all the aforementioned technologies.

Personally, I prefer hyphenated for CSS, underscore for PHP, camel case for AJAX, and so on.

But then this means the name and id will not follow the desired naming convention in at least one of the used technologies.

I read many many different opinions (including some in Stack Overflow), but none really provided any final conclusion.

So, my question is, which convention should I use? What is best in HTML 5 and  CSS 3 era?

Thanks

答:
It really depends on the style/standards of the project you are using. I've seen all three styles you mentioned. If I may make a recommendation though, I've seen dashes "-" break certain scripts in a Linux environment. Also, underscores "_" are sometimes considered extra clutter if not needed.

If no other style concerns are important, I would recommend the third option of camel case (myInputName). The reason would be in a web environment, things have to be re-compiled each time, so fewer characters are slightly less processing.

Title: Naming convention for web projects

Body:
It is typical in web projects to have multiple solutions work together to produce the desired outcome. In my case, I am currently working on a project that uses the following: HTML, CSS, JavaScript, jQuery, AJAX, JSON, PHP, MySQL, and some other libraries. This is a typical set of technologies for the average project.

At one point throughout the project, and as you might expect, you would need to interact with data that goes across from HTML to PHP via an AJAX call as a JSON object after being processed by either JavaScript or jQuery, and of course this input data is styled via CSS when displayed to the user.

An example of such HTML element is the following:

<input type="text" name="my-input-name" id="my-input-name" />

Note that the name and id are hyphenated. This could also be written as

<input type="text" name="my_input_name" id="my_input_name" />

Or

<input type="text" name="myInputName" id="myInputName" />

That name and id is what could be used by all the aforementioned technologies.

Personally, I prefer hyphenated for CSS, underscore for PHP, camel case for AJAX, and so on.

But then this means the name and id will not follow the desired naming convention in at least one of the used technologies.

I read many many different opinions (including some in Stack Overflow), but none really provided any final conclusion.

So, my question is, which convention should I use? What is best in HTML 5 and  CSS 3 era?

Thanks


问:
Trouble with adding multiple values into array
I'm trying to learn more about arrays and so I just wrote this simple function:
(I'm calling doThis from an onClick for testing purposes).

```<code>function doThis() {
    var multiplier = 3;
    var list = [23, 54, 23, 25, 65];
    var products = multiply(list, multiplier);
    console.log(products);
}
function multiply(list, multiplier) {
    list.forEach(function (element){
        var multi = [element * multiplier];
        console.log(multi);
        return multi;
    });
}
</code>```

My issue is two-fold:

var products is returning undefined.

When I step through the code in the debugger, it shows the arithmetic being done correctly, but it doesn't store more than one value in the variable multi.

The end goal would be to have var products hold the multi array.

答:
```<code> function doThis() {
    var multiplier = 3
    var list = [23, 54, 23, 25, 65]
    var products = multiply(list, multiplier)
    console.log(products)
}

function multiply(list, multiplier) {
var multi = [] ;
list.forEach(
   function (element){
       multi.push(element * multiplier)
       console.log(multi)
       //return multi
   }
);
return multi ;
}
</code>```

Body:
I'm trying to learn more about arrays and so I just wrote this simple function:
(I'm calling doThis from an onClick for testing purposes).

function doThis() {
    var multiplier = 3;
    var list = [23, 54, 23, 25, 65];
    var products = multiply(list, multiplier);
    console.log(products);
}
function multiply(list, multiplier) {
    list.forEach(function (element){
        var multi = [element * multiplier];
        console.log(multi);
        return multi;
    });
}

My issue is two-fold:

var products is returning undefined.

When I step through the code in the debugger, it shows the arithmetic being done correctly, but it doesn't store more than one value in the variable multi.

The end goal would be to have var products hold the multi array.


问:
Cannot connect to Oracle using python 3.4
I just started to learn python and try to connect to oracle 11g, but I always get following error

cx_Oracle.InternalError: No Oracle error?

Here is my simple script to connect to oracle

```<code>import cx_Oracle as oracle
con = oracle.connect('user/password@ip:port/service')
</code>```

Already try to look for any reference in other sites including here but can't find the solution. I don't think I have connection issue to oracle, because I use the same PC to connect to oracle using PHP.
Any advise would be appreciated, thanks.

答:
One thing to keep in mind anytime you work with Oracle is that they use a proprietary connection protocol TNS (Transparent Network Substrate).
Therefore, you might need to use the cx_Oracle.makedsn(ip, port, SID) method and then pass it to cx_Oracle.connect() method to create your connection. Thus the general format on how to set up Oracle connection is:

```<code>import cx_Oracle

ip = 'xxx.xxx.xx.xxx'
port = 'xxxx'
SID = 'SID'
username = 'username'
password = 'password'

dsn_tns = cx_Oracle.makedsn(ip, port, SID)
db = cx_Oracle.connect(username, password, dsn_tns)
</code>```

This is assuming you have already gotten cx_Oracle to work and import properly, which can be finicky depending on your environment.

Body:
I just started to learn python and try to connect to oracle 11g, but I always get following error

cx_Oracle.InternalError: No Oracle error?

Here is my simple script to connect to oracle

import cx_Oracle as oracle
con = oracle.connect('user/password@ip:port/service')

Already try to look for any reference in other sites including here but can't find the solution. I don't think I have connection issue to oracle, because I use the same PC to connect to oracle using PHP.
Any advise would be appreciated, thanks.

Body:
One thing to keep in mind anytime you work with Oracle is that they use a proprietary connection protocol TNS (Transparent Network Substrate).
Therefore, you might need to use the cx_Oracle.makedsn(ip, port, SID) method and then pass it to cx_Oracle.connect() method to create your connection. Thus the general format on how to set up Oracle connection is:

import cx_Oracle

ip = 'xxx.xxx.xx.xxx'
port = 'xxxx'
SID = 'SID'
username = 'username'
password = 'password'

dsn_tns = cx_Oracle.makedsn(ip, port, SID)
db = cx_Oracle.connect(username, password, dsn_tns)

This is assuming you have already gotten cx_Oracle to work and import properly, which can be finicky depending on your environment.


问:
Fastest way to read a binary file with a defined format?
I have large binary data files that have a predefined format, originally written by a Fortran program as little endians. I would like to read these files in the fastest, most efficient manner, so using the array package seemed right up my alley as suggested in Improve speed of reading and converting from binary file?.

The problem is the pre-defined format is non-homogeneous. It looks something like this:
['<2i','<5d','<2i','<d','<i','<3d','<2i','<3d','<i','<d','<i','<3d']

with each integer i taking up 4 bytes, and each double d taking 8 bytes.

Is there a way I can still use the super efficient array package (or another suggestion) but with the right format?

答:
Use struct. In particular, struct.unpack.

```<code>result = struct.unpack("<2i5d...", buffer)
</code>```

Here buffer holds the given binary data.

Body:
Use struct. In particular, struct.unpack.

result = struct.unpack("<2i5d...", buffer)

Here buffer holds the given binary data.


问:
image magick php, install
does image magick come bundled with php? if so how do i enable it, if not where and what do i have to do to integrate it.

many thanks

答:
Default its not bundled with php, you need to install an extension.

Maybe this could help you: http://php.net/manual/en/imagick.setup.php

BTW just search imagick, php and the OS and you will find how to install.

Title: image magick php, install