问:
Button click event fires only once .NET
The first time the button is pressed, the eventhandler is called and a popupwindow appears. After exiting that popupwindow, the second time the button is clicked, the eventhandler isn't called at all. I have debugged the code quite a bit without finding anything 'statewise' that should ruin the code, thus only providing this brief bit of code. Please tell me if you believe more resources are needed to pinpoint this problem.

```<code>     <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="ReferenceControl.ascx.cs" Inherits="DynamicForm.DynamicGenerator.Controls.ReferenceControl" %>
    <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>

    <%@ Register Src="~/DynamicGenerator/Controls/SearchControl.ascx" TagName="SearchControl" TagPrefix="dyncontrols" %>

    <asp:UpdatePanel ID="UpdatePanel1" runat="server" RenderMode="Inline" UpdateMode="Conditional"><ContentTemplate>
    <asp:HyperLink ID="link" runat="server"></asp:HyperLink> <asp:Button ID="btn" runat="server" Text="Välj" onclick="btn_Click" />
    </asp:Panel>
<ajaxToolkit:ModalPopupExtender ID="popUpControl" runat="server" TargetControlID="popupDummyTarget" PopupControlID="pnlSearch" BackgroundCssClass="modalBackground">
</ajaxToolkit:ModalPopupExtender>

protected void btn_Click(object sender, EventArgs e)
    {
        ShowSearch();
    }

void ShowSearch()
    {
                    //some stuff
        popUpControl.Show();
    }
</code>```

How can I make my button listen to my requests?

I have tried adding DataBind() in the eventhandler, unfortunatly that didn't work.

UPDATE1:
The second click generates this error in firebug:

uncaught exception: [Exception... "'Sys.WebForms.PageRequestManagerServerErrorException: Sys.WebForms.PageRequestManagerServerErrorException: Invalid postback or callback argument. Event validation is enabled using  in configuration or <%@ Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.' when calling method: [nsIDOMEventListener::handleEvent]" nsresult: "0x8057001c (NS_ERROR_XPC_JS_THREW_JS_OBJECT)" location: "JS frame :: chrome://firebug/content/spy.js :: callPageHandler :: line 744" data: no]

答: Load up Firebug and see if you're getting any JavaScript errors after the initial click.</p>

Title: Button click event fires only once .NET

Body:
The first time the button is pressed, the eventhandler is called and a popupwindow appears. After exiting that popupwindow, the second time the button is clicked, the eventhandler isn't called at all. I have debugged the code quite a bit without finding anything 'statewise' that should ruin the code, thus only providing this brief bit of code. Please tell me if you believe more resources are needed to pinpoint this problem.

     <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="ReferenceControl.ascx.cs" Inherits="DynamicForm.DynamicGenerator.Controls.ReferenceControl" %>
    <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>

    <%@ Register Src="~/DynamicGenerator/Controls/SearchControl.ascx" TagName="SearchControl" TagPrefix="dyncontrols" %>

    <asp:UpdatePanel ID="UpdatePanel1" runat="server" RenderMode="Inline" UpdateMode="Conditional"><ContentTemplate>
    <asp:HyperLink ID="link" runat="server"></asp:HyperLink> <asp:Button ID="btn" runat="server" Text="Välj" onclick="btn_Click" />
    </asp:Panel>
<ajaxToolkit:ModalPopupExtender ID="popUpControl" runat="server" TargetControlID="popupDummyTarget" PopupControlID="pnlSearch" BackgroundCssClass="modalBackground">
</ajaxToolkit:ModalPopupExtender>

protected void btn_Click(object sender, EventArgs e)
    {
        ShowSearch();
    }

void ShowSearch()
    {
                    //some stuff
        popUpControl.Show();
    }

How can I make my button listen to my requests?

I have tried adding DataBind() in the eventhandler, unfortunatly that didn't work.

UPDATE1:
The second click generates this error in firebug:

uncaught exception: [Exception... "'Sys.WebForms.PageRequestManagerServerErrorException: Sys.WebForms.PageRequestManagerServerErrorException: Invalid postback or callback argument. Event validation is enabled using  in configuration or <%@ Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.' when calling method: [nsIDOMEventListener::handleEvent]" nsresult: "0x8057001c (NS_ERROR_XPC_JS_THREW_JS_OBJECT)" location: "JS frame :: chrome://firebug/content/spy.js :: callPageHandler :: line 744" data: no]


来源: stackexchange

问:
How to copy range of cells as bitmaps in email body?
I have 7 different cell ranges I need to copy and paste as bitmap images in my e-mail body.

The ranges are E3, V29; e30, v54; e55, v80; e81 , v145; x3, af8; x9, af37; e3, v180

```<code>Sub Criaremail()

    Dim Outlook As Object
    Dim email As Object
    Dim xInspect As Object
    Dim pageEditor As Object

    assunto = Sheets("Corpo do Email").Range("AH1")
    para = Sheets("Corpo do Email").Range("AH2")

    Set Outlook = CreateObject("Outlook.application")
    Set email = Outlook.CreateItem(0)

    With email
        .Display
        .Subject = assunto
        .To = para
        .Body = ""

    Set xInspect = email.GetInspector
    Set pageEditor = xInspect.WordEditor

    Sheets("Corpo do Email").Range("E3:V29").Copy

    pageEditor.Application.Selection.Start = Len(.Body)
    pageEditor.Application.Selection.End =
    pageEditor.Application.Selection.Start
    pageEditor.Application.Selection.PasteSpecial (wdPasteBitmap)
    .Display

    Set pageEditor = Nothing
    Set xInspect = Nothing

    End With

    Set email = Nothing
    Set Outlook = Nothing

End Sub
</code>```

答:
You can either copy each of your 7 ranges individually or you loop over each area of a multirange.

I added two alternatives for pasting: Paste as chart or as bitmap.

With my code, you'll also retain your default email signature.

```<code>Sub Criaremail()

    Dim Outlook As Object
    Dim email As Object
    Dim xInspect As Object
    Dim pageEditor As Object
    Dim assunto As String, para As String
    Dim myRange As Excel.Range

    assunto = Sheets("Corpo do Email").Range("AH1")
    para = Sheets("Corpo do Email").Range("AH2")

    Set Outlook = CreateObject("Outlook.application")
    Set email = Outlook.CreateItem(0)

    With email
        .Subject = assunto
        .To = para

        Set xInspect = email.GetInspector
        Set pageEditor = xInspect.WordEditor

        pageEditor.Range.Characters(1).Select
        With pageEditor.Application.Selection
            .Collapse 1                 ' 1 = wdCollapseStart
            .InsertAfter "Hi," & vbCrLf & vbCrLf & _
                     "here's the info:" & vbCrLf
            .Collapse 0                 ' 0 = wdCollapseEnd
            For Each myRange In Sheets("Corpo do Email") _
                .Range( _
                "E3:V29, E30:V54, E55:V80, E81:V145, X3:AF8, X9:AF37, E3:V180" _
                ).Areas
                myRange.Copy
                '.PasteAndFormat Type:=13       ' 13 = wdChartPicture
                .PasteSpecial DataType:=4       ' 4 = wdPasteBitmap
                .InsertParagraphAfter
                .Collapse 0
            Next myRange
            .InsertAfter "Best wishes,"
            .Collapse 0
        End With
        .Display

        Set pageEditor = Nothing
        Set xInspect = Nothing

    End With

    Set email = Nothing
    Set Outlook = Nothing

End Sub
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have 7 different cell ranges I need to copy and paste as bitmap images in my e-mail body.

The ranges are E3, V29; e30, v54; e55, v80; e81 , v145; x3, af8; x9, af37; e3, v180

Sub Criaremail()

    Dim Outlook As Object
    Dim email As Object
    Dim xInspect As Object
    Dim pageEditor As Object

    assunto = Sheets("Corpo do Email").Range("AH1")
    para = Sheets("Corpo do Email").Range("AH2")

    Set Outlook = CreateObject("Outlook.application")
    Set email = Outlook.CreateItem(0)

    With email
        .Display
        .Subject = assunto
        .To = para
        .Body = ""

    Set xInspect = email.GetInspector
    Set pageEditor = xInspect.WordEditor

    Sheets("Corpo do Email").Range("E3:V29").Copy

    pageEditor.Application.Selection.Start = Len(.Body)
    pageEditor.Application.Selection.End =
    pageEditor.Application.Selection.Start
    pageEditor.Application.Selection.PasteSpecial (wdPasteBitmap)
    .Display

    Set pageEditor = Nothing
    Set xInspect = Nothing

    End With

    Set email = Nothing
    Set Outlook = Nothing

End Sub

Body:
You can either copy each of your 7 ranges individually or you loop over each area of a multirange.

I added two alternatives for pasting: Paste as chart or as bitmap.

With my code, you'll also retain your default email signature.

Sub Criaremail()

    Dim Outlook As Object
    Dim email As Object
    Dim xInspect As Object
    Dim pageEditor As Object
    Dim assunto As String, para As String
    Dim myRange As Excel.Range

    assunto = Sheets("Corpo do Email").Range("AH1")
    para = Sheets("Corpo do Email").Range("AH2")

    Set Outlook = CreateObject("Outlook.application")
    Set email = Outlook.CreateItem(0)

    With email
        .Subject = assunto
        .To = para

        Set xInspect = email.GetInspector
        Set pageEditor = xInspect.WordEditor

        pageEditor.Range.Characters(1).Select
        With pageEditor.Application.Selection
            .Collapse 1                 ' 1 = wdCollapseStart
            .InsertAfter "Hi," & vbCrLf & vbCrLf & _
                     "here's the info:" & vbCrLf
            .Collapse 0                 ' 0 = wdCollapseEnd
            For Each myRange In Sheets("Corpo do Email") _
                .Range( _
                "E3:V29, E30:V54, E55:V80, E81:V145, X3:AF8, X9:AF37, E3:V180" _
                ).Areas
                myRange.Copy
                '.PasteAndFormat Type:=13       ' 13 = wdChartPicture
                .PasteSpecial DataType:=4       ' 4 = wdPasteBitmap
                .InsertParagraphAfter
                .Collapse 0
            Next myRange
            .InsertAfter "Best wishes,"
            .Collapse 0
        End With
        .Display

        Set pageEditor = Nothing
        Set xInspect = Nothing

    End With

    Set email = Nothing
    Set Outlook = Nothing

End Sub


问:
How to completely erase the duplicated lines by linux tools?
This question is not equal to How to print only the unique lines in BASH? because that ones suggests to remove all copies of the duplicated lines, while this one is about eliminating their duplicates only, i..e, change 1, 2, 3, 3 into 1, 2, 3 instead of just 1, 2.

This question is really hard to write because I cannot see anything to give meaning to it. But the example is clearly straight. If I have a file like this:

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

After to parse the file erasing the duplicated lines, becoming it like this:

```<code>1
3
4
</code>```

I know python or some of it, this is a python script I wrote to perform it. Create a file called clean_duplicates.py and run it as:

```<code>import sys

#
# To run it use:
# python clean_duplicates.py < input.txt > clean.txt
#
def main():

    lines = sys.stdin.readlines()

    # print( lines )
    clean_duplicates( lines )

#
# It does only removes adjacent duplicated lines, so your need to sort them
# with sensitive case before run it.
#
def clean_duplicates( lines ):

    lastLine    = lines[ 0 ]
    nextLine    = None
    currentLine = None
    linesCount  = len( lines )

    # If it is a one lined file, to print it and stop the algorithm
    if linesCount == 1:

        sys.stdout.write( lines[ linesCount - 1 ] )
        sys.exit()

    # To print the first line
    if linesCount > 1 and lines[ 0 ] != lines[ 1 ]:

        sys.stdout.write( lines[ 0 ] )

    # To print the middle lines, range( 0, 2 ) create the list [0, 1]
    for index in range( 1, linesCount - 1 ):

        currentLine = lines[ index ]
        nextLine    = lines[ index + 1 ]

        if currentLine == lastLine:

            continue

        lastLine = lines[ index ]

        if currentLine == nextLine:

            continue

        sys.stdout.write( currentLine )

    # To print the last line
    if linesCount > 2 and lines[ linesCount - 2 ] != lines[ linesCount - 1 ]:

        sys.stdout.write( lines[ linesCount - 1 ] )

if __name__ == "__main__":

    main()
</code>```

Although, while searching for duplicates lines remove seems to be easier to use tools as grep, sort, sed, uniq:

How to remove duplicate lines inside a text file?

removing line from list using sort, grep LINUX

Find duplicate lines in a file and count how many time each line was duplicated?

Remove duplicate entries in a Bash script

How to delete duplicate lines in a file without sorting it in Unix?

How to delete duplicate lines in a file...AWK, SED, UNIQ not working on my file

答:
```<code>Europe Finland Office Supplies Online H 5/21/2015 193508565 7/3/2015 2339 651.21 524.96 1523180.19 1227881.44 295298.75
Europe Greece Household Online L 9/11/2015 895509612 9/26/2015 49 668.27 502.54 32745.23 24624.46 8120.77
Europe Hungary Beverages Online C 8/21/2012 722931563 8/25/2012 370 47.45 31.79 17556.50 11762.30 5794.20
Europe Hungary Beverages Online C 8/21/2012 722931563 8/25/2012 370 47.45 31.79 17556.50 11762.30 5794.20
</code>```

If you have this kind of lines you can use this command.

```<code>[isuru@192 ~]$ sort duplines.txt | sed 's/\ /\-/g' | uniq | sed 's/\-/\ /g'
</code>```

But keep in mind when using special characters. If there dashes in your lines makes sure to use different symbol. Here i keep a space between back & forward slash.

Before applied the code

After applied the code

Body:
This question is not equal to How to print only the unique lines in BASH? because that ones suggests to remove all copies of the duplicated lines, while this one is about eliminating their duplicates only, i..e, change 1, 2, 3, 3 into 1, 2, 3 instead of just 1, 2.

This question is really hard to write because I cannot see anything to give meaning to it. But the example is clearly straight. If I have a file like this:

1
2
2
3
4

After to parse the file erasing the duplicated lines, becoming it like this:

1
3
4

I know python or some of it, this is a python script I wrote to perform it. Create a file called clean_duplicates.py and run it as:

import sys

#
# To run it use:
# python clean_duplicates.py < input.txt > clean.txt
#
def main():

    lines = sys.stdin.readlines()

    # print( lines )
    clean_duplicates( lines )

#
# It does only removes adjacent duplicated lines, so your need to sort them
# with sensitive case before run it.
#
def clean_duplicates( lines ):

    lastLine    = lines[ 0 ]
    nextLine    = None
    currentLine = None
    linesCount  = len( lines )

    # If it is a one lined file, to print it and stop the algorithm
    if linesCount == 1:

        sys.stdout.write( lines[ linesCount - 1 ] )
        sys.exit()

    # To print the first line
    if linesCount > 1 and lines[ 0 ] != lines[ 1 ]:

        sys.stdout.write( lines[ 0 ] )

    # To print the middle lines, range( 0, 2 ) create the list [0, 1]
    for index in range( 1, linesCount - 1 ):

        currentLine = lines[ index ]
        nextLine    = lines[ index + 1 ]

        if currentLine == lastLine:

            continue

        lastLine = lines[ index ]

        if currentLine == nextLine:

            continue

        sys.stdout.write( currentLine )

    # To print the last line
    if linesCount > 2 and lines[ linesCount - 2 ] != lines[ linesCount - 1 ]:

        sys.stdout.write( lines[ linesCount - 1 ] )

if __name__ == "__main__":

    main()

Although, while searching for duplicates lines remove seems to be easier to use tools as grep, sort, sed, uniq:

How to remove duplicate lines inside a text file?

removing line from list using sort, grep LINUX

Find duplicate lines in a file and count how many time each line was duplicated?

Remove duplicate entries in a Bash script

How to delete duplicate lines in a file without sorting it in Unix?

How to delete duplicate lines in a file...AWK, SED, UNIQ not working on my file

Body:
Europe Finland Office Supplies Online H 5/21/2015 193508565 7/3/2015 2339 651.21 524.96 1523180.19 1227881.44 295298.75
Europe Greece Household Online L 9/11/2015 895509612 9/26/2015 49 668.27 502.54 32745.23 24624.46 8120.77
Europe Hungary Beverages Online C 8/21/2012 722931563 8/25/2012 370 47.45 31.79 17556.50 11762.30 5794.20
Europe Hungary Beverages Online C 8/21/2012 722931563 8/25/2012 370 47.45 31.79 17556.50 11762.30 5794.20

If you have this kind of lines you can use this command.

[isuru@192 ~]$ sort duplines.txt | sed 's/\ /\-/g' | uniq | sed 's/\-/\ /g'

But keep in mind when using special characters. If there dashes in your lines makes sure to use different symbol. Here i keep a space between back & forward slash.

Before applied the code

After applied the code


问:
How to find value from data’s index?
I have the data:

```<code>0101400
0102500
0103300
0202500
0205600
etc
</code>```

How to get value from index data in javascript

```<code>0101 value 400
0102 value 500
0103 value 300
0202 value 500
0205 value 600
</code>```

Please help, thank you..

答:
If its in string format you can use sub string function to get the last 3 digits and the other part

var data = ["0101400", "0102500", "0103300", "0202500", "0205600"];

for(var i = 0; i < data.length; i++){
  var index = data[i].substr(data[i].length -3, 3);
  var value = data[i].substr(0, data[i].length -3);
  console.log(value + " value " + index );
}```

Title: How to find value from data’s index?

Body:
I have the data:

0101400
0102500
0103300
0202500
0205600
etc

How to get value from index data in javascript

0101 value 400
0102 value 500
0103 value 300
0202 value 500
0205 value 600

Please help, thank you..


问:
Calendar week end days issue
I am getting a calendar instance

```<code>Calendar.getInstance()
</code>```

In one mobile it is showing Saturday as weekend while in another it is showing Sunday as weekend
The timezone of both devices is same

If i set the calendar instance locale to US or any other country it works perfectly.
But i dont want it to be constant. I want it to be regional but consistent on all devices

I want the weekend on both devices same if the time zone is same

答:
you can try this   </p>

```<code>Calendar.getInstance().setFirstDayOfWeek(Calendar.SUNDAY);
</code>```

Title: Calendar week end days issue

Body:
I am getting a calendar instance

Calendar.getInstance()

In one mobile it is showing Saturday as weekend while in another it is showing Sunday as weekend
The timezone of both devices is same

If i set the calendar instance locale to US or any other country it works perfectly.
But i dont want it to be constant. I want it to be regional but consistent on all devices

I want the weekend on both devices same if the time zone is same

Body:
you can try this

Calendar.getInstance().setFirstDayOfWeek(Calendar.SUNDAY);


问:
For error correcting coder, are there any other distance definitions beside hamming distance?
I am trying to get the distance of two binary numbers for error correcting. Although Hamming distance can find the number of different bits between two numbers, it does not indicate the absolute difference of two numbers. Are there any other distance definitions that describe the absolute difference between two binary numbers?</p>

答:
This is a question of coding theory where I am not an expert. However the answer for general-purpose digital systems is NO:

Here, all information is represented by bits that are grouped into bytes, words, etc..

But a group of bytes can represent anything, an instruction, data, and individual bits can even control e.g. an elevator. Thus, bits don't have an intrinsic "importance", and error detection (has a bit changed?) and error correction (which bit combination is closest to the received one?) is done for all bits in the same way.

A completely different situation is when a group of bits has an intrinsic meaning, e.g. represent a number. Here bits are are of different importance. In special-purpose digital systems, this could be exploited to protect more important bits better than others, but I don't have an example.

A trivial case is however special-purpose analog electronics, say an old phone system. Here, your idea to protect more important information better, is realised: Low induced voltages don't disturb loud voices.


问:
How to insert form value into shell_exec
I have a script I am trying to execute in PHP. The script searches a txt file for whatever is queried. It then posts the results.

Example 1

```<code>  <?php
   $output = shell_exec('/var/www/html/scripts/query.sh');
   echo $output;
   ?>
</code>```

"Example 2" I add the query to the end of the query.sh the query is bob@yahoo.com

```<code>   <?php
   $output = shell_exec('/var/www/html/scripts/query.sh bob@yahoo.com');
   echo $output;
   ?>
</code>```

What I want to do is have a form I or anyone can type in a query and it inputs it at the end of query.sh where bob@yahoo.com is. Can anyone help me accomplish this? I am new to PHP so try not to flame me to bad. Thank you for your help.

This is the bash script

```<code>   #!/bin/bash
 dir=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )

if [ "$1" != "" ]; then
  letter1=$(echo ${1,,}|cut -b1)
  if [[ $letter1 == [a-zA-Z0-9] ]]; then
      if [ -f "$dir/data/$letter1" ]; then
          grep -ai "^$1" "$dir/data/$letter1"
      else
          letter2=$(echo ${1,,}|cut -b2)
          if [[ $letter2 == [a-zA-Z0-9] ]]; then
              if [ -f "$dir/data/$letter1/$letter2" ]; then
                  grep -ai "^$1" "$dir/data/$letter1/$letter2"
              else
                  letter3=$(echo ${1,,}|cut -b3)
                  if [[ $letter3 == [a-zA-Z0-9] ]]; then
                      if [ -f "$dir/data/$letter1/$letter2/$letter3" ]; then
                          grep -ai "^$1" "$dir/data/$letter1/$letter2/$letter3"
                      fi
                  else
                      if [ -f "$dir/data/$letter1/$letter2/symbols" ];  then
                          grep -ai "^$1" "$dir/data/$letter1/$letter2 /symbols"
                      fi
                  fi
              fi
          else
              if [ -f "$dir/data/$letter1/symbols" ]; then
                  grep -ai "^$1" "$dir/data/$letter1/symbols"
              fi
          fi
      fi
  else
      if [ -f "$dir/data/symbols" ]; then
          grep -ai "^$1" "$dir/data/symbols"
      fi
  fi
  else
  echo "[*] Example: ./query name@domain.com"
 fi
</code>```

答:
so your code should look pretty similar to this.

```<code><?php
       if(isset($_POST['arg']){
       $your_input = $_POST['arg'];
       $output = shell_exec("/var/www/html/scripts/query.sh {$your_input}");
       echo $output;
       }
 ?>

<form action="" method="POST">
<input type="text" name="arg">
<input type="submit" value="Submit">
</form>
</code>```

Try this, it should work fine.

Body:
I have a script I am trying to execute in PHP. The script searches a txt file for whatever is queried. It then posts the results.

Example 1

  <?php
   $output = shell_exec('/var/www/html/scripts/query.sh');
   echo $output;
   ?>

"Example 2" I add the query to the end of the query.sh the query is bob@yahoo.com

   <?php
   $output = shell_exec('/var/www/html/scripts/query.sh bob@yahoo.com');
   echo $output;
   ?>

What I want to do is have a form I or anyone can type in a query and it inputs it at the end of query.sh where bob@yahoo.com is. Can anyone help me accomplish this? I am new to PHP so try not to flame me to bad. Thank you for your help.

This is the bash script

   #!/bin/bash
 dir=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )

if [ "$1" != "" ]; then
  letter1=$(echo ${1,,}|cut -b1)
  if [[ $letter1 == [a-zA-Z0-9] ]]; then
      if [ -f "$dir/data/$letter1" ]; then
          grep -ai "^$1" "$dir/data/$letter1"
      else
          letter2=$(echo ${1,,}|cut -b2)
          if [[ $letter2 == [a-zA-Z0-9] ]]; then
              if [ -f "$dir/data/$letter1/$letter2" ]; then
                  grep -ai "^$1" "$dir/data/$letter1/$letter2"
              else
                  letter3=$(echo ${1,,}|cut -b3)
                  if [[ $letter3 == [a-zA-Z0-9] ]]; then
                      if [ -f "$dir/data/$letter1/$letter2/$letter3" ]; then
                          grep -ai "^$1" "$dir/data/$letter1/$letter2/$letter3"
                      fi
                  else
                      if [ -f "$dir/data/$letter1/$letter2/symbols" ];  then
                          grep -ai "^$1" "$dir/data/$letter1/$letter2 /symbols"
                      fi
                  fi
              fi
          else
              if [ -f "$dir/data/$letter1/symbols" ]; then
                  grep -ai "^$1" "$dir/data/$letter1/symbols"
              fi
          fi
      fi
  else
      if [ -f "$dir/data/symbols" ]; then
          grep -ai "^$1" "$dir/data/symbols"
      fi
  fi
  else
  echo "[*] Example: ./query name@domain.com"
 fi

Body:
so your code should look pretty similar to this.

<?php
       if(isset($_POST['arg']){
       $your_input = $_POST['arg'];
       $output = shell_exec("/var/www/html/scripts/query.sh {$your_input}");
       echo $output;
       }
 ?>

<form action="" method="POST">
<input type="text" name="arg">
<input type="submit" value="Submit">
</form>

Try this, it should work fine.


问:
How to change particle effect color?
How can I change the color of the particle system to be same as my player color?

I tried to find on some tutorials how to do it and I got this solution:

```<code>GameObject effectBlow = Instantiate(blowOut, transform.position, Quaternion.identity) as GameObject;
effectBlow.gameObject.GetComponent<ParticleSystem>().startColor = material.material.color;
</code>```

But now my Unity is complaining about that code and it says it's obsolete and of course colors don't change in game.

I don't know how to change it, can somebody help me ?

答:
startColor property is deprecated,so it can't be used like that, try this code

```<code>        GameObject effectBlow = Instantiate(blowOut, transform.position, Quaternion.identity) as GameObject;
        var main = effectBlow.gameObject.GetComponent<ParticleSystem>().main;
        main.startColor = player.GetComponent<Renderer>().material.color;
</code>```

So what it basically does is it create a variable main and the instantiated gameobject's particleSystem main module will be refereed to it from that main variable we use startColor property to modify the color of player gameobject

For more info check this out :
https://docs.unity3d.com/ScriptReference/ParticleSystem-main.html

Title: How to change particle effect color?

Body:
How can I change the color of the particle system to be same as my player color?

I tried to find on some tutorials how to do it and I got this solution:

GameObject effectBlow = Instantiate(blowOut, transform.position, Quaternion.identity) as GameObject;
effectBlow.gameObject.GetComponent<ParticleSystem>().startColor = material.material.color;

But now my Unity is complaining about that code and it says it's obsolete and of course colors don't change in game.

I don't know how to change it, can somebody help me ?

Body:
startColor property is deprecated,so it can't be used like that, try this code

        GameObject effectBlow = Instantiate(blowOut, transform.position, Quaternion.identity) as GameObject;
        var main = effectBlow.gameObject.GetComponent<ParticleSystem>().main;
        main.startColor = player.GetComponent<Renderer>().material.color;

So what it basically does is it create a variable main and the instantiated gameobject's particleSystem main module will be refereed to it from that main variable we use startColor property to modify the color of player gameobject

For more info check this out :
https://docs.unity3d.com/ScriptReference/ParticleSystem-main.html


问:
I keep getting null exception when the parameter is supposed to be empty when I create new data
I'm having trouble with my doPost method in my servlet. I'm doing a simple system with java and oracle for its database. And in database, attribute rph_id is auto-increment, so in Java, when I want to create a new set of data, the rph_id is supposed to be empty, right?

The codes worked before but now it doesn't work anymore. It keeps giving null exception.

```<code>protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{

    int rph_id = Integer.parseInt(request.getParameter("rph_id"));
    String rph_date = request.getParameter("rph_date");
    String rph_time = request.getParameter("rph_time");
    String rph_type = request.getParameter("rph_type");
    int teacher_id = Integer.parseInt(request.getParameter("teacher_id"));
    int subject_id = Integer.parseInt(request.getParameter("subject_id"));
    String rph_submitstatus = null;
    String rph_comment = null;

    RPHS rph = new RPHS(rph_date, rph_time, rph_type, rph_submitstatus, rph_comment, teacher_id, subject_id, false);
    rph = RphDAO.getRph(rph);
}
</code>```

I keep getting null at line int rph_id = Integer.parseInt(request.getParameter("rph_id"));

the rph_id is auto-increment in the database. It's an attribute in the parent class, and I have to use in the child class.

答:
You're saying that it's auto-increment key at DB, so why are you trying to get it from request parameters ?  You can't get a value from there if you didn't ever set a value , or set by a html form etc..

You should get it from your RPHS object after insert.

```<code>protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
    //int rph_id = Integer.parseInt(request.getParameter("rph_id"));
    ..
    ..

    RPHS rph = new RPHS(rph_date, rph_time, rph_type, rph_submitstatus, rph_comment, teacher_id, subject_id, false);
    rph = RphDAO.getRph(rph);

    int rph_id=rph.getRphId();
}
</code>```

Body:
I'm having trouble with my doPost method in my servlet. I'm doing a simple system with java and oracle for its database. And in database, attribute rph_id is auto-increment, so in Java, when I want to create a new set of data, the rph_id is supposed to be empty, right?

The codes worked before but now it doesn't work anymore. It keeps giving null exception.

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{

    int rph_id = Integer.parseInt(request.getParameter("rph_id"));
    String rph_date = request.getParameter("rph_date");
    String rph_time = request.getParameter("rph_time");
    String rph_type = request.getParameter("rph_type");
    int teacher_id = Integer.parseInt(request.getParameter("teacher_id"));
    int subject_id = Integer.parseInt(request.getParameter("subject_id"));
    String rph_submitstatus = null;
    String rph_comment = null;

    RPHS rph = new RPHS(rph_date, rph_time, rph_type, rph_submitstatus, rph_comment, teacher_id, subject_id, false);
    rph = RphDAO.getRph(rph);
}

I keep getting null at line int rph_id = Integer.parseInt(request.getParameter("rph_id"));

the rph_id is auto-increment in the database. It's an attribute in the parent class, and I have to use in the child class.

Body:
You're saying that it's auto-increment key at DB, so why are you trying to get it from request parameters ?  You can't get a value from there if you didn't ever set a value , or set by a html form etc..

You should get it from your RPHS object after insert.

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
    //int rph_id = Integer.parseInt(request.getParameter("rph_id"));
    ..
    ..

    RPHS rph = new RPHS(rph_date, rph_time, rph_type, rph_submitstatus, rph_comment, teacher_id, subject_id, false);
    rph = RphDAO.getRph(rph);

    int rph_id=rph.getRphId();
}


问:
Progress Bar is hidden While Printing a html Page
I am making a project where I have to use a progress bar, and in the end I have to print that page simply. But the problem is whenever I print/ or save as pdf, the page using ctrl+p command progress bar becomes invisible on the printed/PDF document.

I am using very simple example, which is available on w3schools.com. and I am providing the code as well

```<code><html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container">
  <h2 style="color:red">Colored Progress Bars</h2>

  <!-- Blue -->
  <div class="progress">
    <div class="progress-bar" style="width:10%"></div>
  </div><br>

  <!-- Green -->
  <div class="progress">
    <div class="progress-bar bg-success" style="width:20%"></div>
  </div><br>
</div>

</body>
</html>
</code>```

答:
I hope it helps you:

```<code>@media print {
.progress {
    position: relative;
}
.progress:before {
    display: block;
    content: '';
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    z-index: 0;
    border-bottom: 2rem solid #eeeeee;
}
.progress-bar {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    z-index: 1;
    border-bottom: 2rem solid #337ab7;
}
.bg-success {
    border-bottom-color: #67c600;
}
.bg-info {
    border-bottom-color: #5bc0de;
}
.bg-warning {
    border-bottom-color: #f0a839;
}
.bg-danger {
    border-bottom-color: #ee2f31;
}
}
</code>```

my reference > Bootstrap - progress-bar is not shown in print preview

Body:
I am making a project where I have to use a progress bar, and in the end I have to print that page simply. But the problem is whenever I print/ or save as pdf, the page using ctrl+p command progress bar becomes invisible on the printed/PDF document.

I am using very simple example, which is available on w3schools.com. and I am providing the code as well

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

Colored Progress Bars

Body:
I hope it helps you:

@media print {
.progress {
    position: relative;
}
.progress:before {
    display: block;
    content: '';
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    z-index: 0;
    border-bottom: 2rem solid #eeeeee;
}
.progress-bar {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    z-index: 1;
    border-bottom: 2rem solid #337ab7;
}
.bg-success {
    border-bottom-color: #67c600;
}
.bg-info {
    border-bottom-color: #5bc0de;
}
.bg-warning {
    border-bottom-color: #f0a839;
}
.bg-danger {
    border-bottom-color: #ee2f31;
}
}

my reference > Bootstrap - progress-bar is not shown in print preview


问:
How to convert an integer in a base to a string
Sometimes I have integers like these 021 or 011.

If I try to convert them to a string, the result will be:

```<code>p 021.to_s # "17" instead "021"
p 011.to_s # "9" instead "011"
</code>```

Why does this happen and how can I convert the integers to strings?

答:
You can refer to the literals documentation to find the special prefixs to write numbers in decimal, hexadecimal, octal or binary formats.

For decimal numbers use a prefix of 0d, for hexadecimal numbers use a prefix of 0x, for octal numbers use a prefix of 0 or 0o, for binary numbers use a prefix of 0b. The alphabetic component of the number is not case-sensitive.

21 or 0d21 is considered as number in decimal format but 021 is considered as number in octal format. And when interpreted to print it, it uses default decimal format.

Body:
Sometimes I have integers like these 021 or 011.

If I try to convert them to a string, the result will be:

p 021.to_s # "17" instead "021"
p 011.to_s # "9" instead "011"

Why does this happen and how can I convert the integers to strings?


问:
Jquery SlideToggle AND scroll
I'm having a problem with a slidetoggle link which appears at the bottom of my page.
Effectively I want the user to click to show/hide the hidden div (which works fine)

The problem is the page doesn't scroll down to show the now, not hidden div

As a JQuery novice, is there any way to toggle the div and then center it on the page? Or at least scroll down, without things getting too complicated?

Thanks

答:
To perform this function, I'd recommend using a callback from your slideToggle call to set the document scroll using the scrollTop function.  You'll be able to determine the value to the scrollTop setter by using offset to get the top position of the toggled container relative to the page. I'd suggest restricting the scroll behavior to only fire when the element is shown, not hidden.

In general, directly setting page scroll can be a slightly jarring UX. For that reason I'm actually going to give you code that animates scrollTop rather than straight up sets it using the scrollTop function, but this approach is not necessary as a direct call to scrollTop will equally position the page. I just think as a user I'd rather see a gradual scroll rather than a sudden positional change.

The code, for instance, would take the form:

```<code>$(".myShowHideLink").click(function() {
    $(".myToggleContainer").slideToggle("slow", function() {
        if ($(this).is(":visible")) {
            $(document).animate({
                scrollTop: $(this).offset().top
            }, "slow")
        }
    });
});
</code>```

You may want to actually use $(this).offset().top - 50 or something similar so the scroll's set just a few pixels above the top of the container, but that's up to you. I find I  don't like my elements to be butting up against the top border of the window.

I apologize I haven't created a test case for this as I'm shooting from the hip, but if it doesn't work as advertised, let me know and I'll adjust the code.

ContentLicense: CC BY-SA 3.0

Title: Jquery SlideToggle AND scroll

Body:
To perform this function, I'd recommend using a callback from your slideToggle call to set the document scroll using the scrollTop function.  You'll be able to determine the value to the scrollTop setter by using offset to get the top position of the toggled container relative to the page. I'd suggest restricting the scroll behavior to only fire when the element is shown, not hidden.

In general, directly setting page scroll can be a slightly jarring UX. For that reason I'm actually going to give you code that animates scrollTop rather than straight up sets it using the scrollTop function, but this approach is not necessary as a direct call to scrollTop will equally position the page. I just think as a user I'd rather see a gradual scroll rather than a sudden positional change.

The code, for instance, would take the form:

$(".myShowHideLink").click(function() {
    $(".myToggleContainer").slideToggle("slow", function() {
        if ($(this).is(":visible")) {
            $(document).animate({
                scrollTop: $(this).offset().top
            }, "slow")
        }
    });
});

You may want to actually use $(this).offset().top - 50 or something similar so the scroll's set just a few pixels above the top of the container, but that's up to you. I find I  don't like my elements to be butting up against the top border of the window.

I apologize I haven't created a test case for this as I'm shooting from the hip, but if it doesn't work as advertised, let me know and I'll adjust the code.


问:
Execute two functions for a button in flutter
So i want to be able to save the text from the textcontroller that user have keyed in into shared preferences However, i want to go to the next page too at the same time.

So:

Save the text in a shared preference

Go to next page

```<code>final _text = TextEditingController();

_nameSaver() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString('my_string_key', _text.text);
  }

FooterRaisedButton(
                  "Next",
                  () => (_text.text.isEmpty)
                      ? null
                      : Navigator.pushNamed(context, '/onboardMarket'),
                  "#0087a8")
</code>```

I dont know how to call out the function that saves the name at the same time the button pressed will go to the next page

答:
Remove fat arrow (=>), and implement it like this:

```<code>FooterRaisedButton(
  "Next",
   () async {
    if (_text.text.isEmpty)
      return; // return if it is empty
    await nameSaver(); // else save it here
    Navigator.pushNamed(context, '/onboardMarket'); // once done, navigate
  }
);
</code>```

Just to give you a basic idea,

```<code>// only one statement can be executed using fat notation
RaisedButton(onPressed: () => _calculate(1));

// here you can perform as many as you need.
RaisedButton(onPressed: () {
  _calculate(1);
  _printScreen();
});
</code>```

Body:
So i want to be able to save the text from the textcontroller that user have keyed in into shared preferences However, i want to go to the next page too at the same time.

So:

Save the text in a shared preference

Go to next page

final _text = TextEditingController();

_nameSaver() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString('my_string_key', _text.text);
  }

FooterRaisedButton(
                  "Next",
                  () => (_text.text.isEmpty)
                      ? null
                      : Navigator.pushNamed(context, '/onboardMarket'),
                  "#0087a8")

I dont know how to call out the function that saves the name at the same time the button pressed will go to the next page

Body:
Remove fat arrow (=>), and implement it like this:

FooterRaisedButton(
  "Next",
   () async {
    if (_text.text.isEmpty)
      return; // return if it is empty
    await nameSaver(); // else save it here
    Navigator.pushNamed(context, '/onboardMarket'); // once done, navigate
  }
);

Just to give you a basic idea,

// only one statement can be executed using fat notation
RaisedButton(onPressed: () => _calculate(1));

// here you can perform as many as you need.
RaisedButton(onPressed: () {
  _calculate(1);
  _printScreen();
});


问:
Why I'm getting java.lang.IndexOutOfBoundsException when I try to get an item of jsonArray?
In my app I have smth like attaching files to messages. These attached file are shown in RecyclerView with adapter. Each item of RV has it own btn for deleting it. The problem is when I have two items at my list and try to delete 1 item not the 2-nd I'm receiving an error. But when I try to remove 2-nd item and then 1-st everything ok. I used debugger and managed to locate problematic line but I don't know how to solve this problem. So, here is code from adapter for removing item from list:

```<code>val array = Singleton.array
if (array!!.size() > 0) {
  for (i in 0 until array.size()) {
   val obj = array.get(i).asJsonObject

   if (obj.get("filename").toString().substring(1, obj.get("filename").toString().length - 1) == mNames[position]) {
   array.remove(obj)
   mNames.removeAt(position)
   Singleton.array = array
   updateNames(mNames)
   }

 }
}
</code>```

I have problem at this line:

```<code>val obj = array.get(i).asJsonObject
</code>```

I checked via logger this variable and everything seems to be ok,  I can get value with 0 index. Then I thought that problem is at the place where I send data to adapter, but everything ok. I used debugger and saw that method getAsJsonObject() throws this exception:

why does it happen and how I can solve this error. I tried to change this:
for (i in 0 until array.size()) to this for (i in 0 until array.size()-1) and it didn't work. Then I tried to change this loop to this for (i in 1 until array.size()) and it didn't help also. So, where I made mistake and how I can prevent this problem in future?

P.S. Sorry for attaching screenshot of debugger, because I couldn't get text data from it.

答:
Dear friends it seems that I managed to solve this problem but I'm not sure so I need your checking. So, I added return statement in my condition:

```<code>if (obj.get("filename").toString().substring(1, obj.get("filename").toString().length - 1) == mNames[position]) {
array.remove(obj)
mNames.removeAt(position)
Singleton.array = array
updateNames(mNames)
return@setButton
}
</code>```

so when I meet this condition I return from process of deleting. I think that I know why my app has been crashing sometimes - I press yes btn at my alert dialog and my object was removed from array but my loop continue working and checking. But maybe I'm wrong again :)

Body:
In my app I have smth like attaching files to messages. These attached file are shown in RecyclerView with adapter. Each item of RV has it own btn for deleting it. The problem is when I have two items at my list and try to delete 1 item not the 2-nd I'm receiving an error. But when I try to remove 2-nd item and then 1-st everything ok. I used debugger and managed to locate problematic line but I don't know how to solve this problem. So, here is code from adapter for removing item from list:

val array = Singleton.array
if (array!!.size() > 0) {
  for (i in 0 until array.size()) {
   val obj = array.get(i).asJsonObject

   if (obj.get("filename").toString().substring(1, obj.get("filename").toString().length - 1) == mNames[position]) {
   array.remove(obj)
   mNames.removeAt(position)
   Singleton.array = array
   updateNames(mNames)
   }

 }
}

I have problem at this line:

val obj = array.get(i).asJsonObject

I checked via logger this variable and everything seems to be ok,  I can get value with 0 index. Then I thought that problem is at the place where I send data to adapter, but everything ok. I used debugger and saw that method getAsJsonObject() throws this exception:

why does it happen and how I can solve this error. I tried to change this:
for (i in 0 until array.size()) to this for (i in 0 until array.size()-1) and it didn't work. Then I tried to change this loop to this for (i in 1 until array.size()) and it didn't help also. So, where I made mistake and how I can prevent this problem in future?

P.S. Sorry for attaching screenshot of debugger, because I couldn't get text data from it.

Body:
Dear friends it seems that I managed to solve this problem but I'm not sure so I need your checking. So, I added return statement in my condition:

if (obj.get("filename").toString().substring(1, obj.get("filename").toString().length - 1) == mNames[position]) {
array.remove(obj)
mNames.removeAt(position)
Singleton.array = array
updateNames(mNames)
return@setButton
}

so when I meet this condition I return from process of deleting. I think that I know why my app has been crashing sometimes - I press yes btn at my alert dialog and my object was removed from array but my loop continue working and checking. But maybe I'm wrong again :)


问:
Django model search won't return any values
I'm trying to create a search function that will return the corresponding values in the table based on the id or asset_name but it's not returning anything when I search for a valid id or asset_name. Is there something I'm missing in my code?

Views.py

```<code>def search(request):
template = 'blog/home.html'

query = request.GET.get('q')

if query:
    results = Post.objects.filter(Q(id__icontains=query) | Q(asset_name__icontains=query))
else:
    results = Post.objects.filter(status="Published")

context = {
    'query': query
}
return render(request, template, context)

class PostListView(ListView):
model = Post
template_name = 'blog/home.html'
context_object_name = 'posts'
ordering = ['-date_posted']
</code>```

Urls.py

```<code>urlpatterns = [
path('', PostListView.as_view(), name='blog-home'),
path('results/', search, name='search'),
]
</code>```

Home.html

```<code><form method="GET" action="{% url 'search' %}">
 <input type="text" name="q" value="{{request.GET.q}}" placeholder="Search for project" />
 <input type="submit" value="Search" />
</form>

<tbody>
{% for post in posts %}
<tr data-href="linkToFile.pdf">
<td>{{ post.id }}{% if query %}&q={{query}}{% endif %}</td>
<td><a href="{% url 'post-detail' post.id %}">{{ post.asset_name }}{% if query %}&q={{query}}{% endif %}</a></td>
</tr>
{% endfor %}
</tbody>
</code>```

答:
In your template, you are not sending posts as a context in search view. Which is why the iteration % for post in posts %} isn't working. I think its simpler to use it like this:

Template

```<code><form method="GET" action="{% url 'results' %}">
 <input type="text" name="q" value="{{query}}" placeholder="Search for project" />
 <input type="submit" value="Search" />
</form>

<tbody>
{% for post in posts %}
<tr data-href="linkToFile.pdf">
<td>{{ post.id }}{% if query %}&q={{query}}{% endif %}</td>
<td><a href="{% url 'post-detail' post.id %}">{{ post.asset_name }}{% if query %}&q={{query}}{% endif %}</a></td>
</tr>
{% endfor %}
</tbody>
</code>```

View

```<code>class PostListView(ListView):
    model = Post
    template_name = 'blog/home.html'
    context_object_name = 'posts'
    ordering = ['-date_posted']

    def get_context_data(self, **kwargs):
        context = super(PostListView, self).get_context_data(**kwargs)
        <b>query = request.GET.get('q')
        if query:
           context['posts'] = Post.objects.filter(Q(id__icontains=query) | Q(asset_name__icontains=query))
           context['query'] = query</b>
        return context</code>```

In this way, you can get search and list view using one PostListView view, also don't need to use extra view to show search results.

Body:
I'm trying to create a search function that will return the corresponding values in the table based on the id or asset_name but it's not returning anything when I search for a valid id or asset_name. Is there something I'm missing in my code?

Views.py

def search(request):
template = 'blog/home.html'

query = request.GET.get('q')

if query:
    results = Post.objects.filter(Q(id__icontains=query) | Q(asset_name__icontains=query))
else:
    results = Post.objects.filter(status="Published")

context = {
    'query': query
}
return render(request, template, context)

class PostListView(ListView):
model = Post
template_name = 'blog/home.html'
context_object_name = 'posts'
ordering = ['-date_posted']

Urls.py

urlpatterns = [
path('', PostListView.as_view(), name='blog-home'),
path('results/', search, name='search'),
]

Home.html

<form method="GET" action="{% url 'search' %}">
 <input type="text" name="q" value="{{request.GET.q}}" placeholder="Search for project" />
 <input type="submit" value="Search" />
</form>

{% for post in posts %}

{{ post.id }}{% if query %}&q={{query}}{% endif %}
{{ post.asset_name }}{% if query %}&q={{query}}{% endif %}

{% endfor %}

Body:
In your template, you are not sending posts as a context in search view. Which is why the iteration % for post in posts %} isn't working. I think its simpler to use it like this:

Template

<form method="GET" action="{% url 'results' %}">
 <input type="text" name="q" value="{{query}}" placeholder="Search for project" />
 <input type="submit" value="Search" />
</form>

<tbody>
{% for post in posts %}
<tr data-href="linkToFile.pdf">
<td>{{ post.id }}{% if query %}&q={{query}}{% endif %}</td>
<td><a href="{% url 'post-detail' post.id %}">{{ post.asset_name }}{% if query %}&q={{query}}{% endif %}</a></td>
</tr>
{% endfor %}
</tbody>

View

class PostListView(ListView):
    model = Post
    template_name = 'blog/home.html'
    context_object_name = 'posts'
    ordering = ['-date_posted']

    def get_context_data(self, **kwargs):
        context = super(PostListView, self).get_context_data(**kwargs)
        query = request.GET.get('q')
        if query:
           context['posts'] = Post.objects.filter(Q(id__icontains=query) | Q(asset_name__icontains=query))
           context['query'] = query
        return context

In this way, you can get search and list view using one PostListView view, also don't need to use extra view to show search results.


问:
Are there any open-source implementations of the Mercator Web Crawler
Marc Najork and Allan Heydon have written an excellent paper on their Java, scalable and extensible web crawler called Mercator.

Here are some resources on the Mercator web crawler:

Mercator Presentation (pdf)

Mercator Introduction (pdf)

Mercator Web Crawler Paper (pdf)

First result in Google for the query: "Web Crawling Contents Najork pdf"

Has anybody seen any implementations of the crawler (preferably java)?

Update:

I'm I was having trouble with the links, I'm going to try to get better links for the referenced papers. but I think I've fixed them now.

答:
I've found a couple of Java crawlers that are supposed to be pretty close to Mercator:

Nutch is multithreaded and distributed.

Heritrix is only multithreaded.

Other references are welcome.


问:
MARS Simulator has PC-relative addressing refer to the number of bytes instead of words?
I'm currently reading the book of David Patterson and John Hennesy titled: "Computer Organisation and Design - 4th Edition". In some point the book says:

Since all MIPS instructions are 4 bytes long, MIPS stretches the distance of the branch by having PC-relative addressing refer to the number of
  words to the next instruction instead of the number of bytes.

As soon as I read that, I went over to the MARS Simulator to see that in practise. To my surprise, I observed that the $pc register doesn't follow that rule and has always the byte memory address stored.

Shouldn't the $pc register be something like this before the execution of the below instructions located in the instruction addresses?

```<code>Instruction Address |    $pc Content
                    |
    0x00400000      |     0x00100000
    0x00400004      |     0x00100001
    0x00400008      |     0x00100002
      ....          |         ....
</code>```

答:
... stretches the distance of the branch by having PC-relative addressing refer to the number of words to the next instruction instead of the number of bytes.

This sentence only means:

The instruction 0x1000nnnn (b nnnn) stored at the address X will jump to the instruction at the address X+4+4*nnnn, not to the instruction at the address X+4+nnnn.

The sentence says nothing about the PC register and its value itself.

I observed that the $pc register doesn't follow that rule and has always the byte memory address stored.

Shouldn't the $pc register be something like this before the execution of the below instructions located in the instruction addresses?

The question here is: What exactly is the $pc register?

On some CPUs (like ARM), there are instructions that would be written as addu $t0,$t0,$pc in MIPS assembly language. Talking about such CPUs it is easy to answer the question:

The value of the $pc register is the value which will be added to $t0 if the instruction addu $t0,$t0,$pc is executed.

On real MIPS CPUs (not MIPS emulators), the PC register is some kind of memory (a 30-bit latch) which can hold 30 bits of information.

However, when talking about information stored in some memory, we have to define how to interpret the information:

The bits 10000111 may be interpreted as 135 (unsigned), 87 (BCD), -121 (two's complement), -120 (one's complement), -7 (sign and absolute), SOME_ENUM_CONSTANT (enumeration), -0.09, 0.7, 1.35 (various floating- and fixed-point variants) ...

It is well defined that the bits 0000...011100 in the PC register point to the instruction at address 0x70. However, it is not defined if this value has to be written as PC=0x1C or as PC=0x70.

Therefore some MIPS emulator might display $pc=0x400000 and another one might display $pc=0x100000 for the same value in the PC register!

However, I think (nearly) all MIPS emulators will display $pc=0x400000 because the users are interested in the address the instruction points to.

Body:
I'm currently reading the book of David Patterson and John Hennesy titled: "Computer Organisation and Design - 4th Edition". In some point the book says:

Since all MIPS instructions are 4 bytes long, MIPS stretches the distance of the branch by having PC-relative addressing refer to the number of
  words to the next instruction instead of the number of bytes.

As soon as I read that, I went over to the MARS Simulator to see that in practise. To my surprise, I observed that the $pc register doesn't follow that rule and has always the byte memory address stored.

Shouldn't the $pc register be something like this before the execution of the below instructions located in the instruction addresses?

Instruction Address |    $pc Content
                    |
    0x00400000      |     0x00100000
    0x00400004      |     0x00100001
    0x00400008      |     0x00100002
      ....          |         ....


问:
Align image in center and middle within div
I have following div

```<code><div id="over" style="position:absolute; width:100%; height:100%>
 <img src="img.png">
</div>
</code>```

How to align the image so as to be located in the middle and center of div ?

答:
This worked for me when you have to center align image and your parent div to image has covers whole screen. i.e. height:100% and width:100%</p>

```<code>#img{
    position:absolute;
    top:50%;
    left:50%;
    transform:translate(-50%,-50%);
}
</code>```

Body:
I have following div

How to align the image so as to be located in the middle and center of div ?

Body:
This worked for me when you have to center align image and your parent div to image has covers whole screen. i.e. height:100% and width:100%

#img{
    position:absolute;
    top:50%;
    left:50%;
    transform:translate(-50%,-50%);
}


问:
How can I enlarge font-size on phone navigation screen?
On-screen information like miles, time remaining and ETA (Estimated Time of Arrival)  are too small to be readable on Google Maps (tested on Samsung Galaxy S9). This is a recent change [for the worse] that I have I discovered in Google Maps. Has anyone else experienced this issue or/and found a way to resolve it?

I tried adjusting application and phone system settings, but without any success.

I need to have ETA information that is accessibly-sized.

Any help would be appreciated

答:
You may adjust the size of the labels of the map by following these steps:

On your Android phone or tablet, open the Settings app

Tap Accessibility. From here, you can:

Change font size: To make words larger, tap Font size, and then set your preferred letter size.

Change display size: To make items on your screen larger, tap Display size, and then set your preferred icon size.

You may also refer to this link for more information


问:
Add value to dynamically populated list c#
I'm constructing a web page based on ASN.NET MVC3 with Razor templates and Entity. The task is to populate a @Html.DropDownList from the database, so far so good but now I want to insert a static value in the DropDownList.

The code looks as follows

The create method

```<code>public ActionResult Create()
{
    var parents = db.Organizations.OrderBy(o => o.Title).ToList();
    var organization = new Organization();
    return View(organization);
}
</code>```

Extract from the Razor template

```<code><div class="editor-field">
    @Html.DropDownList("ParentGuid",
    new SelectList(ViewBag.Organizations as System.Collections.IEnumerable,
    "ParentGuid", "Title", Model.ParentGuid))
</div>
</code>```

So, the above code works but Im stuck in figuring out how to insert an empty row in the dropdown.

答:
I am not much familiarize with @ however, if you tried the overload?

```<code>@Html.DropDownList("ParentGuid",
    new SelectList(ViewBag.Organizations as System.Collections.IEnumerable,
    "ParentGuid", "Title", Model.ParentGuid), "Your empty option text here")
</code>```

Body:
I'm constructing a web page based on ASN.NET MVC3 with Razor templates and Entity. The task is to populate a @Html.DropDownList from the database, so far so good but now I want to insert a static value in the DropDownList.

The code looks as follows

The create method

public ActionResult Create()
{
    var parents = db.Organizations.OrderBy(o => o.Title).ToList();
    var organization = new Organization();
    return View(organization);
}

Extract from the Razor template

    @Html.DropDownList("ParentGuid",
    new SelectList(ViewBag.Organizations as System.Collections.IEnumerable,
    "ParentGuid", "Title", Model.ParentGuid))

So, the above code works but Im stuck in figuring out how to insert an empty row in the dropdown.

Body:
I am not much familiarize with @ however, if you tried the overload?

@Html.DropDownList("ParentGuid",
    new SelectList(ViewBag.Organizations as System.Collections.IEnumerable,
    "ParentGuid", "Title", Model.ParentGuid), "Your empty option text here")


答:
Here's a simple (perhaps too simple?) approach that focuses on the embedded JSON objects that have a "#text" attribute:

```<code>["#text", "@x", "@y"],       # the header
( ..
  | objects
  | select(has("#text"))
  | [.["#text", "@x", "@y"]] # a row
)
| @csv
</code>```

When given this program and the sample input, an invocation of jq using the -r option would produce:

```<code>"#text","@x","@y"
"Text1","121.10","83.42"
"Text2","121.10","124.82"
"Text3","85.10","69.62"
"Text4","85.10","83.42"
"Text5","85.10","97.22"
</code>```

If you don't want the quotation marks and are willing to risk that the output is not strictly CSV, then one option would be to use join(",") instead of @csv at the end of the pipeline.

Variants

You might want to use @tsv instead of @csv.

If a more restrictive approach to selecting the relevant embedded objects is needed, then perhaps replacing .. with .. | .text? will suffice.

If not, additional filters can be added depending on the detailed requirements.

Title: Parsing Json file with jq tool

Body:
I Have the following nested json file which I want to parse with jq tool and print in table form like I show at the end

The input.json structure is like this:

{
 "document":{
  "page":[
     {
        "@index":"0",
        "image":{
           "@data":"ABC",
           "@format":"png",
           "@height":"620.00",
           "@type":"base64encoded",
           "@width":"450.00",
           "@x":"85.00",
           "@y":"85.00"
        }
     },
     {
        "@index":"1",
        "row":[
           {
              "column":[
                 {
                    "text":""
                 },
                 {
                    "text":{
                       "#text":"Text1",
                       "@fontName":"Arial",
                       "@fontSize":"12.0",
                       "@height":"12.00",
                       "@width":"71.04",
                       "@x":"121.10",
                       "@y":"83.42"
                    }
                 }
              ]
           },
           {
              "column":[
                 {
                    "text":""
                 },
                 {
                    "text":{
                       "#text":"Text2",
                       "@fontName":"Arial",
                       "@fontSize":"12.0",
                       "@height":"12.00",
                       "@width":"101.07",
                       "@x":"121.10",
                       "@y":"124.82"
                    }
                 }
              ]
           }
        ]
     },
     {
        "@index":"2",
        "row":[
           {
              "column":{
                 "text":{
                    "#text":"Text3",
                    "@fontName":"Arial",
                    "@fontSize":"12.0",
                    "@height":"12.00",
                    "@width":"363.44",
                    "@x":"85.10",
                    "@y":"69.62"
                 }
              }
           },
           {
              "column":{
                 "text":{
                    "#text":"Text4",
                    "@fontName":"Arial",
                    "@fontSize":"12.0",
                    "@height":"12.00",
                    "@width":"382.36",
                    "@x":"85.10",
                    "@y":"83.42"
                 }
              }
           },
           {
              "column":{
                 "text":{
                    "#text":"Text5",
                    "@fontName":"Arial",
                    "@fontSize":"12.0",
                    "@height":"12.00",
                    "@width":"435.05",
                    "@x":"85.10",
                    "@y":"97.22"
                 }
              }
           }
        ]
     },
     {
        "@index":"3"
     }
  ]
 }
}

Following the answers of the following question (Parsing nested json with jq) I've tried this code but doesn't work

$ cat file.json | jq .document.page[].row | ["#text", "@x", "@y"] | @csv

The output I'm trying to get is:

#text @x     @y
Text1 121.10 83.42
Text2 121.10 124.82
Text3 65.10  69.62
Text4 85.10  83.42
Text5 85.10  97.22

How can achieve this?

Thanks

UPDATE

Thanks so much for the help. I've tried with a real file a bit longer.

I was able to adapt the first peak's solution like below:

["#text", "@data", "@fontName", "@fontSize", "@format", "@height", "@type", "@width", "@x", "@y"],
( ..
| objects
| select(has("#text","@data"))
| [.["#text", "@data", "@fontName", "@fontSize", "@format", "@height", "@type", "@width", "@x", "@y"]]
)
| @tsv

and with new input I get this table:

+---------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| #text         | @data | @fontName | @fontSize | @format | @height | @type         | @width | @x     | @y     |
+---------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
|               | ABC   |           |           | png     | 620     | base64encoded | 450    | 85     | 85     |
+---------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| Text ä 1      |       | Tahoma    | 12        |         | 12      |               | 427.79 | 85.1   | 69.62  |
+---------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| Text ¢76      |       | Tahoma    | 12        |         | 12      |               | 270.5  | 85.1   | 690.72 |
+---------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| Text % 5      |       | Tahoma    | 12        |         | 12      |               | 130.84 | 358.86 | 690.72 |
+---------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| Text 7Ç8      |       | Tahoma    | 12        |         | 12      |               | 115.95 | 85.1   | 704.52 |
+---------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| Text • 2 Wñ79 |       | Tahoma    | 8         |         | 8.04    |               | 398.16 | 121.1  | 68.06  |
+---------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| Text          |       | Tahoma    | 12        |         | 12      |               | 101.5  | 85.1   | 83.42  |
|   » 1 A\\\\CÓ |       |           |           |         |         |               |        |        |        |
+---------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| Text 12       |       | Tahoma    | 12        |         | 12      |               | 312.26 | 189.83 | 83.42  |
+---------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| Text 82       |       | Tahoma    | 12        |         | 12      |               | 44.99  | 85.1   | 97.22  |
+---------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| Text 31       |       | Tahoma    | 8         |         | 8.04    |               | 381.83 | 133.1  | 95.66  |
+---------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+

If possible, how to add the follwing 3 columns (counter, page and row) to know the corresponding page and row for each line?

The expected output would be like this:

+-------+------+-----+-------------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| counter | page | row | #text             | @data | @fontName | @fontSize | @format | @height | @type         | @width | @x     | @y     |
+-------+------+-----+-------------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| 1     | 0    |     |                   | ABC   |           |           | png     | 620     | base64encoded | 450    | 85     | 85     |
+-------+------+-----+-------------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| 2     | 1    | 0   | Text ä 1          |       | Tahoma    | 12        |         | 12      |               | 427.79 | 85.1   | 69.62  |
+-------+------+-----+-------------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| 3     | 1    | 1   | Text ¢76          |       | Tahoma    | 12        |         | 12      |               | 270.5  | 85.1   | 690.72 |
+-------+------+-----+-------------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| 4     | 1    | 1   | Text % 5          |       | Tahoma    | 12        |         | 12      |               | 130.84 | 358.86 | 690.72 |
+-------+------+-----+-------------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| 5     | 2    | 2   | Text 7Ç8          |       | Tahoma    | 12        |         | 12      |               | 115.95 | 85.1   | 704.52 |
+-------+------+-----+-------------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| 6     | 2    | 0   | Text • 2 Wñ79     |       | Tahoma    | 8         |         | 8.04    |               | 398.16 | 121.1  | 68.06  |
+-------+------+-----+-------------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| 7     | 2    | 1   | Text  » 1 A\\\\CÓ |       | Tahoma    | 12        |         | 12      |               | 101.5  | 85.1   | 83.42  |
+-------+------+-----+-------------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| 8     | 2    | 1   | Text 12           |       | Tahoma    | 12        |         | 12      |               | 312.26 | 189.83 | 83.42  |
+-------+------+-----+-------------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| 9     | 2    | 2   | Text 82           |       | Tahoma    | 12        |         | 12      |               | 44.99  | 85.1   | 97.22  |
+-------+------+-----+-------------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| 10    | 2    | 2   | Text 31           |       | Tahoma    | 8         |         | 8.04    |               | 381.83 | 133.1  | 95.66  |
+-------+------+-----+-------------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+

This is new more representative input file input2.json.

And seeing the Json structure in image below gives and idea about page number and row number present in json file and values within them.

Body:
Here's a simple (perhaps too simple?) approach that focuses on the embedded JSON objects that have a "#text" attribute:

["#text", "@x", "@y"],       # the header
( ..
  | objects
  | select(has("#text"))
  | [.["#text", "@x", "@y"]] # a row
)
| @csv

When given this program and the sample input, an invocation of jq using the -r option would produce:

"#text","@x","@y"
"Text1","121.10","83.42"
"Text2","121.10","124.82"
"Text3","85.10","69.62"
"Text4","85.10","83.42"
"Text5","85.10","97.22"

If you don't want the quotation marks and are willing to risk that the output is not strictly CSV, then one option would be to use join(",") instead of @csv at the end of the pipeline.

Variants

You might want to use @tsv instead of @csv.

If a more restrictive approach to selecting the relevant embedded objects is needed, then perhaps replacing .. with .. | .text? will suffice.

If not, additional filters can be added depending on the detailed requirements.


问:
Keycloak/OIDC : retrieve user groups attributes
I've extracted a user's groups information from the OIDC endpoint of Keycloak, but they don't come with the group ATTRIBUTES I defined (see Attributes tab into the group form, near Settings). Is there a claim to add to my request?

I'm using a RESTeasy client to reach Keycloak's admin API (had much better results than using the provided admin client, yet):

@Path("/admin/realms/{realm}")
public interface KeycloakAdminService {
    @GET
    @Path("/users/{id}/groups")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    List<GroupRepresentation> getUserGroups(@PathParam("realm") String realm, @PathParam("id") String userId,
                                            @HeaderParam(AUTHORIZATION) String accessToken);
    //DEBUG the access token must always be prefixed by "Bearer "
}
```

<p>So I can fetch a user's groups:</p>

<pre class="lang-java prettyprint-override"><code>private void fetchUserGroups(UserInfoOIDC infos, String userId) {
    log.info("Fetching user groups from {}...", getRealm());
    try {
        KeycloakAdminService proxy = kcTarget.proxy(KeycloakAdminService.class);
        AccessTokenResponse response = authzClient.obtainAccessToken(getAdminUsername(), getAdminPassword());
        List<GroupRepresentation> groups = proxy.getUserGroups(getRealm(), userId,
                "Bearer " + response.getToken());
        infos.importUserGroups(groups); //DEBUG here we go!
    } catch (WebApplicationException e) {
        log.error("User groups failure on {}: {}", getRealm(), e.getMessage());
    }
}
</code>```

But when it comes to data exploration, it turns out that no attributes are provided into the GroupRepresentation#getAttributes structure.

I've read that claims can be added to user info requests. Does it work on the admin API? How can I achieve that result with RESTeasy templates?
Thx

答:
I was able to achieve this by adding groups/roles info in token other claims property:

For this in keycloak config, go to your client -> mappers & add a group/role mapper. E.g.

Now this info will start coming in your access token:

To access these group attribute in Java you can extract it from otherclaims property of accesstoken. E.g.:

```<code>KeycloakSecurityContext keycloakSecurityContext = (KeycloakSecurityContext)(request.getAttribute(KeycloakSecurityContext.class.getName()));
AccesToken token = keycloakSecurityContext.getToken();
</code>```

In below image you can see that otherclaims property of token is filled with groups attribute that we created on keycloak. Note that if we had named "token claim property" as groupXYZ, the otherclaims would be showing:
groupsXYZ=[Administrator]

Body:
I've extracted a user's groups information from the OIDC endpoint of Keycloak, but they don't come with the group ATTRIBUTES I defined (see Attributes tab into the group form, near Settings). Is there a claim to add to my request?

I'm using a RESTeasy client to reach Keycloak's admin API (had much better results than using the provided admin client, yet):

@Path("/admin/realms/{realm}")
public interface KeycloakAdminService {
    @GET
    @Path("/users/{id}/groups")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    List<GroupRepresentation> getUserGroups(@PathParam("realm") String realm, @PathParam("id") String userId,
                                            @HeaderParam(AUTHORIZATION) String accessToken);
    //DEBUG the access token must always be prefixed by "Bearer "
}

So I can fetch a user's groups:

private void fetchUserGroups(UserInfoOIDC infos, String userId) {
    log.info("Fetching user groups from {}...", getRealm());
    try {
        KeycloakAdminService proxy = kcTarget.proxy(KeycloakAdminService.class);
        AccessTokenResponse response = authzClient.obtainAccessToken(getAdminUsername(), getAdminPassword());
        List<GroupRepresentation> groups = proxy.getUserGroups(getRealm(), userId,
                "Bearer " + response.getToken());
        infos.importUserGroups(groups); //DEBUG here we go!
    } catch (WebApplicationException e) {
        log.error("User groups failure on {}: {}", getRealm(), e.getMessage());
    }
}

But when it comes to data exploration, it turns out that no attributes are provided into the GroupRepresentation#getAttributes structure.

I've read that claims can be added to user info requests. Does it work on the admin API? How can I achieve that result with RESTeasy templates?
Thx

Body:
I was able to achieve this by adding groups/roles info in token other claims property:

For this in keycloak config, go to your client -> mappers & add a group/role mapper. E.g.

Now this info will start coming in your access token:

To access these group attribute in Java you can extract it from otherclaims property of accesstoken. E.g.:

KeycloakSecurityContext keycloakSecurityContext = (KeycloakSecurityContext)(request.getAttribute(KeycloakSecurityContext.class.getName()));
AccesToken token = keycloakSecurityContext.getToken();

In below image you can see that otherclaims property of token is filled with groups attribute that we created on keycloak. Note that if we had named "token claim property" as groupXYZ, the otherclaims would be showing:
groupsXYZ=[Administrator]


问:
How do I auto renew my AWS certificate and why wont it accept the new one I assigned?
I have setup AWS to manage my SSL through ACM. I use ELB to route my traffic from HTTP to HTTPS. I am trying to renew an expired certificate. I created a new one got it validated through DNS and then assigned it via ELB. But it will still not show up when going to my site: dreamprojects.co

Any help troubleshooting is much appreciated.

Tried renewing the cert a few times. added *.dreamprojects.co and *.www.dreamproject.co but it didn't help.

答:
Is dreamprojects.co your domain or you have mentioned as an example here?
This doesn't seem like to point to ELB but directly pointed to EC2 instance.

dig dreamprojects.co +short
  13.59.145.97

The cert presented when accessing dreamprojects.co issued by Lets Encrypt and expired.
ELB provides DNS name which you need to add it as a CNAME record because IP gets changed.


问:
Localstorage is cleared when i'm doing this.router.navigate
I'm developing a website with Angular 5 + Typescript.
I use the localStorage to store the JWT Token for the login.

When i'm clicking in a link ( Home or another ) , I use a function like this one :

```<code>public toHome() {
    this.router.navigate(['']);
}
</code>```

After clicking on the link, my localStorage and my sessionStorage is cleared and so my user is disconnected.

Who can help me please ?
thanks you

答:
dont use routing in html file, instead you can use Router function while form submition in component.ts file as like :-
this.router.navigate(['/path']);

and dont forget to import Router file and include it in constructor.

Body:
I'm developing a website with Angular 5 + Typescript.
I use the localStorage to store the JWT Token for the login.

When i'm clicking in a link ( Home or another ) , I use a function like this one :

public toHome() {
    this.router.navigate(['']);
}

After clicking on the link, my localStorage and my sessionStorage is cleared and so my user is disconnected.

Who can help me please ?
thanks you


答:
You are removed element from source array , that's why you getting exception so use new array for your filtered values

Problem at below line

```<code>array.remove(obj)
</code>```

Solution :

```<code>val positionsForRemove = ArrayList<Int>(),
val array = Singleton.array
if (array!!.size() > 0) {
   for (i in 0 until array.size()) {
     val obj = array.get(i).asJsonObject
     if (obj.get("filename").toString().substring(1, obj.get("filename").toString().length - 1) == mNames[position])
       positionsForRemove.add(position)
    }
   for(position in positionsForRemove){
          array.remove(position)
          mNames.remove(position)
        }
  Singleton.array = array
  updateNames(mNames)

}
</code>```

Title: Why I'm getting java.lang.IndexOutOfBoundsException when I try to get an item of jsonArray?

Body:
You are removed element from source array , that's why you getting exception so use new array for your filtered values

Problem at below line

array.remove(obj)

Solution :

val positionsForRemove = ArrayList<Int>(),
val array = Singleton.array
if (array!!.size() > 0) {
   for (i in 0 until array.size()) {
     val obj = array.get(i).asJsonObject
     if (obj.get("filename").toString().substring(1, obj.get("filename").toString().length - 1) == mNames[position])
       positionsForRemove.add(position)
    }
   for(position in positionsForRemove){
          array.remove(position)
          mNames.remove(position)
        }
  Singleton.array = array
  updateNames(mNames)

}


问:
The best way to model a one-to-many relationship in hibernate
I am new to hibernate,
According to the article below it seems that the best way to map relationships is unidirectionally in most of the cases other than special cases like Q and A application where  the number of child entities is limited.

Link -
https://www.callicoder.com/hibernate-spring-boot-jpa-one-to-many-mapping-example/

Is this correct?? I want to clear my doughts and start my ralationship mappings.

答:
Unidirectional or bi-directional, it all depends on your requirements.
For example :-
   A and B are two entities :
   1>A has one-one unidirectional relationship with B, This is a scenario where you do not
     need/want to load A when you are loading B.
   2>If you want to load A when you are loading B , then you will require One-One bi-
    directional mapping.</p>


问:
Selecting fields from different table
I have 3 tables. Order, Orderlines and Stores. In Order table has StoreId which is a foreign key from Stores table and In Orderlines table has OrderId a foreign key from Order table. I only need to get the fields Order.OrderId, Order.WarehouseOrderId, Store.StoreName and the count of Orderlines per Order. So currently this is my implementation:

```<code>public List<Order> GetOrdersDashboardWithoutStatus1(SearchDashboardCriteria cri)
{
    using (var ctx = CreateDbContext())
    {
        var orders = (from items in ctx.Orders select items);
        if (cri.MerchantId != 0)
        {
            orders = orders.Where(x => x.Store.MerchantId == cri.MerchantId);
        }

        return orders.Where(x => (DbFunctions.TruncateTime(x.DateImported) >= DbFunctions.TruncateTime(cri.StartDate))
                && (DbFunctions.TruncateTime(x.DateImported) <= DbFunctions.TruncateTime(cri.EndDate)))
                 .Include(x => x.Store).Include(x => x.OrderLines).ToList();
    }
}
</code>```

Through the currently implementation is working but the performance is very slow and sometimes it gets a Time Out error because a records may have 30K+ orders.

答:
You could try something like this

```<code>using (var ctx = CreateDbContext())
{
            var orders = (from x in ctx.Orders
                          where x.Store.MerchantId == cri.MerchantId
                          && add your other where condition
                          select NewDataModel
                          {
                            orderId = x.OrderId,
                            wareHouse = x.WarehouseOrderId,
                            storeName = x.Store.StoreName
                          }).ToArray();

}
</code>```

Anonymous projection or projection to your custom model only retrieve columns that are included in the projection.

Instead of Select * from Orders ... it will be Select OrderId,WareHouseOrderId from Orders

you can also try for paging (Take,skip) if your use case support it.
Similar answer for anonymous projection

Title: Selecting fields from different table

Body:
I have 3 tables. Order, Orderlines and Stores. In Order table has StoreId which is a foreign key from Stores table and In Orderlines table has OrderId a foreign key from Order table. I only need to get the fields Order.OrderId, Order.WarehouseOrderId, Store.StoreName and the count of Orderlines per Order. So currently this is my implementation:

public List<Order> GetOrdersDashboardWithoutStatus1(SearchDashboardCriteria cri)
{
    using (var ctx = CreateDbContext())
    {
        var orders = (from items in ctx.Orders select items);
        if (cri.MerchantId != 0)
        {
            orders = orders.Where(x => x.Store.MerchantId == cri.MerchantId);
        }

        return orders.Where(x => (DbFunctions.TruncateTime(x.DateImported) >= DbFunctions.TruncateTime(cri.StartDate))
                && (DbFunctions.TruncateTime(x.DateImported) <= DbFunctions.TruncateTime(cri.EndDate)))
                 .Include(x => x.Store).Include(x => x.OrderLines).ToList();
    }
}

Through the currently implementation is working but the performance is very slow and sometimes it gets a Time Out error because a records may have 30K+ orders.

Body:
You could try something like this

using (var ctx = CreateDbContext())
{
            var orders = (from x in ctx.Orders
                          where x.Store.MerchantId == cri.MerchantId
                          && add your other where condition
                          select NewDataModel
                          {
                            orderId = x.OrderId,
                            wareHouse = x.WarehouseOrderId,
                            storeName = x.Store.StoreName
                          }).ToArray();

}

Anonymous projection or projection to your custom model only retrieve columns that are included in the projection.

Instead of Select * from Orders ... it will be Select OrderId,WareHouseOrderId from Orders

you can also try for paging (Take,skip) if your use case support it.
Similar answer for anonymous projection