问:
ag-grid column search not working with object as cell value
I am using cell_renderer to define my cell, something like this:

```<code>        var cell_renderer = function(params) {
            var element = "";
            var values = params.value;
                angular.forEach(values, function(each_param){
                    element += '<a href="#/workunit/' + each_param.id + '" target="_blank">' + each_param.id +
                            '<span class="text-danger text-bold">'+
                            '<span class="" title="' + inactive_message +
                            '">' + inactive_flag + ' </span>' +
                            '<span class="" title="' + misconfigured_message +
                            '"> ' +misconfigured_flag + '</span>'+
                            '</span></a><br>';
                })
            return element;
        };
</code>```

My column definnition is this:

```<code>                var testObject = {};
                testObject.headerName = "my header";
                testObject.field = each_branch;
                testObject.width = 200;
                testObject.cellClassRules = cell_class_rules;
                testObject.cellRenderer = cell_renderer;
                columnDefs.push(testObject);
</code>```

Here testObject.field = each_branch , is a json object.

Hence the inbuild search functionality not working in ag-grid. Can anyone please help me here.

答:
The solution is to provide valueGetter in filter params.

Say for example you have { name: 'Some Name', id: 1 }. In that case you want to filter by the name. So:

```<code>{
  filter: 'agTextColumnFilter',
  filterParams: {
    valueGetter: params => {
      return params.data.name
    }
  }
}
</code>```

Body:
I am using cell_renderer to define my cell, something like this:

        var cell_renderer = function(params) {
            var element = "";
            var values = params.value;
                angular.forEach(values, function(each_param){
                    element += '' + each_param.id +
                            ''+
                            '' + inactive_flag + ' ' +
                            ' ' +misconfigured_flag + ''+
                            '
';
                })
            return element;
        };

My column definnition is this:

                var testObject = {};
                testObject.headerName = "my header";
                testObject.field = each_branch;
                testObject.width = 200;
                testObject.cellClassRules = cell_class_rules;
                testObject.cellRenderer = cell_renderer;
                columnDefs.push(testObject);

Here testObject.field = each_branch , is a json object.

Hence the inbuild search functionality not working in ag-grid. Can anyone please help me here.

Body:
The solution is to provide valueGetter in filter params.

Say for example you have { name: 'Some Name', id: 1 }. In that case you want to filter by the name. So:

{
  filter: 'agTextColumnFilter',
  filterParams: {
    valueGetter: params => {
      return params.data.name
    }
  }
}


来源: stackexchange

问:
How to display alternate lines of text in 2 columns?
I have this part of code where all text lines come to the screen at once.
Now I want for each lines to come on the screen from the other side (ie. first line from left, second from right etc.).
Can anyone help?

```<code>Start                   SEI
                        LDX #$01
                        STX $0286
                        DEX
                        STX $D020
                        STX $D021
                        JSR $E544

mainLoop               LDA #$FA
waitRaster             CMP $D012
                        BNE waitRaster
waitRaster2            CMP $D012
                        BEQ waitRaster2

                        LDA #$0F
                        STA $D020
                        JSR UpdateThings
                        INC $D020
                        JMP mainLoop

UpdateThings        ; is state 0 ?
                        LDA State
                        BNE nextState
                    ; yes, call Move Text to Screen routine
                        JSR MoveTextIn
nextState              RTS
</code>```

I tried with some change here..

```<code>MoveTextIn              LDX 02
                        LDY Counter
loop                   ; LDA TextLines1+(1*40),x
                       ; STA $0400+(1*40),X
                        LDA TextLines2+(1*40),y
                        STA $0400+(1*40),X
                       ; LDA TextLines+(5*40),Y
                       ; STA $0400+(5*40),X
                        INX
                        INY
                        CPY #$28
                        BNE loop
and there....
                       ; LDX #$27
                        TXA
                        SEC
                        SBC Counter
                        TAY
</code>```

and again here...

```<code>loop2                   ;LDA TextLines1+(0*40),x
                        ;STA $0400+(0*40),X
                        LDA TextLines2+(0*40),y
                        STA $0400+(0*40),X
                        ;LDA TextLines+(4*40),Y
                        ;STA $0400+(4*40),X
                        DEX
                        DEY
                        BPL loop2

                        LDA Counter
                        BEQ TextMoveDone

                        DEC Counter
                        RTS
TextMoveDone            INC State
                        RTS

State                   !byte 0

Counter                 !byte $10

TextLines1              !scr "!x-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-xx!"
TextLines2              !scr "!x      commodore master soft         x!"
                        !scr "!        -------------------           !"
                        !scr "!         somewhere in 2019.           !"
                        !scr "!          ----------------            !"
                        !scr "! -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-  !"
</code>```

答:
I'm copying my solution below. I think it is self explanatory.

counter must be set to zero before jumping to MoveTextIn

```<code>MoveTextIn
shiftRight      ldx #$00
                lda textLines1+(0*40),x
                sta $0400+(0*40),x
                lda textLines1(2*40),x
                sta $0400+(2*40),x
                lda textLines1(4*40),x
                sta $0400+(4*40),x

                inx
                cmp #$40
                bne shiftRight

shiftLeft       lda textLines1+(1*40),x
                sta $0400+(1*40),x
                lda textLines1(3*40),x
                sta $0400+(3*40),x
                lda textLines1(5*40),x
                sta $0400+(5*40),x

                dex
                bne shiftLeft

copyRight       ldx counter
                lda textLines1+(1*40),x
                sta $0400+(1*40)-1
                lda textLines1+(3*40),x
                sta $0400+(3*40)-1
                lda textLines1+(5*40),x
                sta $0400+(5*40)-1

copyLeft        sec
                lda #$40
                sbc counter
                tax
                lda textLines1+(0*40),x
                sta $0400+(0*40)-1
                lda textLines1+(2*40),x
                sta $0400+(2*40)-1
                lda textLines1+(4*40),x
                sta $0400+(4*40)-1

                inc counter
                lda counter
                cmp #$40
                beq textMoveDone
                rts

textMoveDone    inc state
                rts
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have this part of code where all text lines come to the screen at once.
Now I want for each lines to come on the screen from the other side (ie. first line from left, second from right etc.).
Can anyone help?

Start                   SEI
                        LDX #$01
                        STX $0286
                        DEX
                        STX $D020
                        STX $D021
                        JSR $E544

mainLoop               LDA #$FA
waitRaster             CMP $D012
                        BNE waitRaster
waitRaster2            CMP $D012
                        BEQ waitRaster2

                        LDA #$0F
                        STA $D020
                        JSR UpdateThings
                        INC $D020
                        JMP mainLoop

UpdateThings        ; is state 0 ?
                        LDA State
                        BNE nextState
                    ; yes, call Move Text to Screen routine
                        JSR MoveTextIn
nextState              RTS

I tried with some change here..

MoveTextIn              LDX 02
                        LDY Counter
loop                   ; LDA TextLines1+(1*40),x
                       ; STA $0400+(1*40),X
                        LDA TextLines2+(1*40),y
                        STA $0400+(1*40),X
                       ; LDA TextLines+(5*40),Y
                       ; STA $0400+(5*40),X
                        INX
                        INY
                        CPY #$28
                        BNE loop
and there....
                       ; LDX #$27
                        TXA
                        SEC
                        SBC Counter
                        TAY

and again here...

loop2                   ;LDA TextLines1+(0*40),x
                        ;STA $0400+(0*40),X
                        LDA TextLines2+(0*40),y
                        STA $0400+(0*40),X
                        ;LDA TextLines+(4*40),Y
                        ;STA $0400+(4*40),X
                        DEX
                        DEY
                        BPL loop2

                        LDA Counter
                        BEQ TextMoveDone

                        DEC Counter
                        RTS
TextMoveDone            INC State
                        RTS

State                   !byte 0

Counter                 !byte $10

TextLines1              !scr "!x-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-xx!"
TextLines2              !scr "!x      commodore master soft         x!"
                        !scr "!        -------------------           !"
                        !scr "!         somewhere in 2019.           !"
                        !scr "!          ----------------            !"
                        !scr "! -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-  !"

Body:
I'm copying my solution below. I think it is self explanatory.

counter must be set to zero before jumping to MoveTextIn

MoveTextIn
shiftRight      ldx #$00
                lda textLines1+(0*40),x
                sta $0400+(0*40),x
                lda textLines1(2*40),x
                sta $0400+(2*40),x
                lda textLines1(4*40),x
                sta $0400+(4*40),x

                inx
                cmp #$40
                bne shiftRight

shiftLeft       lda textLines1+(1*40),x
                sta $0400+(1*40),x
                lda textLines1(3*40),x
                sta $0400+(3*40),x
                lda textLines1(5*40),x
                sta $0400+(5*40),x

                dex
                bne shiftLeft

copyRight       ldx counter
                lda textLines1+(1*40),x
                sta $0400+(1*40)-1
                lda textLines1+(3*40),x
                sta $0400+(3*40)-1
                lda textLines1+(5*40),x
                sta $0400+(5*40)-1

copyLeft        sec
                lda #$40
                sbc counter
                tax
                lda textLines1+(0*40),x
                sta $0400+(0*40)-1
                lda textLines1+(2*40),x
                sta $0400+(2*40)-1
                lda textLines1+(4*40),x
                sta $0400+(4*40)-1

                inc counter
                lda counter
                cmp #$40
                beq textMoveDone
                rts

textMoveDone    inc state
                rts


问:
Convert dataframe date row to a weekend / not weekend value
I have a dataframe with a DATE row and I need to convert it to a row of value 1 if the date is a weekend day and 0 if it is not.

So far, I converted the data to weekdays

```<code>df['WEEKDAY'] = pandas.to_datetime(df['DATE']).dt.dayofweek
</code>```

It's there a way to create this "WEEKEND" row without functions?

Thanks!

答:
One more way of getting weekend indicator is by first converting the date column to day of the week and then using those values to get weekend/not weekend. This can be implemented as follows:</p>

```<code>df['WEEKDAY'] = pandas.to_datetime(df['DATE']).dt.dayofweek  # monday = 0, sunday = 6

df['weekend_indi'] = 0          # Initialize the column with default value of 0
df.loc[df['WEEKDAY'].isin([5, 6]), 'weekend_indi'] = 1  # 5 and 6 correspond to Sat and Sun
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a dataframe with a DATE row and I need to convert it to a row of value 1 if the date is a weekend day and 0 if it is not.

So far, I converted the data to weekdays

df['WEEKDAY'] = pandas.to_datetime(df['DATE']).dt.dayofweek

It's there a way to create this "WEEKEND" row without functions?

Thanks!

Body:
One more way of getting weekend indicator is by first converting the date column to day of the week and then using those values to get weekend/not weekend. This can be implemented as follows:

df['WEEKDAY'] = pandas.to_datetime(df['DATE']).dt.dayofweek  # monday = 0, sunday = 6

df['weekend_indi'] = 0          # Initialize the column with default value of 0
df.loc[df['WEEKDAY'].isin([5, 6]), 'weekend_indi'] = 1  # 5 and 6 correspond to Sat and Sun


问:
How to tar gzip with the same folder name
All, I need to tar gzip the folder and the name should be same as the original folder name.

Example Directory : /user/abc/documents/20190101
I need to tar the 20190101 folder to 20190101.tar.gz by not explicitly specifying the name of the folder.

tar -czvf /user/abc/documents/20190101.tar.gz /user/abc/documents/20190101/testing/20190506-081500000

答:
try this, if you can use bash:

targz.sh

```<code>#!/bin/bash
name=$(sed 's@\(.*/\)\([0-9]*\)/.*@\1|\2@' <<< "$1")
tar -czvf "${name%%|*}${name##*|}.tar.gz" "$1"
</code>```

Usage

```<code>targz.sh "/user/abc/documents/20190101/testing/20190506-081500000"
</code>```

explanation

```<code>sed '              # use sed
s@                 # substitute
\(.*/\)            # save first part into arg1 (\1)
\([0-9]*\)/        # save date into arg2 (\2)
.*@                # ignore all char to the end
\1|\2@' <<< "$1"   # print \1 | \2

${name%%|*}        # \1 --> path
${name##*|}        # \2 --> date
</code>```

Body:
try this, if you can use bash:

targz.sh

#!/bin/bash
name=$(sed 's@\(.*/\)\([0-9]*\)/.*@\1|\2@' <<< "$1")
tar -czvf "${name%%|*}${name##*|}.tar.gz" "$1"

Usage

targz.sh "/user/abc/documents/20190101/testing/20190506-081500000"

explanation

sed '              # use sed
s@                 # substitute
\(.*/\)            # save first part into arg1 (\1)
\([0-9]*\)/        # save date into arg2 (\2)
.*@                # ignore all char to the end
\1|\2@' <<< "$1"   # print \1 | \2

${name%%|*}        # \1 --> path
${name##*|}        # \2 --> date


问:
How to mock a multipart file upload when using Spring and Apache File Upload
The project I'm working on needs to support large file uploads and know the time taken during their upload.

To handle the large files I'm using the streaming API of Apache FileUpload, this also allows me to measure the time taken for the complete stream to be saved.

The problem I'm having is that I cannot seem to be able to utilise MockMvc in an Integration Test on this controller. I know that the controller works as I've successfully uploaded files using postman.

Simplified Controller Code:

```<code>@PostMapping("/upload")
public String handleUpload(HttpServletRequest request) throws Exception {
    ServletFileUpload upload = new ServletFileUpload();
    FileItemIterator iterStream = upload.getItemIterator(request);
    while (iterStream.hasNext()) {
        FileItemStream item = iterStream.next();
        String name = item.getFieldName();
        InputStream stream = item.openStream();
        if (!item.isFormField()) {
            // Process the InputStream
        } else {
            String formFieldValue = Streams.asString(stream);
        }
    }
}
</code>```

Simplified Test Code:

```<code>private fun uploadFile(tfr: TestFileContainer) {
    val mockFile = MockMultipartFile("file", tfr.getData()) // .getData*() returns a ByteArray

    val receiveFileRequest = MockMvcRequestBuilders.multipart("/upload")
    .file(mockFile)
    .contentType(MediaType.MULTIPART_FORM_DATA)

    val result = mockMvc.perform(receiveFileRequest)
      .andExpect(status().isCreated)
      .andExpect(header().exists(LOCATION))
      .andReturn(

}
</code>```

This is the error I'm currently getting

org.apache.tomcat.util.http.fileupload.FileUploadException: the
  request was rejected because no multipart boundary was found

Can anyone help?

答:
The MockMultipartFile approach won't work as Spring does work behind the scenes and simply passes the file around.

Ended up using RestTemplate instead as it actually constructs requests.

Body:
The project I'm working on needs to support large file uploads and know the time taken during their upload.

To handle the large files I'm using the streaming API of Apache FileUpload, this also allows me to measure the time taken for the complete stream to be saved.

The problem I'm having is that I cannot seem to be able to utilise MockMvc in an Integration Test on this controller. I know that the controller works as I've successfully uploaded files using postman.

Simplified Controller Code:

@PostMapping("/upload")
public String handleUpload(HttpServletRequest request) throws Exception {
    ServletFileUpload upload = new ServletFileUpload();
    FileItemIterator iterStream = upload.getItemIterator(request);
    while (iterStream.hasNext()) {
        FileItemStream item = iterStream.next();
        String name = item.getFieldName();
        InputStream stream = item.openStream();
        if (!item.isFormField()) {
            // Process the InputStream
        } else {
            String formFieldValue = Streams.asString(stream);
        }
    }
}

Simplified Test Code:

private fun uploadFile(tfr: TestFileContainer) {
    val mockFile = MockMultipartFile("file", tfr.getData()) // .getData*() returns a ByteArray

    val receiveFileRequest = MockMvcRequestBuilders.multipart("/upload")
    .file(mockFile)
    .contentType(MediaType.MULTIPART_FORM_DATA)

    val result = mockMvc.perform(receiveFileRequest)
      .andExpect(status().isCreated)
      .andExpect(header().exists(LOCATION))
      .andReturn(

}

This is the error I'm currently getting

org.apache.tomcat.util.http.fileupload.FileUploadException: the
  request was rejected because no multipart boundary was found

Can anyone help?


问:
How to check for undefined when using find on an javascript array
In my array I am using .find to find an object and set its property to some value.
  I want to set the name only if there is a value. i.e; check for undefined
  Below is my array, am using .find to find the object and set its name.
  I want to set only if the object with id === checkid is found.</p>

```<code> this.myarray.find(colDef => colDef.id === checkid).name = newname;.
</code>```

答:
/Check if obj isn't null of undefined, and if it's an object. If if is a valid object, then assign the value for '.name'</p>

```<code>const obj = this.myarray.find(colDef => colDef.id === checkid);

if (obj && typeof obj === "object") {
  obj.name = newName;
}
</code>```

Body:
In my array I am using .find to find an object and set its property to some value.
  I want to set the name only if there is a value. i.e; check for undefined
  Below is my array, am using .find to find the object and set its name.
  I want to set only if the object with id === checkid is found.

 this.myarray.find(colDef => colDef.id === checkid).name = newname;.

Body:
/Check if obj isn't null of undefined, and if it's an object. If if is a valid object, then assign the value for '.name'

const obj = this.myarray.find(colDef => colDef.id === checkid);

if (obj && typeof obj === "object") {
  obj.name = newName;
}


问:
How to make snap notepad-plus-plus to support Chinese text?
In Ubuntu/Linux, we can install notepad-plus-plus by snap. Basically, it works fine, but seems couldn't display Chinese text(garbled).

Sincerely, is there anyone have a workaround to fix it?

答:
I had experienced a same problem about Korean.
More easier way is here.

Find default font for snap notepad-plus-plus.

```<code>$ gedit ~/snap/notepad-plus-plus/common/.wine/system.reg

"MS Shell Dlg"="Gulim"

</code>```

Copy the font file into snap notepad-plus-plus wine folder. (For me, it was Gulim.ttc)

```<code>$ cp Gulim.ttc ~/snap/notepad-plus-plus/common/.wine/drive_c/windows/Fonts/
</code>```

Relaunch snap notepad-plus-plus

Body:
I had experienced a same problem about Korean.
More easier way is here.

Find default font for snap notepad-plus-plus.

$ gedit ~/snap/notepad-plus-plus/common/.wine/system.reg

"MS Shell Dlg"="Gulim"

Copy the font file into snap notepad-plus-plus wine folder. (For me, it was Gulim.ttc)

$ cp Gulim.ttc ~/snap/notepad-plus-plus/common/.wine/drive_c/windows/Fonts/

Relaunch snap notepad-plus-plus


问:
How to force use of BibTeX key as citation key with Pandoc and Biber?
I'm trying to get Teaching Tech Together ready for publication. The PDF is looking OK, but I'm struggling to get an HTML that I'm happy with, and I'm hoping someone can help. My LaTeX file contains this:

```<code>\usepackage[backend=biber,style=alphabetic,sorting=nyt,maxbibnames=99]{biblatex}
\addbibresource{book.bib}
</code>```

My BibTeX file contains entries like:

```<code>@inproceedings{Bacc2013,
  author = {Alberto Bacchelli and Christian Bird},
  title = {Expectations, Outcomes, and Challenges of Modern Code Review},
  booktitle = {2013 International Conference on Software Engineering ({ICSE'13})},
  year = {2013},
  month = {5},
  local = {bacchelli-2013-code-review.pdf},
  note = {A summary of work on code review.}
}
</code>```

and I compile everything with:

```<code>$ pdflatex book.tex
$ biber book
$ pdflatex book.tex
$ pdflatex book.tex
</code>```

Citations in the body of the PDF use the BibTeX key as the citation key:

```<code>Debugging depends on being able to read code, which multiple studies have
shown is the single most effective way to find bugs [Basi1987; Keme2009;
Bacc2013]. The code quality rubric developed in [Steg2014; Steg2016a], which is
online at [Steg2016b], is a good checklist of things to look for, though it is best
presented in chunks rather than all at once.
</code>```

The bibliography uses the citation key as well, and includes the note field. (I would rather it came after the date, but I'm trying not to ask for the moon.)

```<code>[Bacc2013] Alberto Bacchelli and Christian Bird. "Expectations, Outcomes, and
    Challenges of Modern Code Review". In: 2013 International Conference on
    Software Engineering (ICSE’13). A summary of work on code review. May 2013.
</code>```

How can I replicate this with Pandoc? My command line is:

```<code>$ pandoc -s --css=assets/bootstrap.css --css=assets/book.css --toc --toc-depth=2 \
  --template=template.html --bibliography=book.bib \
  -o index.html book.tex
</code>```

where template.html is a copy of Pandoc's default HTML template lightly tweaked to use Bootstrap CSS. I would like the resulting HTML to use the BibTeX citation key in both the body and the bibliography. (I would also like citations to hyperlink to the bibliography entry, and bibliography entries to include the note field, but one step at a time...) What is the magic I'm looking for?

答:
In order to produce the same citations across all output formats, pandoc uses the built-in pandoc-citeproc filter, instead of relying on LaTeX. That means also that you cannot use LaTeX to influence citation output:

From the pandoc manual:

Citations and references can be formatted using any style supported by
  the Citation Style Language, listed in the Zotero Style
  Repository. These files are specified using the --csl option or the
  csl metadata field. By default, pandoc-citeproc will use the
  Chicago Manual of Style author-date format. The CSL project provides
  further information on finding and editing styles.

See also this answer on tex.stackexchange.

Body:
I'm trying to get Teaching Tech Together ready for publication. The PDF is looking OK, but I'm struggling to get an HTML that I'm happy with, and I'm hoping someone can help. My LaTeX file contains this:

\usepackage[backend=biber,style=alphabetic,sorting=nyt,maxbibnames=99]{biblatex}
\addbibresource{book.bib}

My BibTeX file contains entries like:

@inproceedings{Bacc2013,
  author = {Alberto Bacchelli and Christian Bird},
  title = {Expectations, Outcomes, and Challenges of Modern Code Review},
  booktitle = {2013 International Conference on Software Engineering ({ICSE'13})},
  year = {2013},
  month = {5},
  local = {bacchelli-2013-code-review.pdf},
  note = {A summary of work on code review.}
}

and I compile everything with:

$ pdflatex book.tex
$ biber book
$ pdflatex book.tex
$ pdflatex book.tex

Citations in the body of the PDF use the BibTeX key as the citation key:

Debugging depends on being able to read code, which multiple studies have
shown is the single most effective way to find bugs [Basi1987; Keme2009;
Bacc2013]. The code quality rubric developed in [Steg2014; Steg2016a], which is
online at [Steg2016b], is a good checklist of things to look for, though it is best
presented in chunks rather than all at once.

The bibliography uses the citation key as well, and includes the note field. (I would rather it came after the date, but I'm trying not to ask for the moon.)

[Bacc2013] Alberto Bacchelli and Christian Bird. "Expectations, Outcomes, and
    Challenges of Modern Code Review". In: 2013 International Conference on
    Software Engineering (ICSE’13). A summary of work on code review. May 2013.

How can I replicate this with Pandoc? My command line is:

$ pandoc -s --css=assets/bootstrap.css --css=assets/book.css --toc --toc-depth=2 \
  --template=template.html --bibliography=book.bib \
  -o index.html book.tex

where template.html is a copy of Pandoc's default HTML template lightly tweaked to use Bootstrap CSS. I would like the resulting HTML to use the BibTeX citation key in both the body and the bibliography. (I would also like citations to hyperlink to the bibliography entry, and bibliography entries to include the note field, but one step at a time...) What is the magic I'm looking for?


问:
Htaccess Hide File Extention and Keep $_GET parameter to be Access
First of all I have 2 file which is index.php and main.php, inside both file I already include the $_GET parameter so it can be access by using this

```<code>index.php?page=login
index.php?page=register&ref=1
main.php?page=member
main.php?page=member&edit
main.php?page=logout
</code>```

by using .htaccess I want to remove the .php extention but I want to keep the parameter and access it with a new url

I made this code

```<code>RewriteEngine On
RewriteBase /

## hide .php extension
# To externally redirect /dir/foo.php to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1 [R=302,L]

RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php?\?p=([^\s]+)? [NC]
RewriteRule ^ /%1? [R=302,L]

RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php?\?p=([^\s]+)&[A-Z]=([^\s]+) [NC]
RewriteRule ^ /%1?/%2? [R=302,L,NE]

# To internally forward /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*?)/?$ $1.php [L]

RewriteRule ^([a-zA-Z0-9_-]+)/?$ index.php?p=$1  [L,QSA]
RewriteRule ^([a-zA-Z0-9_-]+)/?$ main.php?p=$1  [L,QSA]
</code>```

Yes I can access index.php with only http://ex.com/index and main.php http://ex.com/main, but take a look at this code

```<code>RewriteRule ^([a-zA-Z0-9_-]+)/?$ index.php?p=$1  [L,QSA]
RewriteRule ^([a-zA-Z0-9_-]+)/?$ main.php?p=$1  [L,QSA]
</code>```

When the "index.php" rule is in the top, I can access http://ex.com/login or http://ex.com/register (parameters in index.php) but can't access http://ex.com/member or http://ex.com/logout (parameter in main.php)

What I want is to have access to all file by using parameter or not.
thanks

答:
here is the code to use

```<code>RewriteRule ^register/?$ index.php?p=register  [L]
RewriteRule ^login/?$ index.php?p=login  [L]
RewriteRule ^member/?$ main.php?p=member  [L]
RewriteRule ^logout/?$ main.php?p=logout  [L]
</code>```

but yes the parameter can be access by something or what. Just want to find out more.

Body:
First of all I have 2 file which is index.php and main.php, inside both file I already include the $_GET parameter so it can be access by using this

index.php?page=login
index.php?page=register&ref=1
main.php?page=member
main.php?page=member&edit
main.php?page=logout

by using .htaccess I want to remove the .php extention but I want to keep the parameter and access it with a new url

I made this code

RewriteEngine On
RewriteBase /

## hide .php extension
# To externally redirect /dir/foo.php to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1 [R=302,L]

RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php?\?p=([^\s]+)? [NC]
RewriteRule ^ /%1? [R=302,L]

RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php?\?p=([^\s]+)&[A-Z]=([^\s]+) [NC]
RewriteRule ^ /%1?/%2? [R=302,L,NE]

# To internally forward /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*?)/?$ $1.php [L]

RewriteRule ^([a-zA-Z0-9_-]+)/?$ index.php?p=$1  [L,QSA]
RewriteRule ^([a-zA-Z0-9_-]+)/?$ main.php?p=$1  [L,QSA]

Yes I can access index.php with only http://ex.com/index and main.php http://ex.com/main, but take a look at this code

RewriteRule ^([a-zA-Z0-9_-]+)/?$ index.php?p=$1  [L,QSA]
RewriteRule ^([a-zA-Z0-9_-]+)/?$ main.php?p=$1  [L,QSA]

When the "index.php" rule is in the top, I can access http://ex.com/login or http://ex.com/register (parameters in index.php) but can't access http://ex.com/member or http://ex.com/logout (parameter in main.php)

What I want is to have access to all file by using parameter or not.
thanks

Body:
here is the code to use

RewriteRule ^register/?$ index.php?p=register  [L]
RewriteRule ^login/?$ index.php?p=login  [L]
RewriteRule ^member/?$ main.php?p=member  [L]
RewriteRule ^logout/?$ main.php?p=logout  [L]

but yes the parameter can be access by something or what. Just want to find out more.


问:
is there a way to send a file to a custom node form in Node-Red?
In a custom node, I want to provide the possibility to auto-populate form data using a file. So I need to allow a file upload in edit form.

In my custom node, I would like to allow to send a file to a custom end point (made via RED.admin.post) that parse the file and output a json to the caller.

Is there a way to do this?

Body:
I solved in this way:

In template .html file

<script type="text/x-red" data-template-name="...">

    <input id="myFile" type="file" name="fileToParse">
    <input id="file-submit" type="submit" value="Import data from file" name="submit">
...

         oneditprepare: function () {
            $('#file-submit').click(function (e) {
                var fd = new FormData();
                fd.append('file', $('#myFile')[0].files[0]);
                var file = fd.get('file');
                var blb = file.slice();
                var reader = new FileReader();
                // This fires after the blob has been read/loaded.
                reader.addEventListener('loadend', (e) => {
                    var fileData = e.srcElement.result;
                    console.log(fileData);
                    $.ajax({
                        url: '/mynode/file-parse',
                        data: {fileData: fileData},
                        method: 'POST',
                        success: function (data) {
                            populateForm(data);
                        }
                    });
                });
                // Start reading the blob as text.
                reader.readAsBinaryString(blb);
            });

And in .js:

 RED.httpAdmin.post("/mynode/file-parse", function (req, res) {
        var output = [];
        var fileData = req.body.fileData;
        // ... parse fileData end produce output
        res.json(output)
    });


问:
Is there a shorthand way to check for a null to avoid a null reference exception?
I have this code that first checks to see if an object is null like this: this.ButtonLabel.Text != null

```<code>    private async void ChangeTheColours(Object sender, EventArgs e)
    {
        try
        {
            if (this.ButtonLabel.Text != null &&
               (string)this.ButtonLabel.Text.Substring(0, 1) != " ")
            {
                ConfigureColors((Button)sender, "C");
                await Task.Delay(200);
                ConfigureColors((Button)sender, State);
            }
        }
        catch (Exception ex)
        {
            Crashes.TrackError(ex,
                new Dictionary<string, string> {
                        {"ChangeTheColours", "Exception"},
                        {"Device Model", DeviceInfo.Model },
                });
        }
    }
</code>```

Is there a way I can clean up this checking of null and just return from the function later than using the if block and doing the initial this.ButtonLabel.Text check ?

答:
I think this is the cleaner code you are looking for:

```<code>private async void ChangeTheColours(Object sender, EventArgs e)
{
    if(string.IsNullOrWhiteSpace(this.ButtonLabel.Text))
         return;

    try
    {
        ConfigureColors((Button)sender, "C");
        await Task.Delay(200);
        ConfigureColors((Button)sender, State);
    }
    catch (Exception ex)
    {
        Crashes.TrackError(ex,
            new Dictionary<string, string> {
                    {"ChangeTheColours", "Exception"},
                    {"Device Model", DeviceInfo.Model },
            });
    }
}
</code>```

If you only need to check for null (and not whitespaces) and you are using the object right away, you can use Safe navigation operator:

instead of

```<code>if(article != null && article.Author != null
     && !string.IsNullOrWhiteSpace(article.Author.Name)){ }
</code>```

write:

```<code>if(!string.IsNullOrWhiteSpace(article?.Author?.Name)){  }
</code>```

Body:
I have this code that first checks to see if an object is null like this: this.ButtonLabel.Text != null

    private async void ChangeTheColours(Object sender, EventArgs e)
    {
        try
        {
            if (this.ButtonLabel.Text != null &&
               (string)this.ButtonLabel.Text.Substring(0, 1) != " ")
            {
                ConfigureColors((Button)sender, "C");
                await Task.Delay(200);
                ConfigureColors((Button)sender, State);
            }
        }
        catch (Exception ex)
        {
            Crashes.TrackError(ex,
                new Dictionary<string, string> {
                        {"ChangeTheColours", "Exception"},
                        {"Device Model", DeviceInfo.Model },
                });
        }
    }

Is there a way I can clean up this checking of null and just return from the function later than using the if block and doing the initial this.ButtonLabel.Text check ?

Body:
I think this is the cleaner code you are looking for:

private async void ChangeTheColours(Object sender, EventArgs e)
{
    if(string.IsNullOrWhiteSpace(this.ButtonLabel.Text))
         return;

    try
    {
        ConfigureColors((Button)sender, "C");
        await Task.Delay(200);
        ConfigureColors((Button)sender, State);
    }
    catch (Exception ex)
    {
        Crashes.TrackError(ex,
            new Dictionary<string, string> {
                    {"ChangeTheColours", "Exception"},
                    {"Device Model", DeviceInfo.Model },
            });
    }
}

If you only need to check for null (and not whitespaces) and you are using the object right away, you can use Safe navigation operator:

instead of

if(article != null && article.Author != null
     && !string.IsNullOrWhiteSpace(article.Author.Name)){ }

write:

if(!string.IsNullOrWhiteSpace(article?.Author?.Name)){  }


问:
Load json data after ajax submit success
i try to create tags form with textextjs
but i have a problem with ajax to call new data after another ajax success submit

this is my code to call json

```<code>var tagload =   $('#textarea')
    .textext({
        plugins : 'autocomplete filter tags ajax',
        ajax : {
            url: "<?= base_url() ?>admin_ajx/tags_ajx/data_tags",
            dataType : 'json',
            cacheResults : true
        }
    });
</code>```

and this is my code to submit new data to json

```<code>        $(document).ready(function(){
           $(".save_new_tags").click(function(){
                var data = $('.add_new_tags').serialize();
                $.ajax({
                            type: 'POST',
                            url: "<?= base_url() ?>admin_ajx/tags_ajx/add_tags",
                            data: data,
                            success: function() {
                            $(".add_new_tags")[0].reset();
                            alert("Post Success!");
                            tagload.ajax.reload();
                        }
                    });
                });
            });
</code>```

how to load new data, after success submit new data

i thinks the problem is here
 cacheResults : true

i'am still looking for solution

答:
There is not AJAX property on the returned jQuery selection in tagload.

The example with cacheResults property set to true assumes that the backend is returning all possible results.

Since you're allowing for updates to the possible values, this isn't the situation any longer.

Removing cacheResults option or set it to false should have your tag suggestions updated.

You could also keep the cacheResults option set to true and update the suggestions on the Textext instance after fetching the tags using $.ajax.

```<code>var opts = {
  url: "<?= base_url() ?>admin_ajx/tags_ajx/data_tags",
  dataType : 'json',
  cacheResults : true
}

var tagload = $('#textarea')
    .textext({
      plugins : 'autocomplete filter tags ajax',
      ajax : opts
    });

$(document).ready(function(){
   $(".save_new_tags").click(function() {
     //...

      $.ajax(opts).done(function(suggestions) {
         var textExts = $('#textarea').textext()[0]
         textExts.ajax()._suggestions = suggestions
     });
  });
});
</code>```

Body:
i try to create tags form with textextjs
but i have a problem with ajax to call new data after another ajax success submit

this is my code to call json

var tagload =   $('#textarea')
    .textext({
        plugins : 'autocomplete filter tags ajax',
        ajax : {
            url: "<?= base_url() ?>admin_ajx/tags_ajx/data_tags",
            dataType : 'json',
            cacheResults : true
        }
    });

and this is my code to submit new data to json

        $(document).ready(function(){
           $(".save_new_tags").click(function(){
                var data = $('.add_new_tags').serialize();
                $.ajax({
                            type: 'POST',
                            url: "<?= base_url() ?>admin_ajx/tags_ajx/add_tags",
                            data: data,
                            success: function() {
                            $(".add_new_tags")[0].reset();
                            alert("Post Success!");
                            tagload.ajax.reload();
                        }
                    });
                });
            });

how to load new data, after success submit new data

i thinks the problem is here
 cacheResults : true

i'am still looking for solution

Body:
There is not AJAX property on the returned jQuery selection in tagload.

The example with cacheResults property set to true assumes that the backend is returning all possible results.

Since you're allowing for updates to the possible values, this isn't the situation any longer.

Removing cacheResults option or set it to false should have your tag suggestions updated.

You could also keep the cacheResults option set to true and update the suggestions on the Textext instance after fetching the tags using $.ajax.

var opts = {
  url: "<?= base_url() ?>admin_ajx/tags_ajx/data_tags",
  dataType : 'json',
  cacheResults : true
}

var tagload = $('#textarea')
    .textext({
      plugins : 'autocomplete filter tags ajax',
      ajax : opts
    });

$(document).ready(function(){
   $(".save_new_tags").click(function() {
     //...

      $.ajax(opts).done(function(suggestions) {
         var textExts = $('#textarea').textext()[0]
         textExts.ajax()._suggestions = suggestions
     });
  });
});


问:
Find next greater number with zeros in sql number
I'm looking for a way to find next greater number starting by 1 and followed by zeros in Microsoft SQL. Numbers could vary in digits. ie:

Query: 9856, Result after procedure: 10000
Query: 98999, Result after procedure: 100000

Thanks.

EDIT: There is no chance of having negative numbers. This is a calculation for a energy meter. For example, numbers can go up to 99999 or 999999 or 9999999. When energy overcome that number, it will start again at 0. So I can't read what energy has been used in that period. To know it, I need to calculate the number as asked, then perform some basic maths.

There is no need for knowing what is going on on 10, 100, etc, because of the nature of the operation. It will only be used when the above escenario happend.

答:
I don't know why you require or mathematically any other formula can be implemented. but technically that can be achieved as follows</p>

```<code>DECLARE @count INT
SET @count = 1000

DECLARE @result INT

SET @result = CASE WHEN @count%10 = 0 THEN @count ELSE CAST('1'+REPLICATE('0',LEN(@count)) AS INT) end

SELECT @result
</code>```

Body:
I don't know why you require or mathematically any other formula can be implemented. but technically that can be achieved as follows

DECLARE @count INT
SET @count = 1000

DECLARE @result INT

SET @result = CASE WHEN @count%10 = 0 THEN @count ELSE CAST('1'+REPLICATE('0',LEN(@count)) AS INT) end

SELECT @result


问:
Difference between dynamic arrays (GCC) and pointers
Considering following pieces of code:

```<code>void foo() {
    int arraySize = getMyComputedValue();
    int dynamicArray[arraySize];

    fillDynamicArray(&dynamicArray[0]);

    for (int i = 0; i < arraySize; i++) {
        // Do something with data
    }
}

void bar() {
    int arraySize = getMyComputedValue();
    int* dynamicArray = new int[arraySize];

    fillDynamicArray(dynamicArray);

    for (int i = 0; i < arraySize; i++) {
        // Do something with data
    }

    delete[] dynamicArray;
    dynamicArray = NULL;
}
</code>```

Both create a dynamic area in memory with varying lengths containing integers.
I've found that the first example foo() (at least in my build environment) only compiles with GCC.

What are the exact differences between the two? Is the first example merely a GNU extension which is shorthand for the bottom example, allowing the compiler to determine when the correct time for de-allocation is?
Or does the first example do exactly as the code says and allocates the memory on the stack?

答:
foo() allocates the memory on the stack, bar() allocates it on the heap. This has two effects: Lifetime (stack memory is automatically reclaimed at function exit), and max array size (stack space is rather limited to a range of a few MB at most, heap space is only limited by available RAM).

foo() is valid C99, but not C++ of any standard. C++ simply never embraced VLAs. This is the core point where you need to realize that C and C++ are two quite distinct languages. There are valid C programs that are not C++ (like foo()), and there are valid C++ programs that are not C (like bar()). C++ is not the strict superset anymore as which it started.

Nevertheless, compilers may choose to implement a superset of the language as an extension. g++ does so, but if you compile with strict C++ standard compliance (g++ -std=c++14 -pedantic -Werror), even g++ throws an error on foo().

Body:
Considering following pieces of code:

void foo() {
    int arraySize = getMyComputedValue();
    int dynamicArray[arraySize];

    fillDynamicArray(&dynamicArray[0]);

    for (int i = 0; i < arraySize; i++) {
        // Do something with data
    }
}

void bar() {
    int arraySize = getMyComputedValue();
    int* dynamicArray = new int[arraySize];

    fillDynamicArray(dynamicArray);

    for (int i = 0; i < arraySize; i++) {
        // Do something with data
    }

    delete[] dynamicArray;
    dynamicArray = NULL;
}

Both create a dynamic area in memory with varying lengths containing integers.
I've found that the first example foo() (at least in my build environment) only compiles with GCC.

What are the exact differences between the two? Is the first example merely a GNU extension which is shorthand for the bottom example, allowing the compiler to determine when the correct time for de-allocation is?
Or does the first example do exactly as the code says and allocates the memory on the stack?


问:
How to optimize code to write data that has more than 1,4 millions rows
i've got a text file that has 1,4 millions rows with delimiters

My goal is to write new file based on ID, so if in the data has 10 differents ID , it will create 10 new files and list the data based on the ID

I already finish my code , but my problem is, because the data has 1,4 million rows , it took so long to finish it and my PC can crash .

this is my code that i write

```<code>DateTime date = DateTime.Now;
            string tgl = date.Date.ToString("dd");
            string bln = date.Month.ToString("d2");
            string thn = date.Year.ToString();
            string tglskrg = thn + bln + tgl;
            System.IO.Directory.CreateDirectory("C:\\Users\\Desktop\\VA");
            System.IO.Directory.CreateDirectory("C:\\Users\\Desktop\\VA\\VA_" + tglskrg);

            string filename = "X:\\exampledata.txt";

            var lines = File.ReadAllLines(filename);

            //group by first value (ID)
            var groups = lines.Skip(1)
                  .Select(x => x.Split(';'))
                  .GroupBy(x => x[0]).ToArray();

            // iterate groups write the joined lines back to a new file with the key name
            foreach (var group in groups)
            {
                File.WriteAllLines(@"C:\\Users\\Desktop\\VA\\VA_" + tglskrg+"\\exampledata_" + group.Key +"_"+tglskrg + ".txt", new[] { "COMPANY CODE;CUSTOMER NUMBER;CUSTOMER NAME;INSERT DATE;TRANSACTION ID;TRANSACTION AMOUNT;ADMIN FEE;TRANSACTION REF;FLAG STATUS;TRANSACTION STATUS" }.Concat(group.Select(x => string.Join(";", x))));
            }

            foreach (var group in groups)
            {
                string path = @"C:\\Users\\Desktop\\VA\\VA_" + tglskrg + "\\exampledata_" + group.Key + "_" + tglskrg + ".txt";
                using (ZipFile zip = new ZipFile())
                {
                    zip.UseUnicodeAsNecessary = true;
                    zip.Password = group.Key + "VA#";
                    zip.AddFile(path, "VA_" + group.Key +"_"+tglskrg);
                    zip.Save(@"C:\Users\Desktop\exampledata_" + group.Key +"_"+tglskrg + ".zip_");
                }
            }
</code>```

Someone say to use StreamReader, but i really don't know how it works and i dont think it will be faster than what i use now

Maybe someone can help me optimize my code?

答:
Instead of reading the whole file into memory and then grouping, you should read each line separately and decide into which file it should go.

I omitted some of your file naming logic, to keep the example simple, but this it what it boils down to:

```<code>var writers = new Dictionary<string, TextWriter>();
const string header = "COMPANY CODE;CUSTOMER NUMBER;CUSTOMER NAME;INSERT DATE;TRANSACTION ID;TRANSACTION AMOUNT;ADMIN FEE;TRANSACTION REF;FLAG STATUS;TRANSACTION STATUS";
const string inputFile = "X:\\exampledata.txt";
const string outputPath = "C:\\Users\\Desktop\\VA\\";

using (var reader = File.OpenText(inputFile))
{
    // skip header
    reader.ReadLine();

    try
    {
        while (!reader.EndOfStream)
        {
            // read one line and separate key and value
            var line = reader.ReadLine();
            var separatorIndex = line.IndexOf(';');
            var id = line.Substring(0, separatorIndex);
            var value = line.Substring(separatorIndex + 1);

            // get a writer or create one
            if (!writers.TryGetValue(id, out var writer))
            {
                writer = File.CreateText($"{outputPath}{id}.txt");
                writer.WriteLine(header);
                writers.Add(id, writer);
            }

            // write the line to the correct file
            writer.WriteLine(value);
        }
    }
    finally
    {
        // dispose all the writers
        foreach (var writer in writers.Values)
        {
            writer.Dispose();
        }
    }
}
</code>```

Body:
i've got a text file that has 1,4 millions rows with delimiters

My goal is to write new file based on ID, so if in the data has 10 differents ID , it will create 10 new files and list the data based on the ID

I already finish my code , but my problem is, because the data has 1,4 million rows , it took so long to finish it and my PC can crash .

this is my code that i write

DateTime date = DateTime.Now;
            string tgl = date.Date.ToString("dd");
            string bln = date.Month.ToString("d2");
            string thn = date.Year.ToString();
            string tglskrg = thn + bln + tgl;
            System.IO.Directory.CreateDirectory("C:\\Users\\Desktop\\VA");
            System.IO.Directory.CreateDirectory("C:\\Users\\Desktop\\VA\\VA_" + tglskrg);

            string filename = "X:\\exampledata.txt";

            var lines = File.ReadAllLines(filename);

            //group by first value (ID)
            var groups = lines.Skip(1)
                  .Select(x => x.Split(';'))
                  .GroupBy(x => x[0]).ToArray();

            // iterate groups write the joined lines back to a new file with the key name
            foreach (var group in groups)
            {
                File.WriteAllLines(@"C:\\Users\\Desktop\\VA\\VA_" + tglskrg+"\\exampledata_" + group.Key +"_"+tglskrg + ".txt", new[] { "COMPANY CODE;CUSTOMER NUMBER;CUSTOMER NAME;INSERT DATE;TRANSACTION ID;TRANSACTION AMOUNT;ADMIN FEE;TRANSACTION REF;FLAG STATUS;TRANSACTION STATUS" }.Concat(group.Select(x => string.Join(";", x))));
            }

            foreach (var group in groups)
            {
                string path = @"C:\\Users\\Desktop\\VA\\VA_" + tglskrg + "\\exampledata_" + group.Key + "_" + tglskrg + ".txt";
                using (ZipFile zip = new ZipFile())
                {
                    zip.UseUnicodeAsNecessary = true;
                    zip.Password = group.Key + "VA#";
                    zip.AddFile(path, "VA_" + group.Key +"_"+tglskrg);
                    zip.Save(@"C:\Users\Desktop\exampledata_" + group.Key +"_"+tglskrg + ".zip_");
                }
            }

Someone say to use StreamReader, but i really don't know how it works and i dont think it will be faster than what i use now

Maybe someone can help me optimize my code?

Body:
Instead of reading the whole file into memory and then grouping, you should read each line separately and decide into which file it should go.

I omitted some of your file naming logic, to keep the example simple, but this it what it boils down to:

var writers = new Dictionary<string, TextWriter>();
const string header = "COMPANY CODE;CUSTOMER NUMBER;CUSTOMER NAME;INSERT DATE;TRANSACTION ID;TRANSACTION AMOUNT;ADMIN FEE;TRANSACTION REF;FLAG STATUS;TRANSACTION STATUS";
const string inputFile = "X:\\exampledata.txt";
const string outputPath = "C:\\Users\\Desktop\\VA\\";

using (var reader = File.OpenText(inputFile))
{
    // skip header
    reader.ReadLine();

    try
    {
        while (!reader.EndOfStream)
        {
            // read one line and separate key and value
            var line = reader.ReadLine();
            var separatorIndex = line.IndexOf(';');
            var id = line.Substring(0, separatorIndex);
            var value = line.Substring(separatorIndex + 1);

            // get a writer or create one
            if (!writers.TryGetValue(id, out var writer))
            {
                writer = File.CreateText($"{outputPath}{id}.txt");
                writer.WriteLine(header);
                writers.Add(id, writer);
            }

            // write the line to the correct file
            writer.WriteLine(value);
        }
    }
    finally
    {
        // dispose all the writers
        foreach (var writer in writers.Values)
        {
            writer.Dispose();
        }
    }
}


问:
need result of two table sql query
I have a two sql server tables that contains data like this

Table a

```<code>catId    |    catname          | Isdeleted
-------------------------------------------------

1               ABC               0
2               DEF               0
3               GHI               0
</code>```

and another table is

Table B

```<code>id    |     Name    |    Name1      | Catid
--------------------------------------------------
1           abc           aaaa           1
2           def           bbbb           1
3           ghi           gggg           2
4           jkl           jjjj           2
5           xyz           xxxxx          3
</code>```

Now I want result in this format

catname from table a and all the fields from table b according to
  catid of table a and   catname should be distinct.

Please help me

答:
Write your query like this :

```<code>SELECT DISTINCT a.catname, b.* FROM a INNER JOIN b
ON a.catid = b.catid WHERE catid = [catid]
</code>```

If you have multiple records in table b for each catid or catname, you will see multiple records with same catname in result. there is no other choice unless catname be unique in both tables a and b.

Title: need result of two table sql query

Body:
I have a two sql server tables that contains data like this

Table a

catId    |    catname          | Isdeleted
-------------------------------------------------

1               ABC               0
2               DEF               0
3               GHI               0

and another table is

Table B

id    |     Name    |    Name1      | Catid
--------------------------------------------------
1           abc           aaaa           1
2           def           bbbb           1
3           ghi           gggg           2
4           jkl           jjjj           2
5           xyz           xxxxx          3

Now I want result in this format

catname from table a and all the fields from table b according to
  catid of table a and   catname should be distinct.

Please help me

Body:
Write your query like this :

SELECT DISTINCT a.catname, b.* FROM a INNER JOIN b
ON a.catid = b.catid WHERE catid = [catid]

If you have multiple records in table b for each catid or catname, you will see multiple records with same catname in result. there is no other choice unless catname be unique in both tables a and b.


问:
No log4j2 configuration file found. Using default configuration: logging only errors to the console
```<code>$ java -Dlog4j.configuration=file:///path/to/your/log4j2.xml -jar /path/to/your/jar_file.jar
</code>```

Written to the console, you get

```<code>ERROR StatusLogger No log4j2 configuration file found. Using default configuration: logging only errors to the console.
</code>```

But, it also looks like the configuration file has been found and was not parsable:

```<code>    log4j:WARN Continuable parsing error 2 and column 31
    log4j:WARN Document root element "Configuration", must match DOCTYPE root "null".
    log4j:WARN Continuable parsing error 2 and column 31
    log4j:WARN Document is invalid: no grammar found.
    log4j:ERROR DOM element is - not a <log4j:configuration> element.
    log4j:WARN No appenders could be found for logger (kafka.utils.VerifiableProperties).
    log4j:WARN Please initialize the log4j system properly.
    log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
</code>```

答:
This sometimes can be thrown before the actual log4j2 configuration file found on the web servlet. at least for my case I think so. Cuz I already have in my web.xml

```<code>  <context-param>
    <param-name>log4jConfiguration</param-name>
    <param-value>classpath:log4j2-app.xml</param-value>
  </context-param>
</code>```

and checking the log4j-web source;
in class

```<code>org.apache.logging.log4j.web.Log4jWebInitializerImpl
</code>```

there is the line;

```<code>String location = this.substitutor
                 .replace(this.servletContext.getInitParameter("log4jConfiguration"));
</code>```

all those makes me think that this is temporary log before configuration found.

Body:
$ java -Dlog4j.configuration=file:///path/to/your/log4j2.xml -jar /path/to/your/jar_file.jar

Written to the console, you get

ERROR StatusLogger No log4j2 configuration file found. Using default configuration: logging only errors to the console.

But, it also looks like the configuration file has been found and was not parsable:

    log4j:WARN Continuable parsing error 2 and column 31
    log4j:WARN Document root element "Configuration", must match DOCTYPE root "null".
    log4j:WARN Continuable parsing error 2 and column 31
    log4j:WARN Document is invalid: no grammar found.
    log4j:ERROR DOM element is - not a <log4j:configuration> element.
    log4j:WARN No appenders could be found for logger (kafka.utils.VerifiableProperties).
    log4j:WARN Please initialize the log4j system properly.
    log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.

Body:
This sometimes can be thrown before the actual log4j2 configuration file found on the web servlet. at least for my case I think so. Cuz I already have in my web.xml

  <context-param>
    <param-name>log4jConfiguration</param-name>
    <param-value>classpath:log4j2-app.xml</param-value>
  </context-param>

and checking the log4j-web source;
in class

org.apache.logging.log4j.web.Log4jWebInitializerImpl

there is the line;

String location = this.substitutor
                 .replace(this.servletContext.getInitParameter("log4jConfiguration"));

all those makes me think that this is temporary log before configuration found.


问:
What is the best way to code up a Month and Year drop down list for ASP.NET?
I have an internal application that I needs to have a drop down list for two date type elements:  Month and Year.  These values are not in a database or other repository of information.

I know I could just setup a list with the values I need by adding them to a dictionary like object (I need to correlate the Month to the numerical representation, January => 01):

```<code>var months = new Dictionary<String,String>();
months.Add("01", "January");
...
</code>```

The drop down list for the year will be a bit easier as I can just choose a starting year and iterate up to the current or current+1 year in a generic list.

Is there a better way to handle these data elements?  Something built in, or a good design pattern that I should be implementing?

答:
/Try this code to bind all month in dropdown list without using database/

```<code> public void GetMonthList(DropDownList ddl)
    {
        DateTime month = Convert.ToDateTime("1/1/2000");
        for (int i = 0; i < 12; i++)
        {
            DateTime NextMont = month.AddMonths(i);
            ListItem list = new ListItem();
            list.Text = NextMont.ToString("MMMM");
            list.Value = NextMont.Month.ToString();
            ddl.Items.Add(list);
        }
        //ddl.Items.Insert(0, "Select Month");
        ddl.Items.FindByValue(DateTime.Now.Month.ToString()).Selected = true;
    }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have an internal application that I needs to have a drop down list for two date type elements:  Month and Year.  These values are not in a database or other repository of information.

I know I could just setup a list with the values I need by adding them to a dictionary like object (I need to correlate the Month to the numerical representation, January => 01):

var months = new Dictionary<String,String>();
months.Add("01", "January");
...

The drop down list for the year will be a bit easier as I can just choose a starting year and iterate up to the current or current+1 year in a generic list.

Is there a better way to handle these data elements?  Something built in, or a good design pattern that I should be implementing?

Body:
/Try this code to bind all month in dropdown list without using database/

 public void GetMonthList(DropDownList ddl)
    {
        DateTime month = Convert.ToDateTime("1/1/2000");
        for (int i = 0; i < 12; i++)
        {
            DateTime NextMont = month.AddMonths(i);
            ListItem list = new ListItem();
            list.Text = NextMont.ToString("MMMM");
            list.Value = NextMont.Month.ToString();
            ddl.Items.Add(list);
        }
        //ddl.Items.Insert(0, "Select Month");
        ddl.Items.FindByValue(DateTime.Now.Month.ToString()).Selected = true;
    }


问:
How do you run a python file from another python file?
Im trying to run another file from my tkinter login system but i cant find the way to do it

Ive tried import file

```<code>if (p == '123') and (u == 'test'):
    import correct
</code>```

Im trying to run the file when those are true

答:
If you want to run a file separately without importing it do this.

from os import system
#system calls a command from terminal
system("python <path to python file>")
```

Body:
Im trying to run another file from my tkinter login system but i cant find the way to do it

Ive tried import file

if (p == '123') and (u == 'test'):
    import correct

Im trying to run the file when those are true


问:
Autocomplete search
hi every one i need simple auto suggest code i have tried with  jquery.autocomplete.js am not getting what i need to do
code :- index.jsp

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 "http://www.w3.org/TR/html4/loose.dtd">

 <html>

 <head>

     <link rel="stylesheet" type="text/css" href="style.css" />

     <script type="text/javascript" src="jquery-1.3.2.min.js"></script>

     <script type="text/javascript" src="jquery.autocomplete.js"></script>

 </head>

 <body>

     <div style="width: 300px; margin: 50px auto;">

         <b>Country</b>   : <input type="text" id="country" name="country" class="input_text"/>

     </div>

 </body>

 <script>

     jQuery(function(){

         $("#country").autocomplete("list.jsp");

     });

 </script>

 </html>

and list.jsp
<%@page import="java.util.Iterator"%>

 <%@page import="java.util.List"%>

 <%@page import="java.util.ArrayList"%>

 <%

    String countries[] = {

                             "Afghanistan",

                            "Albania",

                             "Algeria",

                            "Andorra",

                             "Angola",

                             "Antigua and Barbuda",

                             "Argentina",

                             "Armenia",

                             "Yemen",

                             "Zambia",

                             "Zimbabwe"

                             };

     String query = (String)request.getParameter("q");

     System.out.println("1"+request.getParameterNames().nextElement());

     response.setHeader("Content-Type", "text/html");

     int cnt=1;

     for(int i=0;i<countries.length;i++)

     {

         if(countries[i].toUpperCase().startsWith(query.toUpperCase()))

        {

            out.print(countries[i]+"\n");

             if(cnt>=10)
                break;

             cnt++;

         }

     }

 %>
</code>```

there is one more style.css is there but it is not showing anything while execution
note all source file is present in same folder please tell me where am lacking

答:
According the documentation of autocomplete, you need a javascript json object. This is a container for all your data. I miss this container in your source code which you have posted.

If you click on Demos of utocomplete, scroll to the end of this page. I think the last demo represents what you look for.

Title: Autocomplete search

Body:
hi every one i need simple auto suggest code i have tried with  jquery.autocomplete.js am not getting what i need to do
code :- index.jsp

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 "http://www.w3.org/TR/html4/loose.dtd">

     <link rel="stylesheet" type="text/css" href="style.css" />

         Country   : <input type="text" id="country" name="country" class="input_text"/>

and list.jsp
<%@page import="java.util.Iterator"%>

 <%@page import="java.util.List"%>

 <%@page import="java.util.ArrayList"%>

 <%

    String countries[] = {

                             "Afghanistan",

                            "Albania",

                             "Algeria",

                            "Andorra",

                             "Angola",

                             "Antigua and Barbuda",

                             "Argentina",

                             "Armenia",

                             "Yemen",

                             "Zambia",

                             "Zimbabwe"

                             };

     String query = (String)request.getParameter("q");

     System.out.println("1"+request.getParameterNames().nextElement());

     response.setHeader("Content-Type", "text/html");

     int cnt=1;

     for(int i=0;i<countries.length;i++)

     {

         if(countries[i].toUpperCase().startsWith(query.toUpperCase()))

        {

            out.print(countries[i]+"\n");

             if(cnt>=10)
                break;

             cnt++;

         }

     }

 %>

there is one more style.css is there but it is not showing anything while execution
note all source file is present in same folder please tell me where am lacking


问:
Azure DevOps build pipeline for Angular and Failed to exec build script Node error
I am working with Azure DevOps CI/CD for Angular 7 project but it is failing with following at the time of building angular code:

Error: Npm failed with return code: 1

Going through the pipeline task log I found that Node is exiting with following error:

2019-05-27T06:57:25.6984762Z npm verb lifecycle fuse@7.1.0~build: CWD: D:\a\1\s\Client
  2019-05-27T06:57:25.6984945Z npm info lifecycle fuse@7.1.0~build: Failed to exec build script
  2019-05-27T06:57:25.6985117Z npm verb stack Error: fuse@7.1.0 build: node --max_old_space_size=6144 ./node_modules/@angular/cli/bin/ng build --dev "--prod"
  2019-05-27T06:57:25.6985258Z npm verb stack Exit status 1
  2019-05-27T06:57:25.6985401Z npm verb stack     at EventEmitter. (C:\npm\prefix\node_modules\npm\node_modules\npm-lifecycle\index.js:301:16)
  2019-05-27T06:57:25.6985577Z npm verb stack     at EventEmitter.emit (events.js:189:13)
  2019-05-27T06:57:25.6985721Z npm verb stack     at ChildProcess. (C:\npm\prefix\node_modules\npm\node_modules\npm-lifecycle\lib\spawn.js:55:14)
  2019-05-27T06:57:25.6986143Z npm verb stack     at ChildProcess.emit (events.js:189:13)
  2019-05-27T06:57:25.6986311Z npm verb stack     at maybeClose (internal/child_process.js:970:16)
  2019-05-27T06:57:25.6986453Z npm verb stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:259:5)
  2019-05-27T06:57:25.6986609Z npm verb pkgid fuse@7.1.0
  2019-05-27T06:57:25.6986743Z npm verb cwd D:\a\1\s\Client
  2019-05-27T06:57:25.6986877Z npm verb Windows_NT 10.0.14393
  2019-05-27T06:57:25.6987017Z npm verb argv "C:\Program Files\nodejs\node.exe" "C:\npm\prefix\node_modules\npm\bin\npm-cli.js" "run" "build" "--" "--prod"
  2019-05-27T06:57:25.6987169Z npm verb node v10.15.3
  2019-05-27T06:57:25.6987304Z npm verb npm  v6.9.0
  2019-05-27T06:57:25.6987435Z npm ERR! code ELIFECYCLE
  2019-05-27T06:57:25.6987584Z npm ERR! errno 1
  2019-05-27T06:57:25.6987890Z npm ERR! fuse@7.1.0 build: node --max_old_space_size=6144 ./node_modules/@angular/cli/bin/ng build --dev "--prod"
  2019-05-27T06:57:25.6988173Z npm ERR! Exit status 1

I tried looking through different threads based upon error keywords but have not found a fix yet. Please note that everything works fine in the development environment.

I am not allowed to attach file or image so I am pasting pipeline YAML here:

trigger:
- master

pool:
  vmImage: 'vs2017-win2016'

steps:
- task: Npm@1
  displayName: 'npm install'
  inputs:
    command: install
    workingDir: Client

- task: Npm@1
  displayName: 'Build Angular'
  inputs:
    command: custom
    customCommand: run build -- --prod
    workingDir: Client

- task: PublishPipelineArtifact@0
  inputs:
    artifactName: 'angular'
    targetPath: 'Client/dist'```

Please help.

答:
I was able to get it working after discussion with Microsoft support guys. Here is direct link to solution

Thanks for your support!

Body:
I am working with Azure DevOps CI/CD for Angular 7 project but it is failing with following at the time of building angular code:

Error: Npm failed with return code: 1

Going through the pipeline task log I found that Node is exiting with following error:

2019-05-27T06:57:25.6984762Z npm verb lifecycle fuse@7.1.0~build: CWD: D:\a\1\s\Client
  2019-05-27T06:57:25.6984945Z npm info lifecycle fuse@7.1.0~build: Failed to exec build script
  2019-05-27T06:57:25.6985117Z npm verb stack Error: fuse@7.1.0 build: node --max_old_space_size=6144 ./node_modules/@angular/cli/bin/ng build --dev "--prod"
  2019-05-27T06:57:25.6985258Z npm verb stack Exit status 1
  2019-05-27T06:57:25.6985401Z npm verb stack     at EventEmitter. (C:\npm\prefix\node_modules\npm\node_modules\npm-lifecycle\index.js:301:16)
  2019-05-27T06:57:25.6985577Z npm verb stack     at EventEmitter.emit (events.js:189:13)
  2019-05-27T06:57:25.6985721Z npm verb stack     at ChildProcess. (C:\npm\prefix\node_modules\npm\node_modules\npm-lifecycle\lib\spawn.js:55:14)
  2019-05-27T06:57:25.6986143Z npm verb stack     at ChildProcess.emit (events.js:189:13)
  2019-05-27T06:57:25.6986311Z npm verb stack     at maybeClose (internal/child_process.js:970:16)
  2019-05-27T06:57:25.6986453Z npm verb stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:259:5)
  2019-05-27T06:57:25.6986609Z npm verb pkgid fuse@7.1.0
  2019-05-27T06:57:25.6986743Z npm verb cwd D:\a\1\s\Client
  2019-05-27T06:57:25.6986877Z npm verb Windows_NT 10.0.14393
  2019-05-27T06:57:25.6987017Z npm verb argv "C:\Program Files\nodejs\node.exe" "C:\npm\prefix\node_modules\npm\bin\npm-cli.js" "run" "build" "--" "--prod"
  2019-05-27T06:57:25.6987169Z npm verb node v10.15.3
  2019-05-27T06:57:25.6987304Z npm verb npm  v6.9.0
  2019-05-27T06:57:25.6987435Z npm ERR! code ELIFECYCLE
  2019-05-27T06:57:25.6987584Z npm ERR! errno 1
  2019-05-27T06:57:25.6987890Z npm ERR! fuse@7.1.0 build: node --max_old_space_size=6144 ./node_modules/@angular/cli/bin/ng build --dev "--prod"
  2019-05-27T06:57:25.6988173Z npm ERR! Exit status 1

I tried looking through different threads based upon error keywords but have not found a fix yet. Please note that everything works fine in the development environment.

I am not allowed to attach file or image so I am pasting pipeline YAML here:

trigger:
- master

pool:
  vmImage: 'vs2017-win2016'

steps:
- task: Npm@1
  displayName: 'npm install'
  inputs:
    command: install
    workingDir: Client

- task: Npm@1
  displayName: 'Build Angular'
  inputs:
    command: custom
    customCommand: run build -- --prod
    workingDir: Client

- task: PublishPipelineArtifact@0
  inputs:
    artifactName: 'angular'
    targetPath: 'Client/dist'

Please help.


问:
Display MySQL count query result in a HTML table in php
How to Display MySQL COUNT() query results in an HTML table in php.

I used the following queries:

```<code>select name, count(*) from contacts group by 1 having count(*) > 1;
</code>```

答:
Follow this example:</p>

```<code><?php

$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "select name, count(*) as total from contacts group by 1 having count(*) > 1";
$result = $conn->query($sql);

if ($result->num_rows > 0) { ?>

<table style="width:100%">
  <tr>
    <th>Name</th>
    <th>Total</th>
  </tr>
  <?php while($row = $result->fetch_assoc()) { ?>
  <tr>
    <td><?=$row['name'];?></td>
    <td><?=$row['total'];?></td>
  </tr>
  <?php } ?>
</table>

<?php } else { echo "0 results"; } ?>
</code>```

Body:
How to Display MySQL COUNT() query results in an HTML table in php.

I used the following queries:

select name, count(*) from contacts group by 1 having count(*) > 1;

Body:
Follow this example:

<?php

$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "select name, count(*) as total from contacts group by 1 having count(*) > 1";
$result = $conn->query($sql);

if ($result->num_rows > 0) { ?>

<table style="width:100%">
  <tr>
    <th>Name</th>
    <th>Total</th>
  </tr>
  <?php while($row = $result->fetch_assoc()) { ?>
  <tr>
    <td><?=$row['name'];?></td>
    <td><?=$row['total'];?></td>
  </tr>
  <?php } ?>
</table>

<?php } else { echo "0 results"; } ?>


问:
Delete specific Text in NSMutableAttributedString
I have this function which inserts a NSTextAttachment into a UITextView. After it is inserted I am wanting to delete a specific bit of text before it updates the textView with the new NSMutableAttributedString. Is there a NSMutableAttributedString function to replace text?

```<code>// Create Attachment
    let attachment = NSTextAttachment()
    attachment.image = image
    attachment.bounds = CGRect(origin: .zero, size: image.size)

// Current Attributed String
    var atStr = NSMutableAttributedString(attributedString: textView.attributedText)

// Insert Attachment
    let attachmentAtStr = NSAttributedString(attachment: attachment)
    if let selectedRange = textView.selectedTextRange {
        let cursorIndex = textView.offset(from: textView.beginningOfDocument, to: selectedRange.start)
        atStr.insert(attachmentAtStr, at: cursorIndex)
        atStr.addAttributes(self.textView.typingAttributes, range: NSRange(location: cursorIndex, length: 1))
    } else {
        atStr.append(attachmentAtStr)
    }

// Delete Specific Text (ERROR: Value of type 'NSMutableAttributedString' has no member 'replacingOccurrences')
    atStr = atStr.replacingOccurrences(of: "text to replace", with: "replacement", options: [.caseInsensitive, .regularExpression])

    textView.attributedText = atStr
</code>```

答: You need to call replaceCharacters(in:with:), which takes an NSRange and a substitute string. You will clearly need to determine the range first, but that's easy.

Body:
I have this function which inserts a NSTextAttachment into a UITextView. After it is inserted I am wanting to delete a specific bit of text before it updates the textView with the new NSMutableAttributedString. Is there a NSMutableAttributedString function to replace text?

// Create Attachment
    let attachment = NSTextAttachment()
    attachment.image = image
    attachment.bounds = CGRect(origin: .zero, size: image.size)

// Current Attributed String
    var atStr = NSMutableAttributedString(attributedString: textView.attributedText)

// Insert Attachment
    let attachmentAtStr = NSAttributedString(attachment: attachment)
    if let selectedRange = textView.selectedTextRange {
        let cursorIndex = textView.offset(from: textView.beginningOfDocument, to: selectedRange.start)
        atStr.insert(attachmentAtStr, at: cursorIndex)
        atStr.addAttributes(self.textView.typingAttributes, range: NSRange(location: cursorIndex, length: 1))
    } else {
        atStr.append(attachmentAtStr)
    }

// Delete Specific Text (ERROR: Value of type 'NSMutableAttributedString' has no member 'replacingOccurrences')
    atStr = atStr.replacingOccurrences(of: "text to replace", with: "replacement", options: [.caseInsensitive, .regularExpression])

    textView.attributedText = atStr


问:
How to create a FOR where every 10 correct questions raise a level
I have to find the method where every 10 correct questions raise 1 level and so on.

void updateScoreAndLevel(int answerGiven){

```<code>    if(isCorrect(answerGiven)) {
        for (int i = 1; i <= currentLevel; i = i + 100) {
            currentScore = currentScore + 100;
        }
        for (int i = 10; i <= currentScore; i++) {
            currentLevel = currentLevel + i;
        }

    }else{
        currentScore = currentScore - 50;
        currentLevel = currentLevel ;
    }
</code>```

I hope that every 10 correct questions go up one level but it does not give me

答:
Here is a longer example of what I meant in my comment (Sorry if my syntax is off, but I haven't written Java in years):</p>

```<code>// Defines global variables (including parallel arrays of questions/answers)
String[] questions = {"1", "2", "3", "4", "5", "6", "7", "8", "9"};
String[] answers = {"a", "b", "c", "d", "e", "f", "g", "h", "i"};
int score = 0;
int level = 1;
int counter = 0;

// Loops through all questions
for(int i = 0; i < questions.length; i++){
  String nextQuestion = questions[i];

  // (You should show nextQuestion to the user and get their answer here...)
  // (Eg: https://www.mkyong.com/android/android-prompt-user-input-dialog-example/)
  String answer = answers[i]; // This demo assumes that the user answers correctly

  // Checks if answer is correct, and updates variables accordingly
  if(answer == answers[i]){
    // Correct answer increases score and counter (and sometimes level)
    score = score + 100;
    counter = counter + 1;
    // After 3 correct answers, changes level and resets counter
    if(counter == 3){
      level = level + 1;
      counter = 0;
    }
  }
  else{
    // Incorrect answer decreases score
    score = score - 50;
  }
}
</code>```

Body:
I have to find the method where every 10 correct questions raise 1 level and so on.

void updateScoreAndLevel(int answerGiven){

    if(isCorrect(answerGiven)) {
        for (int i = 1; i <= currentLevel; i = i + 100) {
            currentScore = currentScore + 100;
        }
        for (int i = 10; i <= currentScore; i++) {
            currentLevel = currentLevel + i;
        }

    }else{
        currentScore = currentScore - 50;
        currentLevel = currentLevel ;
    }

I hope that every 10 correct questions go up one level but it does not give me

Body:
Here is a longer example of what I meant in my comment (Sorry if my syntax is off, but I haven't written Java in years):

// Defines global variables (including parallel arrays of questions/answers)
String[] questions = {"1", "2", "3", "4", "5", "6", "7", "8", "9"};
String[] answers = {"a", "b", "c", "d", "e", "f", "g", "h", "i"};
int score = 0;
int level = 1;
int counter = 0;

// Loops through all questions
for(int i = 0; i < questions.length; i++){
  String nextQuestion = questions[i];

  // (You should show nextQuestion to the user and get their answer here...)
  // (Eg: https://www.mkyong.com/android/android-prompt-user-input-dialog-example/)
  String answer = answers[i]; // This demo assumes that the user answers correctly

  // Checks if answer is correct, and updates variables accordingly
  if(answer == answers[i]){
    // Correct answer increases score and counter (and sometimes level)
    score = score + 100;
    counter = counter + 1;
    // After 3 correct answers, changes level and resets counter
    if(counter == 3){
      level = level + 1;
      counter = 0;
    }
  }
  else{
    // Incorrect answer decreases score
    score = score - 50;
  }
}


问:
"Premature end of file" error when Java read and writes XML data files
I have been using JDOM library to read and write XML files through Java Servlets.

Problem is that when I send many requests using AJAX to my servlets which read and write data in XML files, many times it fails displaying error: Premature end of file. How can I synchronize all these read/writes to files or is there any other way to prevent these problem? Let me know if more details are required.

Will use of threads do any good in this situation?

Thanks a lot!

答:
I have faced such type of problem but exactly not the same. I am sharing my experience about this error. Please, sorry for any inconvenience.

I have faced the following problem

I have to form a xml file with dynamic variable data. And post that xml to a URL by PostMethod in java.

Normally It works. But when dynamic variable data is null. Then it shows the  “Premature end of file".

Solution:

Just checking the variable is null or not. And it works for me.


问:
Pull most frequent combination of 2 columns from panda dataframe by count
I am relatively new to Python programming.. I have a dataframe, df - from which i need to pull a combination of 2 columns that has most number of occurences

I followed the below thought process
- Did a grouping of dataframe by the requested 2 columns
- Performed a count of rows (hence used axis = 0)that belong to each of those groupings
- Based on the count of rows pulled for each unique group/combination, i tried to sort those rows

Code below

```<code>output = df.groupby(['column1','column2']).count().sort_values(by=['column1','column2'], axis = 0)[0]

Getting some error like this:
in get_loc return self._engine.get_loc(key)

resulting into this exception:
in get_loc return self._engine.get_loc(self._maybe_cast_indexer(key))
</code>```

Appreciate any help here

答:
Your error is being caused by the [0] at the end of your line where you do the groupby. You didn't post the full error message, but I would bet you have a KeyError: 0.  That is due to you no longer having a 0 in your index. If you take a look at the DataFrame created after the groupby you'll see that you now have a hierarchical index, created from the unique value combinations of column1 and column2.

The quick solution? Replace [0] with .iloc[0] to get the row in the zero-index-location.

```<code>output = df.groupby(['column1','column2']).count().sort_values(by=['column1','column2'], axis = 0).iloc[0]
</code>```

Or use .head(1), to get the top row of the DataFrame.

Body:
I am relatively new to Python programming.. I have a dataframe, df - from which i need to pull a combination of 2 columns that has most number of occurences

I followed the below thought process
- Did a grouping of dataframe by the requested 2 columns
- Performed a count of rows (hence used axis = 0)that belong to each of those groupings
- Based on the count of rows pulled for each unique group/combination, i tried to sort those rows

Code below

output = df.groupby(['column1','column2']).count().sort_values(by=['column1','column2'], axis = 0)[0]

Getting some error like this:
in get_loc return self._engine.get_loc(key)

resulting into this exception:
in get_loc return self._engine.get_loc(self._maybe_cast_indexer(key))

Appreciate any help here

Body:
Your error is being caused by the [0] at the end of your line where you do the groupby. You didn't post the full error message, but I would bet you have a KeyError: 0.  That is due to you no longer having a 0 in your index. If you take a look at the DataFrame created after the groupby you'll see that you now have a hierarchical index, created from the unique value combinations of column1 and column2.

The quick solution? Replace [0] with .iloc[0] to get the row in the zero-index-location.

output = df.groupby(['column1','column2']).count().sort_values(by=['column1','column2'], axis = 0).iloc[0]

Or use .head(1), to get the top row of the DataFrame.


问:
XPath not locating element
What is wrong with my path to select the following:

```<code><label class="form-control-label" for="profile_form_state">State</label>
</code>```

Xpath:

```<code>xpath = '//label[ends-with(@for, "_state")]'
</code>```

I am using rspec and capybara

```<code> expect(rendered).to have_xpath(xpath)
</code>```

Error:

```<code>   xmlXPathCompOpEval: function ends-with not found
</code>```

答:
Looks like your XPath processor only supports XPath, 1.0 while ends-with is defined in XPath 2.0 and above. But you can simulate ends-with() in XPath 1.0 using substring() and string-length() :

```<code>xpath = '//label["_state" = substring(@for, string-length(@for) - string-length("_state") +1)]'
</code>```

You can shorten the expression a bit by replacing string-length("_state") +1 with pre-calculated value 5 (length of the word _state minus one) :

```<code>xpath = '//label["_state" = substring(@for, string-length(@for) - 5)]'
</code>```

Title: XPath not locating element

Body:
What is wrong with my path to select the following:

State

Xpath:

xpath = '//label[ends-with(@for, "_state")]'

I am using rspec and capybara

 expect(rendered).to have_xpath(xpath)

Error:

   xmlXPathCompOpEval: function ends-with not found

Body:
Looks like your XPath processor only supports XPath, 1.0 while ends-with is defined in XPath 2.0 and above. But you can simulate ends-with() in XPath 1.0 using substring() and string-length() :

xpath = '//label["_state" = substring(@for, string-length(@for) - string-length("_state") +1)]'

You can shorten the expression a bit by replacing string-length("_state") +1 with pre-calculated value 5 (length of the word _state minus one) :

xpath = '//label["_state" = substring(@for, string-length(@for) - 5)]'


问:
How to create a publicly visible, provably random seed ahead of time? (Verifiable random number)
Imagine that you are hosting a debate with n participants and you wish to split them in half in a completely random fashion.

One might do so by creating a list of participants, randomly shuffling that list, then forcing the first n/2 participants to debate as a team.

If this debate was particularly important, however, we would want to ensure that the teams we have created are provably random in a way that is publicly visible. We want to be able to show that the teams we have created are not the direct result of any human's decisions. Would there be a way to do this?

I believe this problem boils down to the issue of creating a seed for a random number generator that is based on the state of the world at a particular time, but I'm not sure. Is this a problem software engineers have tackled before, and is there an API out there for this?

答:
What you may be thinking of is verifiable random numbers, which are random numbers generated using data that will be disclosed along with all the information needed to verify them. The most prolific use of verifiable random numbers in practice I am aware of is found in the selection procedure for the Internet Engineering Task Force's Nominations Committee (or NomCom for short). RFC 3797 describes this selection procedure, as well as how verifiable random selection works in general.

Another related technology is the verifiable delay function, which is a function that takes noticeable time to compute (for example, to hash publicly disclosed data to a random-looking number) but for which it's easy to verify whether the output is correct. This is described in two works, among others:

Lenstra, A.K., Wesolowski, B. "A random zoo: sloth, unicorn, and trx", 2015 (before the concept was coined).

Boneh, D., Bonneau, J., et al. "Verifiable Delay Functions", 2018.


问:
Pattern for interruptible loops using actors
I'm designing an actor that consumes items from an endless stream, and need a way to control when it starts and stops using messages.  Is there a common pattern for implementing interruptible loops like this with actors?  I was thinking of just having my actor send messages to itself.  Something like (pseudo Scala):

```<code>class Interruptible extends Actor {
  val stream: Stream
  val running: boolean

  def receive = {
    case "start" => {
      running = true
      consumeItem
    }

    case "stop" => {
      running = false
    }

    case "consumeNext" => consumeItem
  }

  def consumeItem {
    if (running) {
      stream.getItem
      this ! "consumeNext"
    }
  }
}
</code>```

Is this the best way to go about things?

Thanks!

答:
Perhaps encoded like this:

```<code>class Interruptible extends Actor {
  val stream: Stream

  def inactive: Receive = { // This is the behavior when inactive
    case "start" =>
      self become active
  }

  def active: Receive = { // This is the behavior when it's active
    case "stop" =>
      self become inactive
    case "next" =>
      doSomethingWith(stream.getItem)
      self ! "next"
  }

  def receive = inactive // Start out as inactive
}
</code>```

Cheers,

Body:
I'm designing an actor that consumes items from an endless stream, and need a way to control when it starts and stops using messages.  Is there a common pattern for implementing interruptible loops like this with actors?  I was thinking of just having my actor send messages to itself.  Something like (pseudo Scala):

class Interruptible extends Actor {
  val stream: Stream
  val running: boolean

  def receive = {
    case "start" => {
      running = true
      consumeItem
    }

    case "stop" => {
      running = false
    }

    case "consumeNext" => consumeItem
  }

  def consumeItem {
    if (running) {
      stream.getItem
      this ! "consumeNext"
    }
  }
}

Is this the best way to go about things?

Thanks!

Body:
Perhaps encoded like this:

class Interruptible extends Actor {
  val stream: Stream

  def inactive: Receive = { // This is the behavior when inactive
    case "start" =>
      self become active
  }

  def active: Receive = { // This is the behavior when it's active
    case "stop" =>
      self become inactive
    case "next" =>
      doSomethingWith(stream.getItem)
      self ! "next"
  }

  def receive = inactive // Start out as inactive
}

Cheers,


问:
Fetching JSON response from web not working
I am trying to fetch a json. While the code used to work I changed it a little and now it doesn't work. The code is supposed to exchange money.

```<code>            sendjsonrequest();
            assert tv != null;

            //Request a string response from the URL resource
            StringRequest stringRequest = new StringRequest(Request.Method.GET, "https://free.currencyconverterapi.com/api/v6/convert?q=EUR_ILS&compact=ultra&apiKey=6f4b50fae0c5c91a84bd",
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            // Display the response string.
                            tv.setText("Response is: " + Float.parseFloat(response) * Float.parseFloat(et1.getText().toString()));
                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    tv.setText("Oops! That didn't work!");
                }
            });

            //Instantiate the RequestQueue and add the request to the queue
            RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
            queue.add(stringRequest);
            String str1 = et1.getText().toString();
            str = Float.parseFloat(str1);
            float e = f * str;
            String ef = Float.toString(e);
            tv.setText(ef);
        }
    });

    button = findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(Main2Activity.this, MainActivity.class);
            startActivity(intent);
        }
    });

}

public void sendjsonrequest() {//sends the request to the website and retrieves specififc data (exchange rate between EUR to ILS)
    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            try {
                tv1 = response.getString("EUR_ILS");

                f = Float.parseFloat(tv1);
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    });
    rq.add(jsonObjectRequest);
}
}
</code>```

答:
```<code> public void sendjsonrequest() {
    StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            try {
                JSONObject jsonObject = new JSONObject(response);
                String tv1 = jsonObject.getString("EUR_ILS");
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    });
    RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
    requestQueue.add(stringRequest);
}
</code>```

Body:
I am trying to fetch a json. While the code used to work I changed it a little and now it doesn't work. The code is supposed to exchange money.

            sendjsonrequest();
            assert tv != null;

            //Request a string response from the URL resource
            StringRequest stringRequest = new StringRequest(Request.Method.GET, "https://free.currencyconverterapi.com/api/v6/convert?q=EUR_ILS&compact=ultra&apiKey=6f4b50fae0c5c91a84bd",
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            // Display the response string.
                            tv.setText("Response is: " + Float.parseFloat(response) * Float.parseFloat(et1.getText().toString()));
                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    tv.setText("Oops! That didn't work!");
                }
            });

            //Instantiate the RequestQueue and add the request to the queue
            RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
            queue.add(stringRequest);
            String str1 = et1.getText().toString();
            str = Float.parseFloat(str1);
            float e = f * str;
            String ef = Float.toString(e);
            tv.setText(ef);
        }
    });

    button = findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(Main2Activity.this, MainActivity.class);
            startActivity(intent);
        }
    });

}

public void sendjsonrequest() {//sends the request to the website and retrieves specififc data (exchange rate between EUR to ILS)
    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            try {
                tv1 = response.getString("EUR_ILS");

                f = Float.parseFloat(tv1);
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    });
    rq.add(jsonObjectRequest);
}
}


问:
How to set content type while uploading a file
I am uploading a file to s3 bucket. While the uploading need to find file extension and need to add it correct content type.

$('#upload-files').on('click', function(e) {
  e.preventDefault();
  var fileName = data.files[0].name;
  var ext = fileName.substring(fileName.lastIndexOf('.') + 1);
  if (ext == "pdf") {
    console.log(data);
    data.submit();
  } else {
    alert("Upload Pdf images only");
    return false;
  }
})
```

How to add its content-type before upload.

答:
This code will help you to send data to server:

public formdata = new FormData();
onSubmit() {
  this.resetform(); //Order matters here
  let headers: any = new Headers();
  headers.append('Content-type', 'undefined');

  formData.append("selectFile", this.formData);
  const req5 = new HttpRequest('POST', 'url as hosted on TOMCAT', formData,
    reportProgress: true,
    responseType: 'text'
  });

  return this.httpClient.request(req5).subscribe(e => {
    (console.log(e);)
  }
}

resetform() {
  this.formData = new FormData();
}
```

Body:
I am uploading a file to s3 bucket. While the uploading need to find file extension and need to add it correct content type.

$('#upload-files').on('click', function(e) {
  e.preventDefault();
  var fileName = data.files[0].name;
  var ext = fileName.substring(fileName.lastIndexOf('.') + 1);
  if (ext == "pdf") {
    console.log(data);
    data.submit();
  } else {
    alert("Upload Pdf images only");
    return false;
  }
})

How to add its content-type before upload.