问:
SQL nested query with join operations
I have a table P with person1id and person2id columns, and a table J with each person's personId and their name columns. I want to have a query that generates a table of person1id, person2id, name1, name2 columns. In the result, name1 is the name of person1id, name2 is the name of person2id.  Is it possible to do this via nested query?

The tables look like below

table P

person1id
person2id

p1_1
p2_1

p1_2
p2_2

table J

personId
name

p1_1
name1

p1_2
name2

p2_1
name3

p2_2
name4

The expected result looks like

person1id
person2id
name1
name2

p1_1
p2_1
name1
name3

p1_2
p2_2
name2
name4

答:
You can try to use join with condition aggregate function, the CASE WHEN condition depends on your new column logic which is your expectation.

Query #1

```<code>SELECT person1id,
       person2id,
       MAX(CASE WHEN personId IN ('p1_1','p1_2') THEN name END) name1,
       MAX(CASE WHEN personId IN ('p2_1','p2_2') THEN name END) name2
FROM P
INNER JOIN J ON personId IN (P.person1id,P.person2id)
GROUP BY person1id,
       person2id;
</code>```

person1id
person2id
name1
name2

p1_1
p2_1
name1
name3

p1_2
p2_2
name2
name4

View on DB Fiddle

Title: SQL nested query with join operations

Body:
You can try to use join with condition aggregate function, the CASE WHEN condition depends on your new column logic which is your expectation.

Query #1

SELECT person1id,
       person2id,
       MAX(CASE WHEN personId IN ('p1_1','p1_2') THEN name END) name1,
       MAX(CASE WHEN personId IN ('p2_1','p2_2') THEN name END) name2
FROM P
INNER JOIN J ON personId IN (P.person1id,P.person2id)
GROUP BY person1id,
       person2id;

person1id
person2id
name1
name2

p1_1
p2_1
name1
name3

p1_2
p2_2
name2
name4

View on DB Fiddle


来源: stackexchange

答:
Negative lookahead is not support in Go's regular expressions. See the question, Negative look-ahead in Go regular expressions

Might want to look at using the package cidranger instead.

ContentLicense: CC BY-SA 4.0

Title: How to exclude particular IPV4 addresses using regex in Go?

Body:
I am able to use negative lookahead in Javascript to not match certain IPs like 127.0.0.1 but I am unable to use the same for my microservice that runs in Go.

This is the regex I use in Javascript -

^(?!127\.0\.0\.1)(([1-9])|([1-9][0-9])|([1][0-9][0-9])|(2[0-1][0-9])|(22[0-3]))\.(((([0-9])|([1-9][0-9])|([1][0-9][0-9])|(2[0-4][0-9])|(25[0-5]))\.){2})(([1-9])|([1-9][0-9])|([1][0-9][0-9])|(2[0-4][0-9])|(25[0-5]))$


问:
Find oldest email via PowerShell
I found multiple posts regarding this topic, but I don't think they are correct.

The following script works great if you want to find the earliest/oldest item (which for my luck, it is a contact).

```<code>Get-MailboxFolderStatistics -IncludeOldestAndNewestItems -Identity USERID |
    Where OldestItemReceivedDate -ne $null |
    Sort OldestItemReceivedDate |
    Select -First 1 OldestItemReceivedDate
</code>```

I want to find the earliest.. first email someone received.  So someone helped me creating the following:

```<code># Get the folder statistics for all folders
$stats = Get-MailboxFolderStatistics -IncludeOldestAndNewestItems -Identity $USERID

# Get the oldest email. Can re-use $stats for the other item types
$OldestEmail = $stats |
  Where-Object {$_.OldestItemReceivedDate -and $_.ContainerClass -eq 'IPF.Note'} |
  Sort-Object OldestItemReceivedDate |
  Select-Object ContainerClass,OldestItemReceivedDate,FolderPath -First 1

# Outputs
ContainerClass OldestItemReceivedDate FolderPath
-------------- ---------------------- ----------
IPF.Note       2/8/2016 2:07:50 PM    /Inbox
</code>```

That previous script works great, if... the email is not on the Purge folder.  For some reason, when the emails are moved to the Purge folder, the ContainerClass is also removed.  I know there is an email prior to 2/8/2016, but it is on the -Archive \Recoverable Items\ Purge

答:
If all you're doing is trying to avoid contact matching, change your ContainerClass to:

```<code>$_.ContainerClass -ne 'IPF.Contact'
</code>```

That way you won't exclude the Purges folder. Alternatively you could adjust it to:

```<code>-and (($_.ContainerClass -eq 'IPF.Note') -or ($_.FolderPath -match "Purges"))
</code>```

edit: I can't make comments to reply to you yet sorry, but yes Purges has no ContainerClass. It'll still proceed just fine with the 1st option (because a $null containerclass is still not equal to 'IPF.Contact'). Did you need to include contacts in the search?

Title: Find oldest email via PowerShell

Body:
I found multiple posts regarding this topic, but I don't think they are correct.

The following script works great if you want to find the earliest/oldest item (which for my luck, it is a contact).

Get-MailboxFolderStatistics -IncludeOldestAndNewestItems -Identity USERID |
    Where OldestItemReceivedDate -ne $null |
    Sort OldestItemReceivedDate |
    Select -First 1 OldestItemReceivedDate

I want to find the earliest.. first email someone received.  So someone helped me creating the following:

# Get the folder statistics for all folders
$stats = Get-MailboxFolderStatistics -IncludeOldestAndNewestItems -Identity $USERID

# Get the oldest email. Can re-use $stats for the other item types
$OldestEmail = $stats |
  Where-Object {$_.OldestItemReceivedDate -and $_.ContainerClass -eq 'IPF.Note'} |
  Sort-Object OldestItemReceivedDate |
  Select-Object ContainerClass,OldestItemReceivedDate,FolderPath -First 1

# Outputs
ContainerClass OldestItemReceivedDate FolderPath
-------------- ---------------------- ----------
IPF.Note       2/8/2016 2:07:50 PM    /Inbox

That previous script works great, if... the email is not on the Purge folder.  For some reason, when the emails are moved to the Purge folder, the ContainerClass is also removed.  I know there is an email prior to 2/8/2016, but it is on the -Archive \Recoverable Items\ Purge

Body:
If all you're doing is trying to avoid contact matching, change your ContainerClass to:

$_.ContainerClass -ne 'IPF.Contact'

That way you won't exclude the Purges folder. Alternatively you could adjust it to:

-and (($_.ContainerClass -eq 'IPF.Note') -or ($_.FolderPath -match "Purges"))

edit: I can't make comments to reply to you yet sorry, but yes Purges has no ContainerClass. It'll still proceed just fine with the 1st option (because a $null containerclass is still not equal to 'IPF.Contact'). Did you need to include contacts in the search?


问:
How to Remove selected item from listbox C#
i currently trying to view all the files and folder selected by the user in a listbox. At the Moment i am able to list what the user have chosen using the openfiledialogue HOWEVER i am now facing prob when i try to remove it form the listbox. i trying to allow the user to click on the checkbox beside the file and press the remove button to remove it

this is my code for remove button

```<code>      private void button2_Click(object sender, EventArgs e)
    {
        for (int i = listView1.SelectedItems.Count - 1; i >= 0; i--)
        {
            listView1.Items.Remove(listView1.SelectedItems[i]);
        }

    }
</code>```

this is the add file to listbox for reference jsut in case

```<code>    private void button1_Click(object sender, EventArgs e)
    {

        OpenFileDialog openfiledialog = new OpenFileDialog();
        // Display open file dialog
        openfiledialog.InitialDirectory = "C:\\";
        //openfiledialog.Multiselect = true;
        openfiledialog.Title = "Lock File";
        openfiledialog.Filter = "All Files | *.*";
        openfiledialog.ShowDialog();

        if (openfiledialog.FileName != "")
        {

        //move through FileInfo array and store in new array of fi
            listView1.Items.Clear();
            foreach (string file in openfiledialog.FileNames)
            {
                listView1.Items.Add(file);
            }
        }

    }
</code>```

and i pressed the remove button nothing happen and i saw some answer on google on the using of selectionmode but when i used that, my listbox does not have the property of selectionmode and have red lines underlined

答:
Try this</p>

```<code>   private void button2_Click(object sender, EventArgs e)
        {
           for(int i = 0 ; i < listView1.SelectedItems.Count; i ++)
               listView1.Items.Remove(listView1.SelectedItems[i]);

        }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
i currently trying to view all the files and folder selected by the user in a listbox. At the Moment i am able to list what the user have chosen using the openfiledialogue HOWEVER i am now facing prob when i try to remove it form the listbox. i trying to allow the user to click on the checkbox beside the file and press the remove button to remove it

this is my code for remove button

      private void button2_Click(object sender, EventArgs e)
    {
        for (int i = listView1.SelectedItems.Count - 1; i >= 0; i--)
        {
            listView1.Items.Remove(listView1.SelectedItems[i]);
        }

    }

this is the add file to listbox for reference jsut in case

    private void button1_Click(object sender, EventArgs e)
    {

        OpenFileDialog openfiledialog = new OpenFileDialog();
        // Display open file dialog
        openfiledialog.InitialDirectory = "C:\\";
        //openfiledialog.Multiselect = true;
        openfiledialog.Title = "Lock File";
        openfiledialog.Filter = "All Files | *.*";
        openfiledialog.ShowDialog();

        if (openfiledialog.FileName != "")
        {

        //move through FileInfo array and store in new array of fi
            listView1.Items.Clear();
            foreach (string file in openfiledialog.FileNames)
            {
                listView1.Items.Add(file);
            }
        }

    }

and i pressed the remove button nothing happen and i saw some answer on google on the using of selectionmode but when i used that, my listbox does not have the property of selectionmode and have red lines underlined

Body:
Try this

   private void button2_Click(object sender, EventArgs e)
        {
           for(int i = 0 ; i < listView1.SelectedItems.Count; i ++)
               listView1.Items.Remove(listView1.SelectedItems[i]);

        }


问:
Typescript not throwing error for callback return type mismatch
CONTEXT :

I have a callback for handling onChange event and a react component using this callback.

For this example, the return types of the callback is a 'string' and the return type expected in the type of the handle change props component is 'void'

QUESTION :

Why am i not getting error's even when the return types are different ?

答:
You don't get an error because one type is compatible with the other.

<Difficulties handleChange> does NOT use the return value of the handler (it's claimed with the void keyword), thus you can basically put there a handler which returns whatever you like, it's all acceptable and TS won't complain.


问:
Remove all elements in a IList that contains any of the other List's elements
I have some strings in a IList as such:

IList - { "Apple", "Apple2" , Banana, Orange, "AppleBanana", Orange2, "Berries"};

I want to remove all of the elements that contains any elements from this list.
List - {"apple", "orange", "grape"}

I am expecting the IList to be returned as - {Banana, "Berries"}

```<code>            Food food1 = new Food();
            Fruits fruit1 = new Fruits();
            fruit1.Name = "Apple";
            food1.fruits.Add(fruit1);
            Fruits fruit2 = new Fruits();
            fruit1.Name = "Apple2";
            food1.fruits.Add(fruit2);
            Fruits fruit3 = new Fruits();
            fruit1.Name = "Banana";
            food1.fruits.Add(fruit3);
            Fruits fruit4 = new Fruits();
            fruit1.Name = "AppleBanana";
            food1.fruits.Add(fruit4);
            Fruits fruit5 = new Fruits();
            fruit1.Name = "Orange";
            food1.fruits.Add(fruit5);
            Fruits fruit6 = new Fruits();
            fruit1.Name = "Orange2";
            food1.fruits.Add(fruit6);
            Fruits fruit7 = new Fruits();
            fruit1.Name = "Berries";
            food1.fruits.Add(fruit7);
        }
        public class Food
        {
            public IList<Fruits> fruits;

            public Food()
            {
                fruits = new List<Fruits>();
            }
        }

        public class Fruits
        {
            public string Name;
        }
</code>```

答:
try this

```<code>var food = new Food(new string[] { "Apple", "Apple2", " Banana", "Orange", "AppleBanana", "Orange", "Berries" });

var fruitsToRemove = new String[] { "apple", "orange", "grape" };

food.Fruits = food.Fruits.Where(i => !fruitsToRemove.Contains(i.Name.ToLower())).ToList();
</code>```

classes

```<code>public class Food
{
    public List<Fruit> Fruits {get;set;} =new List<Fruit>();

    public Food(IEnumerable<string> fruits)
    {
        Fruits = fruits.Select(f => new Fruit {Name=f}).ToList();
    }
}

public class Fruit
{
    public string Name;
}
</code>```

Body:
I have some strings in a IList as such:

IList - { "Apple", "Apple2" , Banana, Orange, "AppleBanana", Orange2, "Berries"};

I want to remove all of the elements that contains any elements from this list.
List - {"apple", "orange", "grape"}

I am expecting the IList to be returned as - {Banana, "Berries"}

            Food food1 = new Food();
            Fruits fruit1 = new Fruits();
            fruit1.Name = "Apple";
            food1.fruits.Add(fruit1);
            Fruits fruit2 = new Fruits();
            fruit1.Name = "Apple2";
            food1.fruits.Add(fruit2);
            Fruits fruit3 = new Fruits();
            fruit1.Name = "Banana";
            food1.fruits.Add(fruit3);
            Fruits fruit4 = new Fruits();
            fruit1.Name = "AppleBanana";
            food1.fruits.Add(fruit4);
            Fruits fruit5 = new Fruits();
            fruit1.Name = "Orange";
            food1.fruits.Add(fruit5);
            Fruits fruit6 = new Fruits();
            fruit1.Name = "Orange2";
            food1.fruits.Add(fruit6);
            Fruits fruit7 = new Fruits();
            fruit1.Name = "Berries";
            food1.fruits.Add(fruit7);
        }
        public class Food
        {
            public IList<Fruits> fruits;

            public Food()
            {
                fruits = new List<Fruits>();
            }
        }

        public class Fruits
        {
            public string Name;
        }

Body:
try this

var food = new Food(new string[] { "Apple", "Apple2", " Banana", "Orange", "AppleBanana", "Orange", "Berries" });

var fruitsToRemove = new String[] { "apple", "orange", "grape" };

food.Fruits = food.Fruits.Where(i => !fruitsToRemove.Contains(i.Name.ToLower())).ToList();

classes

public class Food
{
    public List<Fruit> Fruits {get;set;} =new List<Fruit>();

    public Food(IEnumerable<string> fruits)
    {
        Fruits = fruits.Select(f => new Fruit {Name=f}).ToList();
    }
}

public class Fruit
{
    public string Name;
}


问:
can we get Reference of Date picker Dialog from DateSetListener?
Is there any way to get the reference of Date Picker Dialog from Date Set Listener as in its parameter has view of only Date Set Listener?</p>

```<code>  if(Type.equalsIgnoreCase("datepicker")
{ mField=new EditText(context);
((EditText) mField).setText("Pick Date");
ll.addView(mField);
mField.setOnClickListener(new View.OnClickListener()
 {
 @Override public void onClick(View v)
{
 final Calendar cal = Calendar.getInstance();
 mYear = cal.get(Calendar.YEAR);
mMonth = cal.get(Calendar.MONTH);
 mDay = cal.get(Calendar.DAY_OF_MONTH);
DatePickerDialogWithEditText dialog= new DatePickerDialogWithEditText(context, mdatepickerdialog , mYear, mMonth, mDay, (EditText)mField );
dialog.show(); } });
 } }
    private DatePickerDialogWithEditText.OnDateSetListener mdatepickerdialog = new DatePickerDialogWithEditText.OnDateSetListener()
{
public void onDateSet(DatePicker view , int year , int month, int date)
{
mYear = year; mMonth = month; mDay = date; EditText et = ((DatePickerDialogWithEditText.OnDateSetListener)this).getAssociatedTextView();
et.setText(new StringBuilder().append(mDay).append("-").append(mMonth).append("-").append(mYear)); } };
 }
    class DatePickerDialogWithEditText extends DatePickerDialog
{
 EditText tv;
DatePickerDialogWithEditText(Context c, OnDateSetListener oD, int y, int m, int d, EditText tv)
{
super(c, oD, y, m, d); this.tv = tv;
 }
 EditText getAssociatedTextView()
{
return tv;
}
}
</code>```

答:
here is the code:</p>

```<code>if(Type.equalsIgnoreCase("datepicker"))
        {
            mField=new EditText(context);
            ((EditText) mField).setText("Pick Date");
            ll.addView(mField);
            mField.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                    dialognew = new Mynewdialog(context);
                    dialognew.dialog_obj((EditText) mField);
                }
            });
        }
    }

    protected DatePickerDialogWithEditText.OnDateSetListener mdatepickerdialog = new DatePickerDialogWithEditText.OnDateSetListener()
    {
        public void onDateSet(DatePicker view , int year , int month, int date)
         {
             mYear = year;
             mMonth = month;
             mDay = date;
             dialognew.showdialogtext();

         }
     };
}

class DatePickerDialogWithEditText extends DatePickerDialog
{
    EditText tv;

    DatePickerDialogWithEditText(Context c, OnDateSetListener oD, int y, int m, int d, EditText tv)
    {
        super(c, oD, y, m, d);
        this.tv = tv;
    }

    EditText getAssociatedTextView()
    {
        return tv;
    }
}

class Mynewdialog
{
    private Context context;
    Display dis = new Display(context);
    private DatePickerDialogWithEditText dialog;

    public Mynewdialog(Context mcontext)
    {
        context=mcontext;
    }

    public void dialog_obj(EditText editTextView)
    {
        final Calendar cal = Calendar.getInstance();
        dis.mYear = cal.get(Calendar.YEAR);
        dis.mMonth = cal.get(Calendar.MONTH);
        dis.mDay = cal.get(Calendar.DAY_OF_MONTH);
        dialog = new DatePickerDialogWithEditText(context, dis.mdatepickerdialog, dis.mYear, dis.mMonth, dis.mDay, editTextView);
        dialog.show();
    }

    public void showdialogtext()
    {
        EditText et = dialog.getAssociatedTextView();
        et.setText(new StringBuilder().append(dis.mDay).append("-").append(dis.mMonth).append("-").append(dis.mYear));
    }
}
</code>```

Body:
Is there any way to get the reference of Date Picker Dialog from Date Set Listener as in its parameter has view of only Date Set Listener?

  if(Type.equalsIgnoreCase("datepicker")
{ mField=new EditText(context);
((EditText) mField).setText("Pick Date");
ll.addView(mField);
mField.setOnClickListener(new View.OnClickListener()
 {
 @Override public void onClick(View v)
{
 final Calendar cal = Calendar.getInstance();
 mYear = cal.get(Calendar.YEAR);
mMonth = cal.get(Calendar.MONTH);
 mDay = cal.get(Calendar.DAY_OF_MONTH);
DatePickerDialogWithEditText dialog= new DatePickerDialogWithEditText(context, mdatepickerdialog , mYear, mMonth, mDay, (EditText)mField );
dialog.show(); } });
 } }
    private DatePickerDialogWithEditText.OnDateSetListener mdatepickerdialog = new DatePickerDialogWithEditText.OnDateSetListener()
{
public void onDateSet(DatePicker view , int year , int month, int date)
{
mYear = year; mMonth = month; mDay = date; EditText et = ((DatePickerDialogWithEditText.OnDateSetListener)this).getAssociatedTextView();
et.setText(new StringBuilder().append(mDay).append("-").append(mMonth).append("-").append(mYear)); } };
 }
    class DatePickerDialogWithEditText extends DatePickerDialog
{
 EditText tv;
DatePickerDialogWithEditText(Context c, OnDateSetListener oD, int y, int m, int d, EditText tv)
{
super(c, oD, y, m, d); this.tv = tv;
 }
 EditText getAssociatedTextView()
{
return tv;
}
}

Body:
here is the code:

if(Type.equalsIgnoreCase("datepicker"))
        {
            mField=new EditText(context);
            ((EditText) mField).setText("Pick Date");
            ll.addView(mField);
            mField.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                    dialognew = new Mynewdialog(context);
                    dialognew.dialog_obj((EditText) mField);
                }
            });
        }
    }

    protected DatePickerDialogWithEditText.OnDateSetListener mdatepickerdialog = new DatePickerDialogWithEditText.OnDateSetListener()
    {
        public void onDateSet(DatePicker view , int year , int month, int date)
         {
             mYear = year;
             mMonth = month;
             mDay = date;
             dialognew.showdialogtext();

         }
     };
}

class DatePickerDialogWithEditText extends DatePickerDialog
{
    EditText tv;

    DatePickerDialogWithEditText(Context c, OnDateSetListener oD, int y, int m, int d, EditText tv)
    {
        super(c, oD, y, m, d);
        this.tv = tv;
    }

    EditText getAssociatedTextView()
    {
        return tv;
    }
}

class Mynewdialog
{
    private Context context;
    Display dis = new Display(context);
    private DatePickerDialogWithEditText dialog;

    public Mynewdialog(Context mcontext)
    {
        context=mcontext;
    }

    public void dialog_obj(EditText editTextView)
    {
        final Calendar cal = Calendar.getInstance();
        dis.mYear = cal.get(Calendar.YEAR);
        dis.mMonth = cal.get(Calendar.MONTH);
        dis.mDay = cal.get(Calendar.DAY_OF_MONTH);
        dialog = new DatePickerDialogWithEditText(context, dis.mdatepickerdialog, dis.mYear, dis.mMonth, dis.mDay, editTextView);
        dialog.show();
    }

    public void showdialogtext()
    {
        EditText et = dialog.getAssociatedTextView();
        et.setText(new StringBuilder().append(dis.mDay).append("-").append(dis.mMonth).append("-").append(dis.mYear));
    }
}


问:
Using SVD files from CMSIS for external ICs (e.g. connected via SPI or I2C)
I was wondering today if the SVD fileformat as well as the parser and code generation tools provided by CMSIS could be used to describe and generate headerfiles for an external IC (for example there are some rather complex battery management ics out there with tons of registers).

I am not expecting it to generate any logic but just register and command/address definitions.

The thought behind this questions is: At some point I need to spend the time to read the datasheet and translate it into a set of register and command definitions. Why not directly use a format that could be used to generate code also for other languages?

Edit:
Link to the SVD file format added

答:
Yes, you could generate header files from the SVD files.

svd2rust is one example of such usage.


问:
How to convert binary payload (file) to byte[] in java?
I receive json data that contains binary data like that ,and I would like to convert that data to byte[] in java but I don't know how ?.</p>

```<code>"payload": "7V1bcxs3ln6frfdcfvfbghfdX8HSw9Zu1QzzartyhblfdcvberCObjvJpkiJUpmhRI1pKXYeXHRsZLSrCy
5dElN5tfvQaO72TdSoiOS3TH8Yxdffgtg754679513qdfrgvlslsqdeqaepdccngrdzedrtghBD+d++e7v//p80/v96v7h+u72
+z1gfK/39x/+9t391cPTzeP88aE/++Fvvd53n+8+Xd1c/fBm/unqAf+7
N7v65en++vGP3vx2fvPHw/XDdwfpHf5mevhq/vQDcnAAwD+gEPwDF+bDxTv+3UF61d/4eesrfP356uFx"
</code>```

答:
In my case I had to convert payload that I knew it was a text something like:

{"payload":"eyJ1c2VyX2lkIjo0LCJ1c2VybmFtZSI6IngiLCJjaXR5IjoiaGVyZSJ9"}

This is the difference between java.util.Base64.getDecoder() and getBytes():

```<code>    String s = "eyJ1c2VyX2lkIjo0LCJ1c2VybmFtZSI6IngiLCJjaXR5IjoiaGVyZSJ9";
    byte [] bytes = s.getBytes();
    byte [] bytes_base64 = java.util.Base64.getDecoder().decode(s);
    String bytesToStr = new String(bytes, StandardCharsets.UTF_8);
    String bytesBase64Tostr = new String(bytes_base64, StandardCharsets.UTF_8);

    System.out.println("bytesToStr="+bytesToStr);
    System.out.println("bytesBase64Tostr="+bytesBase64Tostr);
</code>```

Output:

bytesToStr=eyJ1c2VyX2lkIjo0LCJ1c2VybmFtZSI6IngiLCJjaXR5IjoiaGVyZSJ9

bytesBase64Tostr={"user_id":4,"username":"x","city":"here"}

java.util.Base64.getDecoder() worked for in my case

Body:
I receive json data that contains binary data like that ,and I would like to convert that data to byte[] in java but I don't know how ?.

"payload": "7V1bcxs3ln6frfdcfvfbghfdX8HSw9Zu1QzzartyhblfdcvberCObjvJpkiJUpmhRI1pKXYeXHRsZLSrCy
5dElN5tfvQaO72TdSoiOS3TH8Yxdffgtg754679513qdfrgvlslsqdeqaepdccngrdzedrtghBD+d++e7v//p80/v96v7h+u72
+z1gfK/39x/+9t391cPTzeP88aE/++Fvvd53n+8+Xd1c/fBm/unqAf+7
N7v65en++vGP3vx2fvPHw/XDdwfpHf5mevhq/vQDcnAAwD+gEPwDF+bDxTv+3UF61d/4eesrfP356uFx"

Body:
In my case I had to convert payload that I knew it was a text something like:

{"payload":"eyJ1c2VyX2lkIjo0LCJ1c2VybmFtZSI6IngiLCJjaXR5IjoiaGVyZSJ9"}

This is the difference between java.util.Base64.getDecoder() and getBytes():

    String s = "eyJ1c2VyX2lkIjo0LCJ1c2VybmFtZSI6IngiLCJjaXR5IjoiaGVyZSJ9";
    byte [] bytes = s.getBytes();
    byte [] bytes_base64 = java.util.Base64.getDecoder().decode(s);
    String bytesToStr = new String(bytes, StandardCharsets.UTF_8);
    String bytesBase64Tostr = new String(bytes_base64, StandardCharsets.UTF_8);

    System.out.println("bytesToStr="+bytesToStr);
    System.out.println("bytesBase64Tostr="+bytesBase64Tostr);

Output:

bytesToStr=eyJ1c2VyX2lkIjo0LCJ1c2VybmFtZSI6IngiLCJjaXR5IjoiaGVyZSJ9

bytesBase64Tostr={"user_id":4,"username":"x","city":"here"}

java.util.Base64.getDecoder() worked for in my case


问:
Set JSChart visible x-axis
Is there a way to set the visible x-axis range in JSChart despite the range of the data set?

I use JSChart to draw a line chart. The x-axis is date. The y-axis is an integer value (from 0 to 100).
Let's save x-axis min value is 2000-1-1 and max value is 2010-12-31).
Is there way way to configure JSChart to show only the part of data say (2005-1-1 to 2006-1-1)?

I have tried doing

```<code>config.data = myData
config.options.scales.x.suggestedMin = start
config.options.scales.x.suggestedMax = end
</code>```

where start is 2005-1-1 and end is 2006-1-1. But JSChart still show my data from the beginning, i.e. 2000-1-1.

答:
see this ref:

suggestedMin  only change the data values that are used to scale the axis.

To change the explicit ends of the axis, use min and max.

Title: Set JSChart visible x-axis

Body:
Is there a way to set the visible x-axis range in JSChart despite the range of the data set?

I use JSChart to draw a line chart. The x-axis is date. The y-axis is an integer value (from 0 to 100).
Let's save x-axis min value is 2000-1-1 and max value is 2010-12-31).
Is there way way to configure JSChart to show only the part of data say (2005-1-1 to 2006-1-1)?

I have tried doing

config.data = myData
config.options.scales.x.suggestedMin = start
config.options.scales.x.suggestedMax = end

where start is 2005-1-1 and end is 2006-1-1. But JSChart still show my data from the beginning, i.e. 2000-1-1.


问:
Pandas: aggregate min, mean, and max of values from python list of nested dictionaries
I have a list of nested dictionaries in python with data that I want to analyze using pandas. Here's some example data:

```<code>[
  {
    "A": { "left": 1, "right": 2 },
    "B": { "left": 3, "right": 4 },
    "C": { "left": 5, "right": 6 },
  },
  {
    "A": { "left": 7, "right": 8 },
    "B": { "left": 9, "right": 10 },
    "C": { "left": 11, "right": 12 },
  },
  ...
]
</code>```

And so on. As the example shows, each item in the array is a dictionary with the same keys, and each key points to a dictionary with the same keys. In table form, I imagine it should look something like this:

```<code>|idx|A         |B         |C         |
|   |left|right|left|right|left|right|
--------------------------------------
| 0 |   1|    2|   3|    4|   5|    6|
| 1 |   7|    8|   9|   10|  11|   12|
| 2 | ...                            |
</code>```

What I want to do is aggregate the min, mean, and max of "left" and "right" across this list of dictionaries for each letter, so that it ends up with a DataFrame like this:

```<code>|idx|left_min|left_mean|left_max|right_min|right_mean|right_max|
----------------------------------------------------------------
| A |       1|        4|       7|        2|         5|        8|
| B |       3|        6|       9|        4|         7|       14|
| C |       5|        8|      11|        6|         9|       12|
</code>```

I'm experienced with python but relatively new to pandas, so I'm trying to get it right within a pandas framework before I just write it myself in python. I've tried many different ways to mold and shape pandas DataFrames into this form but I can't quite manage it. Every attempt I've made has either multi-indexed in strange ways, or can't aggregate properly. I feel like I'm missing something fundamental here. Any help is appreciated.

答:
Let's tackle this in steps.

pd.json_normalize

```<code>df = pd.json_normalize(data)

   A.left  A.right  B.left  B.right  C.left  C.right
0       1        2       3        4       5        6
1       7        8       9       10      11       12
</code>```

str.split for the multi index.

```<code>df.columns = df.columns.str.split('.',expand=True)

     A          B          C
  left right left right left right
0    1     2    3     4    5     6
1    7     8    9    10   11    12
</code>```

stack and .groupby.agg(['min','max','mean']) for those pesky aggregations.

```<code>df1 = df.stack(0).groupby(level=1).agg(['min','max','mean'])

  left          right
   min max mean   min max mean
A    1   7  4.0     2   8  5.0
B    3   9  6.0     4  10  7.0
C    5  11  8.0     6  12  9.0
</code>```

Finally a simple list comp to flatten your columns.

```<code>df1.columns = [f"{x}_{y}" for x,y in df1.columns]

print(df1)
   left_min  left_max  left_mean  right_min  right_max  right_mean
A         1         7        4.0          2          8         5.0
B         3         9        6.0          4         10         7.0
C         5        11        8.0          6         12         9.0

</code>```

or more succinctly as @sammywemmy

```<code>df1.columns = df1.columns.map('_'.join)
</code>```

Body:
I have a list of nested dictionaries in python with data that I want to analyze using pandas. Here's some example data:

[
  {
    "A": { "left": 1, "right": 2 },
    "B": { "left": 3, "right": 4 },
    "C": { "left": 5, "right": 6 },
  },
  {
    "A": { "left": 7, "right": 8 },
    "B": { "left": 9, "right": 10 },
    "C": { "left": 11, "right": 12 },
  },
  ...
]

And so on. As the example shows, each item in the array is a dictionary with the same keys, and each key points to a dictionary with the same keys. In table form, I imagine it should look something like this:

|idx|A         |B         |C         |
|   |left|right|left|right|left|right|
--------------------------------------
| 0 |   1|    2|   3|    4|   5|    6|
| 1 |   7|    8|   9|   10|  11|   12|
| 2 | ...                            |

What I want to do is aggregate the min, mean, and max of "left" and "right" across this list of dictionaries for each letter, so that it ends up with a DataFrame like this:

|idx|left_min|left_mean|left_max|right_min|right_mean|right_max|
----------------------------------------------------------------
| A |       1|        4|       7|        2|         5|        8|
| B |       3|        6|       9|        4|         7|       14|
| C |       5|        8|      11|        6|         9|       12|

I'm experienced with python but relatively new to pandas, so I'm trying to get it right within a pandas framework before I just write it myself in python. I've tried many different ways to mold and shape pandas DataFrames into this form but I can't quite manage it. Every attempt I've made has either multi-indexed in strange ways, or can't aggregate properly. I feel like I'm missing something fundamental here. Any help is appreciated.

Body:
Let's tackle this in steps.

pd.json_normalize

df = pd.json_normalize(data)

   A.left  A.right  B.left  B.right  C.left  C.right
0       1        2       3        4       5        6
1       7        8       9       10      11       12

str.split for the multi index.

df.columns = df.columns.str.split('.',expand=True)

     A          B          C
  left right left right left right
0    1     2    3     4    5     6
1    7     8    9    10   11    12

stack and .groupby.agg(['min','max','mean']) for those pesky aggregations.

df1 = df.stack(0).groupby(level=1).agg(['min','max','mean'])

  left          right
   min max mean   min max mean
A    1   7  4.0     2   8  5.0
B    3   9  6.0     4  10  7.0
C    5  11  8.0     6  12  9.0

Finally a simple list comp to flatten your columns.

df1.columns = [f"{x}_{y}" for x,y in df1.columns]

print(df1)
   left_min  left_max  left_mean  right_min  right_max  right_mean
A         1         7        4.0          2          8         5.0
B         3         9        6.0          4         10         7.0
C         5        11        8.0          6         12         9.0

or more succinctly as @sammywemmy

df1.columns = df1.columns.map('_'.join)


问:
Python, calculator class definition
I'm struggling with a practice problem below where I'm confused as to what the definitions would look like.

Create a class definition called 'calc' which is a calculator that supports these operators:  +, -, *, /
It should have the following methods:

```<code>def firstNumber(self, value):
def secondNumber(self, value):
def operator(self,op):
def answer(self):
def history(self):
</code>```

Test Example:

```<code>c = calc()
c.firstNumber(4)
c.secondNumber(5)
c.operator('+')
print(c.answer())
#Should print 9 here.

c.firstNumber(5)
c.secondNumber(5)
c.operator('*')
print(c.answer())
#should print 25 here
print(c.history())
#should print:
#1.) 4 + 5 = 9
#2.) 5 * 5 = 25
</code>```

答:
class Calculator(): #Create a class
    def calculate(): #Make function for calculate
        firstNumber = int(input("Enter your first number: ")) #Input first number and convert into interger
        secondNumber = int(input("Enter your second number: ")) #Input second number and convert into interger
        operator = input("Enter your operator: ") #Input operator
        if operator == "+": #Check if operator is +
            return firstNumber + secondNumber #Return result
        elif operator == "-": #Check if operator is -
            return firstNumber - secondNumber #Return result
        elif operator == "*": #Check if operator is *
            return firstNumber * secondNumber #Return result
        elif operator == "/": #Check if operator is /
            return firstNumber / secondNumber #Return result

Calc = Calculator() #Call the class
Result = Calc.calculate() #Calculate
print(Result) #Print the result into the console
```

So this is a basic calculator which will wait for our input for the firstNumber and then convert it to integer and also do the same thing with the secondNumber

Then it let us input the operator which is +, -, *, / and check if the input is one of an operator and then return the result

This is a very basic calculator, lambda or something I forget will make a calculator that same as the calculator you have seen, like when you input 1 + 6 - 3 it will return 4

================================================================

Btw the history function I think it's hard for you cuz you need to do a database which very complex for beginner

Title: Python, calculator class definition

Body:
I'm struggling with a practice problem below where I'm confused as to what the definitions would look like.

Create a class definition called 'calc' which is a calculator that supports these operators:  +, -, *, /
It should have the following methods:

def firstNumber(self, value):
def secondNumber(self, value):
def operator(self,op):
def answer(self):
def history(self):

Test Example:

c = calc()
c.firstNumber(4)
c.secondNumber(5)
c.operator('+')
print(c.answer())
#Should print 9 here.

c.firstNumber(5)
c.secondNumber(5)
c.operator('*')
print(c.answer())
#should print 25 here
print(c.history())
#should print:
#1.) 4 + 5 = 9
#2.) 5 * 5 = 25

Body:
class Calculator(): #Create a class
    def calculate(): #Make function for calculate
        firstNumber = int(input("Enter your first number: ")) #Input first number and convert into interger
        secondNumber = int(input("Enter your second number: ")) #Input second number and convert into interger
        operator = input("Enter your operator: ") #Input operator
        if operator == "+": #Check if operator is +
            return firstNumber + secondNumber #Return result
        elif operator == "-": #Check if operator is -
            return firstNumber - secondNumber #Return result
        elif operator == "*": #Check if operator is *
            return firstNumber * secondNumber #Return result
        elif operator == "/": #Check if operator is /
            return firstNumber / secondNumber #Return result

Calc = Calculator() #Call the class
Result = Calc.calculate() #Calculate
print(Result) #Print the result into the console

So this is a basic calculator which will wait for our input for the firstNumber and then convert it to integer and also do the same thing with the secondNumber

Then it let us input the operator which is +, -, *, / and check if the input is one of an operator and then return the result

This is a very basic calculator, lambda or something I forget will make a calculator that same as the calculator you have seen, like when you input 1 + 6 - 3 it will return 4

================================================================

Btw the history function I think it's hard for you cuz you need to do a database which very complex for beginner


问:
Order DataList and trim last 4 characters
Trying to order a list of files that are sitting in a folder. I am able to display the files just fine and the links work but cannot order them by the file name while removing the last 4 characters (.xlsx). It's ordered by the first 2 digits and I need to remove the last 4 characters ".xls" from the end of the file name. The list of files are:
01-07-2022.xlsx
12-03-2021.xlsx
11-05-2021.xlsx
etc.

I need them in that order and removing the .xlsx as it shows that name on the page. Right now it displays incorrectly below as:

12-04-2020.xlsx
12-03-2021.xlsx
11-07-2020.xlsx
11-05-2021.xlsx
10-01-2020.xlsx

just reading the first 2 digits for 12, 11, 10...etc. and then it shows a mix of the years.

My code to remove the characters and display in order.
Design View:

```<code>
                                        <div id="pccommlist" runat="server" visible="true">
                                            <asp:DataList ID="PCDataList" runat="server" RepeatColumns="1" BorderWidth="0" CellPadding="3" ForeColor="#2ba6cb"
                                                Width="100%">
                                                <FooterStyle BackColor="#ffffff" />
                                                <ItemTemplate>
                                                    <asp:ImageButton Width="16px" ID="excelimage" runat="server" BorderStyle="None" ImageUrl='../imagessecure/icons/lists/excel.png' Height="16px" />
                                                     Precinct as of <asp:Label ID="lblDate" runat="server" />
                                            <asp:HyperLink runat="server" NavigateUrl='<%#"pcredirect.aspx?name=" + DataBinder.Eval(Container.DataItem, "Name").ToString()%>' ID="pcLink" Target="_blank"
                                                Text='<%# DataBinder.Eval(Container.DataItem, "Name").ToString() %>'>
                                            </asp:HyperLink>
                                                </ItemTemplate>
                                                <FooterStyle BackColor="White" ForeColor="#2ba6cb" />
                                                <ItemStyle BorderColor="White" BorderStyle="None" BorderWidth="0" HorizontalAlign="Center"
                                                    VerticalAlign="Bottom" BackColor="White" ForeColor="#2ba6cb" />
                                            </asp:DataList>
                                        </div>
</code>```

Code Behind. Was trying to order it by creation time which was ideal and then tried full name as you see the commented out code above the FullName line.

```<code>    private void GetXLS()
    {

        DirectoryInfo dir = new DirectoryInfo(MapPath("~/pcselect2022/"));
        //FileInfo[] fileArray = dir.GetFiles("*.xlsx").OrderByDescending(p => p.CreationTimeUtc).ToArray(); //pull ONLY the xlsx files
        FileInfo[] fileArray = dir.GetFiles("*.xlsx").OrderByDescending(p => p.FullName).ToArray(); //pull ONLY the xlsx files
        char[] trimChars = { '.', 'x', 'l', 's' };
        string fileName = fileArray.ToString().TrimEnd(trimChars);

        //decide if we need to make controls visible
        pccommlist.Visible = fileArray.Length > 0;
        PCDataList.DataSource = fileArray;
        PCDataList.DataBind();
    }
</code>```

答:
It looks like you want to sort by date (chronologically), but the values you are sorting are strings. Further, the strings are month/day/year, so they cannot be sorted alphabetically and appear in the order you are expecting. If they were iso format (eg yyyy-mm-dd) then they could be sorted alphabetically and also be chronological. (see: Sort array by ISO 8601 date).

So your options:

Rename your files and require that they be named in ISO 8601

Create a class / model that can hold the filename and a datetime (DocumentDate or something). When you build up the list, parse the string filename value and create a date time out of it, and use the DocumentDate to do the sorting, and Filename for display

Body:
Trying to order a list of files that are sitting in a folder. I am able to display the files just fine and the links work but cannot order them by the file name while removing the last 4 characters (.xlsx). It's ordered by the first 2 digits and I need to remove the last 4 characters ".xls" from the end of the file name. The list of files are:
01-07-2022.xlsx
12-03-2021.xlsx
11-05-2021.xlsx
etc.

I need them in that order and removing the .xlsx as it shows that name on the page. Right now it displays incorrectly below as:

12-04-2020.xlsx
12-03-2021.xlsx
11-07-2020.xlsx
11-05-2021.xlsx
10-01-2020.xlsx

just reading the first 2 digits for 12, 11, 10...etc. and then it shows a mix of the years.

My code to remove the characters and display in order.
Design View:

                                            <asp:DataList ID="PCDataList" runat="server" RepeatColumns="1" BorderWidth="0" CellPadding="3" ForeColor="#2ba6cb"
                                                Width="100%">
                                                <FooterStyle BackColor="#ffffff" />
                                                <ItemTemplate>
                                                    <asp:ImageButton Width="16px" ID="excelimage" runat="server" BorderStyle="None" ImageUrl='../imagessecure/icons/lists/excel.png' Height="16px" />
                                                     Precinct as of <asp:Label ID="lblDate" runat="server" />
                                            <asp:HyperLink runat="server" NavigateUrl='<%#"pcredirect.aspx?name=" + DataBinder.Eval(Container.DataItem, "Name").ToString()%>' ID="pcLink" Target="_blank"
                                                Text='<%# DataBinder.Eval(Container.DataItem, "Name").ToString() %>'>
                                            </asp:HyperLink>
                                                </ItemTemplate>
                                                <FooterStyle BackColor="White" ForeColor="#2ba6cb" />
                                                <ItemStyle BorderColor="White" BorderStyle="None" BorderWidth="0" HorizontalAlign="Center"
                                                    VerticalAlign="Bottom" BackColor="White" ForeColor="#2ba6cb" />
                                            </asp:DataList>

Code Behind. Was trying to order it by creation time which was ideal and then tried full name as you see the commented out code above the FullName line.

    private void GetXLS()
    {

        DirectoryInfo dir = new DirectoryInfo(MapPath("~/pcselect2022/"));
        //FileInfo[] fileArray = dir.GetFiles("*.xlsx").OrderByDescending(p => p.CreationTimeUtc).ToArray(); //pull ONLY the xlsx files
        FileInfo[] fileArray = dir.GetFiles("*.xlsx").OrderByDescending(p => p.FullName).ToArray(); //pull ONLY the xlsx files
        char[] trimChars = { '.', 'x', 'l', 's' };
        string fileName = fileArray.ToString().TrimEnd(trimChars);

        //decide if we need to make controls visible
        pccommlist.Visible = fileArray.Length > 0;
        PCDataList.DataSource = fileArray;
        PCDataList.DataBind();
    }


问:
Variable initialized with let is not changing?
My code is returning an empty array from main and then [foo,bar,baz] on the console log after main is called. Was the original array not changed inside of main? When I remove the arr function both console logs return an empty array. Is it because the function arr is a callback for console? If someone could explain why the function arr is affecting the output that would be great thanks.

let arr = ['foo', 'bar', 'baz'];
function main() {
   arr = [];
   function arr() {
      const result= 8
      return result;
    }
   console.log(arr);
}
main();
console.log(arr);```

答:
You created another variable named arr inside the function, so all references to arr inside the function refer to that new variable (which is only scoped to the function), and the outside arr remains unchanged. Your code is equivalent to

let arr = ['foo', 'bar', 'baz'];

function main() {
  // new variable for this scope:
  let arr;
  // function declaration is hoisted:
  arr = function arr() {
    const result = 8
    return result;
  }
  // assignment runs:
  arr = [];
  console.log(arr);
}
main();
// but arr outside remains unchanged because it's a different binding
console.log(arr);```

This is one reason why it's important to give variables meaningful names. A function is not an array, so it probably shouldn't be named arr unless you're deliberately trying to confuse readers of the code.

You can also help prevent yourself from making this sort of mistake by using the ESLint rule no-shadow, which prevents inner scope variables from having the same name as an outer scope variable.

Body:
You created another variable named arr inside the function, so all references to arr inside the function refer to that new variable (which is only scoped to the function), and the outside arr remains unchanged. Your code is equivalent to

let arr = ['foo', 'bar', 'baz'];

function main() {
  // new variable for this scope:
  let arr;
  // function declaration is hoisted:
  arr = function arr() {
    const result = 8
    return result;
  }
  // assignment runs:
  arr = [];
  console.log(arr);
}
main();
// but arr outside remains unchanged because it's a different binding
console.log(arr);

This is one reason why it's important to give variables meaningful names. A function is not an array, so it probably shouldn't be named arr unless you're deliberately trying to confuse readers of the code.

You can also help prevent yourself from making this sort of mistake by using the ESLint rule no-shadow, which prevents inner scope variables from having the same name as an outer scope variable.


问:
no solution: ImportError: No module named flask
I'm new on python, and use 3.10.2 version. I wrote this in vs code;

```<code>from flask import Flask
app=Flask(__name__)
if __name__ == "__main__":
    app.run(debug=True)
</code>```

but the result is;

```<code>Traceback (most recent call last):
  File "blog.py", line 1, in <module>
    from flask import Flask
ImportError: No module named flask
</code>```

I tried everything that written on this site but the result is the same. I am using mac and waiting for your help. Thanks.

答:
Try to install the Flask first, use pip.

```<code>pip install Flask
</code>```

reference :
https://flask.palletsprojects.com/en/2.0.x/installation/

Body:
I'm new on python, and use 3.10.2 version. I wrote this in vs code;

from flask import Flask
app=Flask(__name__)
if __name__ == "__main__":
    app.run(debug=True)

but the result is;

Traceback (most recent call last):
  File "blog.py", line 1, in <module>
    from flask import Flask
ImportError: No module named flask

I tried everything that written on this site but the result is the same. I am using mac and waiting for your help. Thanks.

Body:
Try to install the Flask first, use pip.

pip install Flask

reference :
https://flask.palletsprojects.com/en/2.0.x/installation/


问:
Decoding JSON stream that isn't surrounded by array brackets?
I'm trying to decode a JSON stream from a file. The file is newline separated JSON objects. But it's not formatted with array brackets surrounding the objects, so I can't figure out how to use encoding/json stream decoder.

I get the error not at beginning of value because there is no opening bracket.

```<code>package main

import (
    "encoding/json"
    "fmt"
    "log"
    "strings"
)

func main() {

    // My data is missing opening and closing brackets around the jsonStream string.
    // [
    const jsonStream = `
        {"Name": "Ed", "Text": "Knock knock."},
        {"Name": "Sam", "Text": "Who's there?"},
        {"Name": "Ed", "Text": "Go fmt."},
        {"Name": "Sam", "Text": "Go fmt who?"},
        {"Name": "Ed", "Text": "Go fmt yourself!"}
    `
    // ]
    type Message struct {
        Name, Text string
    }
    dec := json.NewDecoder(strings.NewReader(jsonStream))

    // read open bracket -- this fails (no bracket)
    t, err := dec.Token()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("%T: %v\n", t, t)

    // while the array contains values
    for dec.More() {
        var m Message
        // decode an array value (Message)
        err := dec.Decode(&m)
        if err != nil {
            log.Fatal(err)
        }

        fmt.Printf("%v: %v\n", m.Name, m.Text)
    }

    // read closing bracket -- this also would fail (no bracket)
    t, err = dec.Token()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("%T: %v\n", t, t)

}
</code>```

Removing the dec.Token() error checks doesn't work either. I guess the parser doesn't expect to see objects before it has seen an array open bracket?

Is there some workaround?

答:
There is a small difference in parsing discrete Json objects as stream or an array of Json objects.

In case of array, we need to get the token explicitly (one of [ or {)- that will make way for the Json parser to continue parsing the Json objects in the array. However, in the case of discrete Json objects stream processing, there is no need to look for the starting token. Check out the sample code that has both flavors.

https://go.dev/play/p/Zinv6CwNEPP

Body:
I'm trying to decode a JSON stream from a file. The file is newline separated JSON objects. But it's not formatted with array brackets surrounding the objects, so I can't figure out how to use encoding/json stream decoder.

I get the error not at beginning of value because there is no opening bracket.

package main

import (
    "encoding/json"
    "fmt"
    "log"
    "strings"
)

func main() {

    // My data is missing opening and closing brackets around the jsonStream string.
    // [
    const jsonStream = `
        {"Name": "Ed", "Text": "Knock knock."},
        {"Name": "Sam", "Text": "Who's there?"},
        {"Name": "Ed", "Text": "Go fmt."},
        {"Name": "Sam", "Text": "Go fmt who?"},
        {"Name": "Ed", "Text": "Go fmt yourself!"}
    `
    // ]
    type Message struct {
        Name, Text string
    }
    dec := json.NewDecoder(strings.NewReader(jsonStream))

    // read open bracket -- this fails (no bracket)
    t, err := dec.Token()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("%T: %v\n", t, t)

    // while the array contains values
    for dec.More() {
        var m Message
        // decode an array value (Message)
        err := dec.Decode(&m)
        if err != nil {
            log.Fatal(err)
        }

        fmt.Printf("%v: %v\n", m.Name, m.Text)
    }

    // read closing bracket -- this also would fail (no bracket)
    t, err = dec.Token()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("%T: %v\n", t, t)

}

Removing the dec.Token() error checks doesn't work either. I guess the parser doesn't expect to see objects before it has seen an array open bracket?

Is there some workaround?


问:
How to avoid getting multiple cookies when login using Cognito
We are doing authentication using AWS Cognito. The project is contained with an API server and a web server. On the client-side, the user login to the application, through AsureAD, the cognito instance returns a JWT access token. When a user log out from the application, we remove the cookie and signout from cognito.

My problem is that, we need to create only one access token when user login to the application. But it makes two..

```<code>async logout(req, res, next) {
  try {
    res.header('set-cookie', `SessionCookie-0=; Path=/;`);
  } catch (error) {
    next(appendExceptionStack(error));
  }
}
</code>```

This is how I reset the cookie when logout. This works when it creates only one access cookie. I think this should be handle in cognito side. Can someone help me to avoid from getting two cookies when login to the application.

答:
What OAuth Flow configuration are you using?  Authorization code grant or Implicit grant?  If you are using Authorization code grant and your backend callback is exchanging the auth code for the tokens, you should get back an access token, refresh token and a id token if you have the openid OAuth scope enabled.  Is it your app that is setting the cookies?  Because when using the Authorization code grant, Cognito only sets two cookies for me.  One is named cognito and the other named XSRF-TOKEN. But in my situation, my app which consumes the Cognito tokens does set our own cookies to store the tokens.  In your case who is creating the cookie named SessionCookie-0?
I think providing more details on your setup will be helpful.</p>

Body:
We are doing authentication using AWS Cognito. The project is contained with an API server and a web server. On the client-side, the user login to the application, through AsureAD, the cognito instance returns a JWT access token. When a user log out from the application, we remove the cookie and signout from cognito.

My problem is that, we need to create only one access token when user login to the application. But it makes two..

async logout(req, res, next) {
  try {
    res.header('set-cookie', `SessionCookie-0=; Path=/;`);
  } catch (error) {
    next(appendExceptionStack(error));
  }
}

This is how I reset the cookie when logout. This works when it creates only one access cookie. I think this should be handle in cognito side. Can someone help me to avoid from getting two cookies when login to the application.


问:
case-insensitive alphabetical sorting of nested lists
i'm trying to sort this nested list by inner's list first element:

```<code>ak = [ ['a',1],['E',2],['C',13],['A',11],['b',9] ]
ak.sort(cmp=lambda x, y: cmp(x[0], y[0]))
for i in ak: {
    print i
}
</code>```

by default python considers A > a, hence the output i get is:

```<code>['A', 11] ['C', 13] ['E', 2] ['a', 1] ['b', 9]
</code>```

i've tried converting all list values to even case during comparison by adding x[0].lower etc. but no use. How do i force python (i'm working on 2.4 version) to do case-insensitive alphabetical sorting?

Edited:

Jarret and Brian, your
  assumptions about parenthesis were
  right! I did forget to put them in! And Jarret, your suggestions about not using "cmp" works like a charm! Thanks a lot guys!

答:
Try:

```<code>ak.sort(key=lambda x:x[0].lower())
</code>```

I would recommend that you avoid using cmp as this has been deprecated in Python 2.6, and removed in 3.0. I know you're using 2.4, but the reason cmp has fallen into disfavour is that it is a very slow way to sort.

I'm not sure why your effort with lower failed, though... perhaps you forgot to use the function call versus just the function name? (ie: cmp(x[0].lower(), y[0].lower()) versus cmp(x[0].lower, y[0].lower))

OwnerDisplayName: Alex

LastEditorDisplayName: Alex

ContentLicense: CC BY-SA 2.5

Body:
i'm trying to sort this nested list by inner's list first element:

ak = [ ['a',1],['E',2],['C',13],['A',11],['b',9] ]
ak.sort(cmp=lambda x, y: cmp(x[0], y[0]))
for i in ak: {
    print i
}

by default python considers A > a, hence the output i get is:

['A', 11] ['C', 13] ['E', 2] ['a', 1] ['b', 9]

i've tried converting all list values to even case during comparison by adding x[0].lower etc. but no use. How do i force python (i'm working on 2.4 version) to do case-insensitive alphabetical sorting?

Edited:

Jarret and Brian, your
  assumptions about parenthesis were
  right! I did forget to put them in! And Jarret, your suggestions about not using "cmp" works like a charm! Thanks a lot guys!

Body:
Try:

ak.sort(key=lambda x:x[0].lower())

I would recommend that you avoid using cmp as this has been deprecated in Python 2.6, and removed in 3.0. I know you're using 2.4, but the reason cmp has fallen into disfavour is that it is a very slow way to sort.

I'm not sure why your effort with lower failed, though... perhaps you forgot to use the function call versus just the function name? (ie: cmp(x[0].lower(), y[0].lower()) versus cmp(x[0].lower, y[0].lower))

OwnerDisplayName: Jarret Hardie


问:
Laravel how to add middleware to controller with multiple roles?
What I want to achieve is that the EventController's functions/ methods should be available for role:organizer, and only the view() method [URL: /events/{id}] from the same controller should also be available to role:artist.

I've tried to implement that by creating the following middleware to check for the logged-in user's role:
class UserRole

```<code>{
    /**
     * Handle an incoming request.
     *
     * @param Request $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return Application|JsonResponse|RedirectResponse|Redirector
     */
    public function handle(Request $request, Closure $next, ...$roles)
    {
        if ($request->expectsJson()) {
            return response()->json(['error' => 'Unauthenticated.'], 401);
        }

        if (!Auth::check()) {
            return redirect(RouteServiceProvider::HOME);
        }

        if (in_array(strtolower(Auth::user()->type), $roles)) {
            return $next($request);
        }

        return redirect('/login');
    }
}
</code>```

Then in my EventController, I have assigned the following middlewares in the constructor:

```<code>public function __construct()
    {
        $this->middleware(['auth', 'verified', 'onboarding', 'role:organizer']);
        $this->middleware(['role:artist,organizer'])->only('view');
    }
</code>```

When I run php artisan route:list - I get the list as I want it to be, only events/{id} has both the organizer and artist role

However when I log in with user artist and try to access localhost/events/10 - I get redirected to the /login screen, but when I try to access the same URL with a role organizer it works..

Is there any suggestion on how to make it work? If there's something you don't understand let me know and I'll help you!

答:
The problem is that you have attached the middleware to view endpoint with 'role:organizer' twice in the first time it only check is user has role organizer and it doing redirect and it's not going check the second time so to exclude this behavior you should attache middlewares like this

```<code>$this->middleware(['auth', 'verified', 'onboarding']);
$this->middleware(['role:artist,organizer'])->only('view');
$this->middleware('role:organizer')->except('view');// because it already added above
</code>```

Body:
What I want to achieve is that the EventController's functions/ methods should be available for role:organizer, and only the view() method [URL: /events/{id}] from the same controller should also be available to role:artist.

I've tried to implement that by creating the following middleware to check for the logged-in user's role:
class UserRole

{
    /**
     * Handle an incoming request.
     *
     * @param Request $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return Application|JsonResponse|RedirectResponse|Redirector
     */
    public function handle(Request $request, Closure $next, ...$roles)
    {
        if ($request->expectsJson()) {
            return response()->json(['error' => 'Unauthenticated.'], 401);
        }

        if (!Auth::check()) {
            return redirect(RouteServiceProvider::HOME);
        }

        if (in_array(strtolower(Auth::user()->type), $roles)) {
            return $next($request);
        }

        return redirect('/login');
    }
}

Then in my EventController, I have assigned the following middlewares in the constructor:

public function __construct()
    {
        $this->middleware(['auth', 'verified', 'onboarding', 'role:organizer']);
        $this->middleware(['role:artist,organizer'])->only('view');
    }

When I run php artisan route:list - I get the list as I want it to be, only events/{id} has both the organizer and artist role

However when I log in with user artist and try to access localhost/events/10 - I get redirected to the /login screen, but when I try to access the same URL with a role organizer it works..

Is there any suggestion on how to make it work? If there's something you don't understand let me know and I'll help you!

Body:
The problem is that you have attached the middleware to view endpoint with 'role:organizer' twice in the first time it only check is user has role organizer and it doing redirect and it's not going check the second time so to exclude this behavior you should attache middlewares like this

$this->middleware(['auth', 'verified', 'onboarding']);
$this->middleware(['role:artist,organizer'])->only('view');
$this->middleware('role:organizer')->except('view');// because it already added above


问:
[api](Unsplash Api) trying to generate random pictures for my testing database
I'm using a nodejs package called casual Which basically lets one generate random data

Im defining this method for generating imgs

```<code>casual.define('portrait', () => ({
 uri: `https://source.unsplash.com/collection/9948714?sig=${casual.integer(1, 100)}`
}));
</code>```

From this, I create an array of images like this :

```<code>[
  {"uri":"https://source.unsplash.com/collection/9948714?sig=37"},
  {"uri":"https://source.unsplash.com/collection/9948714?sig=32"},
  {"uri":"https://source.unsplash.com/collection/9948714?sig=91"},
]
</code>```

I'm supposed to get a different image each time, but the PROBLEM is that I get the same picture 3 times, even with the sig.

What I'm I doing wrong?

答:
[SOLVED]

```<code>casual.define('portrait', () => ({
 uri: `https://source.unsplash.com/collection/9948714?${casual.integer(1, 100)}`
}));
</code>```

generating

```<code>[
  {"uri":"https://source.unsplash.com/collection/9948714?37"},
  {"uri":"https://source.unsplash.com/collection/9948714?32"},
  {"uri":"https://source.unsplash.com/collection/9948714?91"},
]
</code>```

just adding a number instead of sig=number worked

Body:
I'm using a nodejs package called casual Which basically lets one generate random data

Im defining this method for generating imgs

casual.define('portrait', () => ({
 uri: `https://source.unsplash.com/collection/9948714?sig=${casual.integer(1, 100)}`
}));

From this, I create an array of images like this :

[
  {"uri":"https://source.unsplash.com/collection/9948714?sig=37"},
  {"uri":"https://source.unsplash.com/collection/9948714?sig=32"},
  {"uri":"https://source.unsplash.com/collection/9948714?sig=91"},
]

I'm supposed to get a different image each time, but the PROBLEM is that I get the same picture 3 times, even with the sig.

What I'm I doing wrong?

Body:
[SOLVED]

casual.define('portrait', () => ({
 uri: `https://source.unsplash.com/collection/9948714?${casual.integer(1, 100)}`
}));

generating

[
  {"uri":"https://source.unsplash.com/collection/9948714?37"},
  {"uri":"https://source.unsplash.com/collection/9948714?32"},
  {"uri":"https://source.unsplash.com/collection/9948714?91"},
]

just adding a number instead of sig=number worked


问:
How select and remove rows based on position for a specific range in R
Suppose I have two data frames like this:

```<code>df1 <- data.frame(a = c(1,2,4,0,0),
             b = c(0,3,5,5,0),
             c = c(0,0,6,7,6))

df2 <- data.frame(a = c(3,6,8,0,0),
             b = c(0,9,10,4,0),
             c = c(0,0,1,4,9))
</code>```

And then I joint it, like

```<code>df3 <- full_join(df1, df2)
print(df3)

   a  b c
1  1  0 0
2  2  3 0
3  4  5 6
4  0  5 7
5  0  0 6
6  3  0 0
7  6  9 0
8  8 10 1
9  0  4 4
10 0  0 9
</code>```

Note that I have always the same pattern, with zeros in rows 1 and 2; and in rows 9 and 10. And I also have zeros between rows 4 and 7.
I want to remove, only, the zeros between rows 4 and 7.
So, I can solve it, like:

```<code>df3[4,1] <- NA
df3[5,1] <- NA
df3[5,2] <- NA
df3[6,2] <- NA
df3[6,3] <- NA
df3[7,3] <- NA

new.df3 <-  as.data.frame(lapply(df3, na.omit))
print(new.df3)

  a  b c
1 1  0 0
2 2  3 0
3 4  5 6
4 3  5 7
5 6  9 6
6 8 10 1
7 0  4 4
8 0  0 9
</code>```

But it is not elegant and very time-consuming.
Any thoughts? I really appreciate it, thanks in advance.
Best!

答:
Here's a different approach:</p>
```<code>mask <- !(seq(nrow(df3)) %in% 4:7 & df3 == 0)
df.lst <- lapply(1:3, function(x) df3[mask[, x], x])
sapply(df.lst, length)
# [1] 8 8 8  # Check to make sure the columns are the same length
names(df.lst) <- colnames(df3)
(new.df3 <- as.data.frame(df.lst))
#   a  b c
# 1 1  0 0
# 2 2  3 0
# 3 4  5 6
# 4 3  5 7
# 5 6  9 6
# 6 8 10 1
# 7 0  4 4
# 8 0  0 9
</code>```

Body:
Suppose I have two data frames like this:

df1 <- data.frame(a = c(1,2,4,0,0),
             b = c(0,3,5,5,0),
             c = c(0,0,6,7,6))

df2 <- data.frame(a = c(3,6,8,0,0),
             b = c(0,9,10,4,0),
             c = c(0,0,1,4,9))

And then I joint it, like

df3 <- full_join(df1, df2)
print(df3)

   a  b c
1  1  0 0
2  2  3 0
3  4  5 6
4  0  5 7
5  0  0 6
6  3  0 0
7  6  9 0
8  8 10 1
9  0  4 4
10 0  0 9

Note that I have always the same pattern, with zeros in rows 1 and 2; and in rows 9 and 10. And I also have zeros between rows 4 and 7.
I want to remove, only, the zeros between rows 4 and 7.
So, I can solve it, like:

df3[4,1] <- NA
df3[5,1] <- NA
df3[5,2] <- NA
df3[6,2] <- NA
df3[6,3] <- NA
df3[7,3] <- NA

new.df3 <-  as.data.frame(lapply(df3, na.omit))
print(new.df3)

  a  b c
1 1  0 0
2 2  3 0
3 4  5 6
4 3  5 7
5 6  9 6
6 8 10 1
7 0  4 4
8 0  0 9

But it is not elegant and very time-consuming.
Any thoughts? I really appreciate it, thanks in advance.
Best!

Body:
Here's a different approach:

mask <- !(seq(nrow(df3)) %in% 4:7 & df3 == 0)
df.lst <- lapply(1:3, function(x) df3[mask[, x], x])
sapply(df.lst, length)
# [1] 8 8 8  # Check to make sure the columns are the same length
names(df.lst) <- colnames(df3)
(new.df3 <- as.data.frame(df.lst))
#   a  b c
# 1 1  0 0
# 2 2  3 0
# 3 4  5 6
# 4 3  5 7
# 5 6  9 6
# 6 8 10 1
# 7 0  4 4
# 8 0  0 9


问:
Counting observations by group using collapse R package
I want to translate the following R code from tidyverse to collapse. The following code count observations by group and append as a column to the data.frame.

```<code>library(tidyverse)
library(collapse)
head(wlddev)

wlddev %>%
  group_by(income) %>%
  add_count(., name = "Size") %>%
  select(country, income, Size) %>%
  distinct()
# A tibble: 216 x 3
# Groups:   income [4]
   country             income               Size
   <chr>               <fct>               <int>
 1 Afghanistan         Low income           1830
 2 Albania             Upper middle income  3660
 3 Algeria             Upper middle income  3660
 4 American Samoa      Upper middle income  3660
 5 Andorra             High income          4819
 6 Angola              Lower middle income  2867
 7 Antigua and Barbuda High income          4819
 8 Argentina           Upper middle income  3660
 9 Armenia             Upper middle income  3660
10 Aruba               High income          4819
# ... with 206 more rows
</code>```

Now want to accomplish the same task with collapse R package.

The following code works as expected.

```<code>wlddev %>%
  fgroup_by(income) %>%
  fselect(country) %>%
  fnobs()

               income country
1         High income    4819
2          Low income    1830
3 Lower middle income    2867
4 Upper middle income    3660
</code>```

However, not able to append the column to original data.frame.

```<code>wlddev %>%
  fgroup_by(income) %>%
  fselect(country) %>%
  fnobs() %>%
  ftransform(.data = wlddev, Size = .)

Error in ftransform_core(.data, e) :
  Lengths of replacements must be equal to nrow(.data) or 1, or NULL to delete columns
</code>```

Any hints, please.

答:
So in principle fnobs counts the number of non-missing values, an option to add the group count is not really afforded (I also wonder why that would be necessary, I have never required it). Nevertheless, the count is there in the grouping object which can be retrieved using GRP(.). So you could create a function:

```<code>gcount <- function(x) {
   # Just turning some unnecessary things off in case we pass a plain vector
   g <- GRP(x, sort = FALSE, return.groups = FALSE, call = FALSE)
   g$group.sizes[g$group.id]
}

</code>```

Then we can do

```<code>wlddev %>%
  ftransform(Size = gcount(income)) %>%
  fselect(country, income, Size) %>%
  funique(cols = 1) # Observations are uniquely identified by country

# or

wlddev %>%
  fgroup_by(income) %>%
  ftransform(Size = gcount(.)) %>%
  fselect(country, income, Size) %>%
  fungroup() %>%
  funique(cols = 1)

</code>```

Of course we can also use fnobs:

```<code>wlddev %>%
  fgroup_by(income) %>%
  fmutate(Size = fnobs(income)) %>%
  fselect(country, income, Size) %>%
  fungroup() %>%
  funique(cols = 1)
</code>```

but that could be misleading if incomecontained missing values. Note (as stated in the documentation) that ftransform is a faster version of base::transform that ignores groupings and fmutate is a faster dplyr::mutate which respects groupings.

If you tell me why the group count would be required as a variable in a data frame, I can think of adding gcount to the next collapse release.

Body:
I want to translate the following R code from tidyverse to collapse. The following code count observations by group and append as a column to the data.frame.

library(tidyverse)
library(collapse)
head(wlddev)

wlddev %>%
  group_by(income) %>%
  add_count(., name = "Size") %>%
  select(country, income, Size) %>%
  distinct()
# A tibble: 216 x 3
# Groups:   income [4]
   country             income               Size
   <chr>               <fct>               <int>
 1 Afghanistan         Low income           1830
 2 Albania             Upper middle income  3660
 3 Algeria             Upper middle income  3660
 4 American Samoa      Upper middle income  3660
 5 Andorra             High income          4819
 6 Angola              Lower middle income  2867
 7 Antigua and Barbuda High income          4819
 8 Argentina           Upper middle income  3660
 9 Armenia             Upper middle income  3660
10 Aruba               High income          4819
# ... with 206 more rows

Now want to accomplish the same task with collapse R package.

The following code works as expected.

wlddev %>%
  fgroup_by(income) %>%
  fselect(country) %>%
  fnobs()

               income country
1         High income    4819
2          Low income    1830
3 Lower middle income    2867
4 Upper middle income    3660

However, not able to append the column to original data.frame.

wlddev %>%
  fgroup_by(income) %>%
  fselect(country) %>%
  fnobs() %>%
  ftransform(.data = wlddev, Size = .)

Error in ftransform_core(.data, e) :
  Lengths of replacements must be equal to nrow(.data) or 1, or NULL to delete columns

Any hints, please.

Body:
So in principle fnobs counts the number of non-missing values, an option to add the group count is not really afforded (I also wonder why that would be necessary, I have never required it). Nevertheless, the count is there in the grouping object which can be retrieved using GRP(.). So you could create a function:

gcount <- function(x) {
   # Just turning some unnecessary things off in case we pass a plain vector
   g <- GRP(x, sort = FALSE, return.groups = FALSE, call = FALSE)
   g$group.sizes[g$group.id]
}

Then we can do

wlddev %>%
  ftransform(Size = gcount(income)) %>%
  fselect(country, income, Size) %>%
  funique(cols = 1) # Observations are uniquely identified by country

# or

wlddev %>%
  fgroup_by(income) %>%
  ftransform(Size = gcount(.)) %>%
  fselect(country, income, Size) %>%
  fungroup() %>%
  funique(cols = 1)

Of course we can also use fnobs:

wlddev %>%
  fgroup_by(income) %>%
  fmutate(Size = fnobs(income)) %>%
  fselect(country, income, Size) %>%
  fungroup() %>%
  funique(cols = 1)

but that could be misleading if incomecontained missing values. Note (as stated in the documentation) that ftransform is a faster version of base::transform that ignores groupings and fmutate is a faster dplyr::mutate which respects groupings.

If you tell me why the group count would be required as a variable in a data frame, I can think of adding gcount to the next collapse release.


问:
Solana Token transfer works in localhost but not on server
So I have a option on my site to "send" xy amount of custom solana token with connection to phantom wallet.
This exact same function works in localhost but not when I upload it to my server and go to the website through the ip adress. How is this even possible when this code is executed client-side in the same browser and the code is the same but when using the website hosted on the server I get:
TypeError: Cannot read properties of undefined (reading 'digest')
In function myToken.getOrCreateAssociatedAccountInfo
Using

```<code><script src="https://unpkg.com/@solana/web3.js@latest/lib/index.iife.min.js"></script>
    <script src="https://unpkg.com/@solana/spl-token@latest/lib/index.iife.min.js"></script>
</code>```

In the headers

Here is the code:

```<code>function sendCOIN(amount){
    return new Promise(async(resolve, reject) => {
        const publicKey = window.solana._publicKey
        const toWallet = new web3.PublicKey("myWalletPublicKey")
        const myMint = new web3.PublicKey("myMintAdress");
        const myToken = new splToken.Token(
            connection,
            myMint,
            splToken.TOKEN_PROGRAM_ID,
            publicKey
        );
        const createTransferTransaction = async () => {
            const fromTokenAccount = await myToken.getOrCreateAssociatedAccountInfo(
                publicKey
            )
            const toTokenAccount = await myToken.getOrCreateAssociatedAccountInfo(
                toWallet
            )
            let transaction = new web3.Transaction().add(
                splToken.Token.createTransferInstruction(
                    splToken.TOKEN_PROGRAM_ID,
                    fromTokenAccount.address,
                    toTokenAccount.address,
                    publicKey,
                    [],
                    web3.LAMPORTS_PER_SOL*amount
                  )
            );
            transaction.feePayer = publicKey;
            console.log("Getting recent blockhash");
            const anyTransaction = transaction;
            anyTransaction.recentBlockhash = (
              await connection.getRecentBlockhash()
            ).blockhash;
            return transaction;
        };

        const sendTransaction = async () => {
            try {
                const transaction = await createTransferTransaction();
                if (!transaction) return;
                console.log("Sending transaction!")
                const { signature } = await window.solana.signAndSendTransaction(transaction);
                console.log("Submitted transaction " + signature + ", awaiting confirmation");
                await connection.confirmTransaction(signature);
                console.log("Transaction " + signature + " confirmed");
                return resolve({signature, publicKey: publicKey.toString()})
            } catch (err) {
                console.warn(err);
                console.log("[error] sendTransaction: " + JSON.stringify(err));
                return reject(500)
            }
        };

        sendTransaction()
    });
}
</code>```

答:
The issue was a missing SSL/TLS certificate/no SSL enabled:
https://github.com/exiled-apes/candy-machine-mint/issues/126</p>

Body:
So I have a option on my site to "send" xy amount of custom solana token with connection to phantom wallet.
This exact same function works in localhost but not when I upload it to my server and go to the website through the ip adress. How is this even possible when this code is executed client-side in the same browser and the code is the same but when using the website hosted on the server I get:
TypeError: Cannot read properties of undefined (reading 'digest')
In function myToken.getOrCreateAssociatedAccountInfo
Using

In the headers

Here is the code:

function sendCOIN(amount){
    return new Promise(async(resolve, reject) => {
        const publicKey = window.solana._publicKey
        const toWallet = new web3.PublicKey("myWalletPublicKey")
        const myMint = new web3.PublicKey("myMintAdress");
        const myToken = new splToken.Token(
            connection,
            myMint,
            splToken.TOKEN_PROGRAM_ID,
            publicKey
        );
        const createTransferTransaction = async () => {
            const fromTokenAccount = await myToken.getOrCreateAssociatedAccountInfo(
                publicKey
            )
            const toTokenAccount = await myToken.getOrCreateAssociatedAccountInfo(
                toWallet
            )
            let transaction = new web3.Transaction().add(
                splToken.Token.createTransferInstruction(
                    splToken.TOKEN_PROGRAM_ID,
                    fromTokenAccount.address,
                    toTokenAccount.address,
                    publicKey,
                    [],
                    web3.LAMPORTS_PER_SOL*amount
                  )
            );
            transaction.feePayer = publicKey;
            console.log("Getting recent blockhash");
            const anyTransaction = transaction;
            anyTransaction.recentBlockhash = (
              await connection.getRecentBlockhash()
            ).blockhash;
            return transaction;
        };

        const sendTransaction = async () => {
            try {
                const transaction = await createTransferTransaction();
                if (!transaction) return;
                console.log("Sending transaction!")
                const { signature } = await window.solana.signAndSendTransaction(transaction);
                console.log("Submitted transaction " + signature + ", awaiting confirmation");
                await connection.confirmTransaction(signature);
                console.log("Transaction " + signature + " confirmed");
                return resolve({signature, publicKey: publicKey.toString()})
            } catch (err) {
                console.warn(err);
                console.log("[error] sendTransaction: " + JSON.stringify(err));
                return reject(500)
            }
        };

        sendTransaction()
    });
}


问:
Eject excess space from string in C
I need to write a function which will eject excess space from string in C.

Example:

```<code>char s[]="  abcde    abcde    ";
</code>```

OUTPUT:

```<code>"abcde abcde"
</code>```

Code:

```<code>#include <stdio.h>
#include <ctype.h>
char *eject(char *str) {
  int i, x;
  for (i = x = 0; str[i]; ++i)
    if (!isspace(str[i]) || (i > 0 && !isspace(str[i - 1])))
      str[x++] = str[i];
  if(x > 0 && str[x-1] == ' ') str[x-1] = '\0';
  return str;
}

int main() {
  char s[] = "  abcde    abcde    ";
  printf("\"%s\"", eject(s));
  return 0;
}
</code>```

This code doesn't work for string "          "
If this string is found program should print:

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

How to fix this?

答:
You could write two functions which trim leading and trailing whitespace characters.

```<code>void trim_front(char *src) {
    size_t i = 0, j = 0;
    while (isspace(src[i])) i++;
    while (i < strlen(src)) src[j++] = src[i++];
    src[j] = '\0';
}

void trim_back(char *src) {
    char *ch = src + strlen(src) - 1;
    while (isspace(*ch)) *ch-- = '\0';
}
</code>```

If you know you don't have to deal with trailing or leading spaces, your task becomes much simpler.

```<code>void reduce_spaces(char *src) {
    size_t i = 0, j = 0;

    for (; i < strlen(src); ++i) {
        if (i == strlen(src) - 1 ||
            (isspace(src[i]) && !isspace(src[i + 1])) ||
            !isspace(src[i])) {
            src[j++] = src[i];
        }
    }

    src[j] = '\0';
}
</code>```

And testing this:

```<code>int main(void) {
    char s[] = "     hello    world     ";

    trim_front(s);
    trim_back(s);
    reduce_spaces(s);

    printf(">%s<\n", s);

    return 0;
}
</code>```

% gcc test.c
% ./a.out
>hello world<
%
```

Of course, if you really want to, you can transplant the code from those functions into reduce_spaces, but decomposing a problem into multiple smaller problems can make things much easier.

Title: Eject excess space from string in C

Body:
I need to write a function which will eject excess space from string in C.

Example:

char s[]="  abcde    abcde    ";

OUTPUT:

"abcde abcde"

Code:

#include <stdio.h>
#include <ctype.h>
char *eject(char *str) {
  int i, x;
  for (i = x = 0; str[i]; ++i)
    if (!isspace(str[i]) || (i > 0 && !isspace(str[i - 1])))
      str[x++] = str[i];
  if(x > 0 && str[x-1] == ' ') str[x-1] = '\0';
  return str;
}

int main() {
  char s[] = "  abcde    abcde    ";
  printf("\"%s\"", eject(s));
  return 0;
}

This code doesn't work for string "          "
If this string is found program should print:

""

How to fix this?

Body:
You could write two functions which trim leading and trailing whitespace characters.

void trim_front(char *src) {
    size_t i = 0, j = 0;
    while (isspace(src[i])) i++;
    while (i < strlen(src)) src[j++] = src[i++];
    src[j] = '\0';
}

void trim_back(char *src) {
    char *ch = src + strlen(src) - 1;
    while (isspace(*ch)) *ch-- = '\0';
}

If you know you don't have to deal with trailing or leading spaces, your task becomes much simpler.

void reduce_spaces(char *src) {
    size_t i = 0, j = 0;

    for (; i < strlen(src); ++i) {
        if (i == strlen(src) - 1 ||
            (isspace(src[i]) && !isspace(src[i + 1])) ||
            !isspace(src[i])) {
            src[j++] = src[i];
        }
    }

    src[j] = '\0';
}

And testing this:

int main(void) {
    char s[] = "     hello    world     ";

    trim_front(s);
    trim_back(s);
    reduce_spaces(s);

    printf(">%s<\n", s);

    return 0;
}

% gcc test.c
% ./a.out
>hello world<
%

Of course, if you really want to, you can transplant the code from those functions into reduce_spaces, but decomposing a problem into multiple smaller problems can make things much easier.


问:
Python Exceptions difficulty
I am trying to complete a lab soon but I am having difficulty, the prompt is:

A pedometer treats walking 2,000 steps as walking 1 mile. Write a steps_to_miles() function that takes the number of steps as a parameter and returns the miles walked. The steps_to_miles() function throws a ValueError object with the message "Exception: Negative step count entered." when the number of steps is negative. Complete the main() program that reads the number of steps from a user, calls the steps_to_miles() function, and outputs the returned value from the steps_to_miles() function. Use a try-except block to catch any ValueError object thrown by the steps_to_miles() function and output the exception message.

Output each floating-point value with two digits after the decimal point, which can be achieved as follows:
print('{:.2f}'.format(your_value))

I have been working on it for awhile now, my code is:

```<code>def steps_to_miles():

  steps = int(input())

     if steps < 0:

        raise ValueError

    return steps

if __name__ == '__main__':

    try:
        steps = steps_to_miles()

        miles_walked = float(steps / 2000)
        print('{:.2f}'.format(miles_walked))

    except ValueError:
        print('Exception: Negative step count entered.')
</code>```

(Sorry for formatting errors...) The code runs but is only giving me 4 out of the 10 points due to Zybooks stating "test_passed function missing" and "Test stepsToMiles(-3850), should throw an exception". What am I missing or how can fix it? Or alternatively is there another way to write the code?

答:
You may need to make your error message a variable, in regards to your zyBooks giving you this error: "Test stepsToMiles(-3850).

I would try this in your function: raise ValueError('Exception: Negative step count entered.')
I would also write in this in your final "except" statement.

```<code>except ValueError as err:
     print(err)
</code>```

Title: Python Exceptions difficulty

Body:
I am trying to complete a lab soon but I am having difficulty, the prompt is:

A pedometer treats walking 2,000 steps as walking 1 mile. Write a steps_to_miles() function that takes the number of steps as a parameter and returns the miles walked. The steps_to_miles() function throws a ValueError object with the message "Exception: Negative step count entered." when the number of steps is negative. Complete the main() program that reads the number of steps from a user, calls the steps_to_miles() function, and outputs the returned value from the steps_to_miles() function. Use a try-except block to catch any ValueError object thrown by the steps_to_miles() function and output the exception message.

Output each floating-point value with two digits after the decimal point, which can be achieved as follows:
print('{:.2f}'.format(your_value))

I have been working on it for awhile now, my code is:

def steps_to_miles():

  steps = int(input())

     if steps < 0:

        raise ValueError

    return steps

if __name__ == '__main__':

    try:
        steps = steps_to_miles()

        miles_walked = float(steps / 2000)
        print('{:.2f}'.format(miles_walked))

    except ValueError:
        print('Exception: Negative step count entered.')

(Sorry for formatting errors...) The code runs but is only giving me 4 out of the 10 points due to Zybooks stating "test_passed function missing" and "Test stepsToMiles(-3850), should throw an exception". What am I missing or how can fix it? Or alternatively is there another way to write the code?

Body:
You may need to make your error message a variable, in regards to your zyBooks giving you this error: "Test stepsToMiles(-3850).

I would try this in your function: raise ValueError('Exception: Negative step count entered.')
I would also write in this in your final "except" statement.

except ValueError as err:
     print(err)


问:
How to reduce number of checkpoint files writen by spark streaming
If spark streaming job involves shuffle and stateful processing, it's easy to generate lots of small files per micro batch. We should decrease the number of files without hurting latency.</p>

答:
If using all default configs, one spark streaming micro batch will generate 80 k files. This will casue high qps and latency for hdfs. Better change below configs to reduce checkpoint files.

Config
Default
Suggested

spark.sql.streaming.minBatchesToRetain
100
30

spark.sql.streaming.stateStore.minDeltasForSnapshot
10
5

spark.sql.shuffle.partitions
200
Depends on micro batch size, 50 or 100

So, total number of files = minBatchesToRetain * 4 (left 2 + right 2) * partitions * operators(each join or aggregation)

If all config are default, it will be 100 * 4 * 200 * 1 = 80 K


问:
google analytics and CRM integration
On this page, https://developers.google.com/analytics/solutions/crm-integration#summary-of-crm-data-integration-options-for-google-analytics ,

at the end of the table, for measure "Your Google Analytics profile based on user Id only shows activity for authenticated users". What does authenticated users mean in this case?

答:
I'd use an ETL tool for combining the data from a Google Analytics account and a CRM software. The reason for doing that is so you can normalize the data.
The authentication is typically handled by the ETL vendor through API access key or OAuth log in.

There're a lot of tools that do this, Fivetran, Acho, Stitch and others.

Title: google analytics and CRM integration


问:
Created kubeconfig file but only able to access default namespace
I used below file to create service account

```<code>apiVersion: v1
kind: ServiceAccount
metadata:
  name: sa-reader
  namespace: default

---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  annotations:
    rbac.authorization.kubernetes.io/autoupdate: "true"
  name: reader-cr
rules:
- apiGroups:
  - ""
  resources:
  - '*'
  verbs:
  - get
  - list
  - watch
- apiGroups:
  - extensions
  resources:
  - '*'
  verbs:
  - get
  - list
  - watch
- apiGroups:
  - apps
  resources:
  - '*'
  verbs:
  - get
  - list
  - watch

---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: read-only-rb
subjects:
- kind: ServiceAccount
  name: sa-reader
roleRef:
  kind: ClusterRole
  name: reader-cr
  apiGroup: rbac.authorization.k8s.io
</code>```

The kubeconfig I created is something similar

```<code>apiVersion: v1
kind: Config
preferences: {}

clusters:
- name: qa
  cluster:
    certificate-authority-data: ca
    server: https:/<server>:443

users:
- name: sa-reader
  user:
    as-user-extra: {}
    token: <token>

contexts:
- name: qa
  context:
    cluster: qa
    user: sa-reader
    namespace: default

current-context: qa
</code>```

With this kubeconfig file, I am able to access resources in the default namespace but not any other namespace. How to access resources in other namespaces as well?

答:
You can operate on a namespace explicitly by using the -n (--namespace) option to kubectl:

```<code>$ kubectl -n my-other-namespace get pod
</code>```

Or by changing your default namespace with the kubectl config command:

```<code>$ kubectl config set-context --current --namespace my-other-namespace
</code>```

With the above command, all future invocations of kubectl will assume the my-other-namespace namespace.

Body:
I used below file to create service account

apiVersion: v1
kind: ServiceAccount
metadata:
  name: sa-reader
  namespace: default

---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  annotations:
    rbac.authorization.kubernetes.io/autoupdate: "true"
  name: reader-cr
rules:
- apiGroups:
  - ""
  resources:
  - '*'
  verbs:
  - get
  - list
  - watch
- apiGroups:
  - extensions
  resources:
  - '*'
  verbs:
  - get
  - list
  - watch
- apiGroups:
  - apps
  resources:
  - '*'
  verbs:
  - get
  - list
  - watch

---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: read-only-rb
subjects:
- kind: ServiceAccount
  name: sa-reader
roleRef:
  kind: ClusterRole
  name: reader-cr
  apiGroup: rbac.authorization.k8s.io

The kubeconfig I created is something similar

apiVersion: v1
kind: Config
preferences: {}

clusters:
- name: qa
  cluster:
    certificate-authority-data: ca
    server: https:/<server>:443

users:
- name: sa-reader
  user:
    as-user-extra: {}
    token: <token>

contexts:
- name: qa
  context:
    cluster: qa
    user: sa-reader
    namespace: default

current-context: qa

With this kubeconfig file, I am able to access resources in the default namespace but not any other namespace. How to access resources in other namespaces as well?

Body:
You can operate on a namespace explicitly by using the -n (--namespace) option to kubectl:

$ kubectl -n my-other-namespace get pod

Or by changing your default namespace with the kubectl config command:

$ kubectl config set-context --current --namespace my-other-namespace

With the above command, all future invocations of kubectl will assume the my-other-namespace namespace.


问:
ASP.NET Button click redirect to new page
I have created a Button programmatically.
I now want to redirect to a new aspx page on the click of this Button, such that we will enter into one of the methods of the new page (like page_load(), etc.)

Is this possible?

Eg:

```<code>Button oButton = new Button;
oButton.Text = "NextPage";
// Redirect to "Redirect.aspx" on click
</code>```

But I am not able to find an entry point in Redirect.aspx where I can do some changes to the UI components once we get redirected to "Redirect.aspx"

Regards,

Parag

答:
You could also use the PostBackUrl property of the Button - this will post to the page specified, and if you need to access items from the previous page you can use the PreviousPage property:

```<code>Button oButton = new Button;
oButton.Text = "NextPage";
oButton.PostBackUrl = "Redirect.aspx";
</code>```

Then in you wanted to get the value from, say, a TextBox on the previous page with an id of txtMyInput, you could do this (very simple example to give you an idea):

```<code>void Page_Load(object sender, EventArgs e)
{

   string myInputText = ((TextBox)PreviousPage.FindControl("txtMyInput")).Text;

   // Do something with/based on the value.

}
</code>```

Just another example of how to accomplish what I think you're asking.

See Button.PostBackUrl Property for more info.

Body:
I have created a Button programmatically.
I now want to redirect to a new aspx page on the click of this Button, such that we will enter into one of the methods of the new page (like page_load(), etc.)

Is this possible?

Eg:

Button oButton = new Button;
oButton.Text = "NextPage";
// Redirect to "Redirect.aspx" on click

But I am not able to find an entry point in Redirect.aspx where I can do some changes to the UI components once we get redirected to "Redirect.aspx"

Regards,

Parag

Body:
You could also use the PostBackUrl property of the Button - this will post to the page specified, and if you need to access items from the previous page you can use the PreviousPage property:

Button oButton = new Button;
oButton.Text = "NextPage";
oButton.PostBackUrl = "Redirect.aspx";

Then in you wanted to get the value from, say, a TextBox on the previous page with an id of txtMyInput, you could do this (very simple example to give you an idea):

void Page_Load(object sender, EventArgs e)
{

   string myInputText = ((TextBox)PreviousPage.FindControl("txtMyInput")).Text;

   // Do something with/based on the value.

}

Just another example of how to accomplish what I think you're asking.

See Button.PostBackUrl Property for more info.