问:
Azure Data Factory Copying a cell value incorrectly when copying data from Azure Blob Storage To Azure SQLDB
I am in the process of building a grocery list app with Azure.

Currently, I have an azure function that writes json files to blob storage. Here is what my current blob storage looks like:

When Azure data factory copies over the data to my SQL DB, this is what it looks like:

Here is the code that I am using to create my table:

```<code>-- Create a new table called 'groceryitems' in schema 'grocerylistapp'
-- Drop the table if it already exists
IF OBJECT_ID('grocerylistapp.groceryitems', 'U') IS NOT NULL
DROP TABLE grocerylistapp.groceryitems
GO

CREATE SCHEMA grocerylistapp
GO

-- Create the table in the specified schema
CREATE TABLE grocerylistapp.groceryitems
(
    id INT IDENTITY(1,1), -- Primary Key column
    epoch DATE,
    [name] VARCHAR(50),
    PRIMARY KEY CLUSTERED([id] ASC)
    -- Specify more columns here
);
GO
1
</code>```

Oddly enough, when I originally did this with Data Warehouse / Synapse, I didn't get this issue, so I am assuming it is something to do particularly with SQL DB.

I also want to add that it randomly decides to distort one row, if I had 3,4, or 5 items in blob storage, it would pick one row and distort it as shown in the screenshot. It is not always the same item.

Thank you.

答:
Firstly, make sure you have chosen the json format file as Soure dataset.

Here're the steps I tested,  and it works well.

Source dataset(json format) from Blob storage:

Import the cchema of the source dataset:

Sink dataset settings:

Mapping settings:

Run the pipeline:

Check the data in table grocerylistapp.groceryitems:

Hope this helps.

Body:
I am in the process of building a grocery list app with Azure.

Currently, I have an azure function that writes json files to blob storage. Here is what my current blob storage looks like:

When Azure data factory copies over the data to my SQL DB, this is what it looks like:

Here is the code that I am using to create my table:

-- Create a new table called 'groceryitems' in schema 'grocerylistapp'
-- Drop the table if it already exists
IF OBJECT_ID('grocerylistapp.groceryitems', 'U') IS NOT NULL
DROP TABLE grocerylistapp.groceryitems
GO

CREATE SCHEMA grocerylistapp
GO

-- Create the table in the specified schema
CREATE TABLE grocerylistapp.groceryitems
(
    id INT IDENTITY(1,1), -- Primary Key column
    epoch DATE,
    [name] VARCHAR(50),
    PRIMARY KEY CLUSTERED([id] ASC)
    -- Specify more columns here
);
GO
1

Oddly enough, when I originally did this with Data Warehouse / Synapse, I didn't get this issue, so I am assuming it is something to do particularly with SQL DB.

I also want to add that it randomly decides to distort one row, if I had 3,4, or 5 items in blob storage, it would pick one row and distort it as shown in the screenshot. It is not always the same item.

Thank you.


来源: stackexchange

问:
Make header available on all components except on login
Supposed I am importing a header component on layouts/default.vue

```<code><template>
  <div>
    <b-container class="mt-5">
      <b-row>
        <b-col md="6" class="mb-3">
          <Header />
        </b-col>
        <b-col md="6">
          <nuxt />
        </b-col>
      </b-row>
    </b-container>
    <Header/>
    <nuxt/>
  </div>
</template>

<script>
import Header from "@/components/Header.vue";

export default {
  components: {
    Header
  }
};
</script>

<style>
...
</style>
</code>```

and that header will be render on all components.

My question is how can I make the header available on all components except on my Login.vue?

Any idea on where can I start to achieve this.

答:
The current route path is '$route.path',so use 'v-show' to judge.
    </p>

ContentLicense: CC BY-SA 4.0

Body:
Supposed I am importing a header component on layouts/default.vue

<template>

          <nuxt />

    <nuxt/>

</template>

and that header will be render on all components.

My question is how can I make the header available on all components except on my Login.vue?

Any idea on where can I start to achieve this.


问:
Is there a way via excel vba to check the contents of a msgbox displayed by an external macro?
Suppose that I am creating a macro that needs to call another excel application's macro which I DO NOT HAVE ACCESS OR RIGHTS TO CHANGE ITS CODE.

Now, in my macro that is calling that other excel application, whenever that other excel application displays a MSGBOX, the process in my macro stops unless I click that MSGBOX.

Now I want to be able to get the message in the displayed MSGBOX and also be able to click its "OK" button.

Is that possible via vba (which means no user interaction)?

BTW, I am using Application.Run to run the other excel application's macro which will create another instance.(Since it spawns 2 MS Excel processes in the Task Manager)

答:
I was able to do what I want by using SendKeys.
Basically what I did was:

```<code>SendKeys "^c" 'copies the text inside the MsgBox
SendKeys "~" 'clicks the "OK" button
Application.Run (OtherExcel.xlsm!Module1.Function)
</code>```

I don't know why but it works. All I need to do now is to get the copied text from the clipboard.

Body:
I was able to do what I want by using SendKeys.
Basically what I did was:

SendKeys "^c" 'copies the text inside the MsgBox
SendKeys "~" 'clicks the "OK" button
Application.Run (OtherExcel.xlsm!Module1.Function)

I don't know why but it works. All I need to do now is to get the copied text from the clipboard.


问:
priority queue and structs
```<code>#include <iostream>
#include <queue>
using namespace std;
struct Call
{
    Call( int callNum, long callTime, int callLength ) :
    CallNum( callNum ), CallTime( callTime ), CallLength( callLength ) { }
    int CallNum;
    long CallTime;
    int CallLength;
};

bool operator>( const Call& lhs, const Call& rhs ) {
    return lhs.CallLength > rhs.CallLength;
}

ostream& operator<<( ostream& os, const Call& c ) {
    os << c.CallNum << " " << c.CallTime << " " << c.CallLength;
    return os;
}

int main()
{
    priority_queue< Call, vector<Call>, greater<Call> > q;
    q.push( Call( 1, 200, 150 ));
    q.push( Call( 2, 300, 950 ));
    q.push( Call( 3, 100, 450 ));
    q.push( Call( 4, 150, 320 ));
    unsigned i=0, n=q.size();
    for ( i=0; i<n; ++i ) {
        cout << q.top() << endl;
        q.pop();
    }
}
</code>```

This is my code. My problem is, When I use q.top(); it prints to screen callNum, callTime, callLength. But I want to use them seperately.

I mean How can I print to screen just callTime? for ex: q.top(callTime); or something else? who can help me?

答:
Are you just looking for:

```<code>cout << q.top().CallNum << endl;
</code>```

and so on?

ContentLicense: CC BY-SA 3.0

Title: priority queue and structs

Body:
#include <iostream>
#include <queue>
using namespace std;
struct Call
{
    Call( int callNum, long callTime, int callLength ) :
    CallNum( callNum ), CallTime( callTime ), CallLength( callLength ) { }
    int CallNum;
    long CallTime;
    int CallLength;
};

bool operator>( const Call& lhs, const Call& rhs ) {
    return lhs.CallLength > rhs.CallLength;
}

ostream& operator<<( ostream& os, const Call& c ) {
    os << c.CallNum << " " << c.CallTime << " " << c.CallLength;
    return os;
}

int main()
{
    priority_queue< Call, vector<Call>, greater<Call> > q;
    q.push( Call( 1, 200, 150 ));
    q.push( Call( 2, 300, 950 ));
    q.push( Call( 3, 100, 450 ));
    q.push( Call( 4, 150, 320 ));
    unsigned i=0, n=q.size();
    for ( i=0; i<n; ++i ) {
        cout << q.top() << endl;
        q.pop();
    }
}

This is my code. My problem is, When I use q.top(); it prints to screen callNum, callTime, callLength. But I want to use them seperately.

I mean How can I print to screen just callTime? for ex: q.top(callTime); or something else? who can help me?

Body:
Are you just looking for:

cout << q.top().CallNum << endl;

and so on?


问:
How can I average the data from text file?
I have a text file with two columns and I want to average the second column, while ignoring the first one. I'm new to programming, I hope you can help.

Input File

答:
Have you tried pandas?

```<code>import pandas as pd
df=pd.read_csv(file, sep="\t") #assuming you have a tab (\t) separated file
df["xy"].mean()
</code>```

Body:
Have you tried pandas?

import pandas as pd
df=pd.read_csv(file, sep="\t") #assuming you have a tab (\t) separated file
df["xy"].mean()


问:
Update field in SQL on particular line matching search syntax
I have a table in SQLite3 called MachineData with the following headers:

ResourceId (Primary Key)

MachineName

PrimaryUser

The table has the ResourceId populated and I need to do a lookup against the ResourceId and inject data along the row.

I have tried the following statements, but it doesn't like my syntax. Any help would be appreciated?

INSERT INTO MachineData (PrimaryUser) VALUES ('Mickey Mouse') WHERE ResourceId LIKE '1001'
```

<p>and also</p>

```INSERT INTO MachineData (PrimaryUser) VALUES ('Mickey Mouse') WHERE (SELECT ResourceId FROM MachineData LIKE '1001')
```

<p>and also</p>

```INSERT INTO MachineData (PrimaryUser) VALUES ('Mickey Mouse') WHERE ResourceId EQUALS '1001'
```

<p>None of these have decided to play nice, always giving me logic error.</p>

<p>The table looks like this:</p>

<p><code>TABLENAME: MachineData</code></p>

```| ResourceId | MachineName | PrimaryUser |
|============|=============|=============|
| 1001       |             |             |
| 1002       |             |             |
| 1003       |             |             |
```

<p>I want to make it look like this:</p>

```| ResourceId | MachineName  | PrimaryUser  |
|============|==============|==============|
| 1001       |              | Mickey Mouse |
| 1002       |              |              |
| 1003       |              |              |
```

答:
Do you want an update?

```<code>UPDATE MachineData
    SET PrimaryUser = 'Mickey Mouse'
    WHERE ResourceId LIKE '1001';
</code>```

I am guessing that ResourceId is a number.  If so, you should not use string operations:

```<code>UPDATE MachineData
    SET PrimaryUser = 'Mickey Mouse'
    WHERE ResourceId LIKE 1001;
</code>```

Body:
I have a table in SQLite3 called MachineData with the following headers:

ResourceId (Primary Key)

MachineName

PrimaryUser

The table has the ResourceId populated and I need to do a lookup against the ResourceId and inject data along the row.

I have tried the following statements, but it doesn't like my syntax. Any help would be appreciated?

INSERT INTO MachineData (PrimaryUser) VALUES ('Mickey Mouse') WHERE ResourceId LIKE '1001'

and also

INSERT INTO MachineData (PrimaryUser) VALUES ('Mickey Mouse') WHERE (SELECT ResourceId FROM MachineData LIKE '1001')

and also

INSERT INTO MachineData (PrimaryUser) VALUES ('Mickey Mouse') WHERE ResourceId EQUALS '1001'

None of these have decided to play nice, always giving me logic error.

The table looks like this:

TABLENAME: MachineData

| ResourceId | MachineName | PrimaryUser |
|============|=============|=============|
| 1001       |             |             |
| 1002       |             |             |
| 1003       |             |             |

I want to make it look like this:

| ResourceId | MachineName  | PrimaryUser  |
|============|==============|==============|
| 1001       |              | Mickey Mouse |
| 1002       |              |              |
| 1003       |              |              |

Body:
Do you want an update?

UPDATE MachineData
    SET PrimaryUser = 'Mickey Mouse'
    WHERE ResourceId LIKE '1001';

I am guessing that ResourceId is a number.  If so, you should not use string operations:

UPDATE MachineData
    SET PrimaryUser = 'Mickey Mouse'
    WHERE ResourceId LIKE 1001;


问:
Mongoose retrieve array of objects. For each object, I only want two properties
I am just practicing Mongoose with JavaScript.

I have this mongoose schema below:

```<code>const item = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    unique: true
  },
  qty: {
    type: Number,
    required: true
  },
  costPrice: Number
});

const supplySchema = new mongoose.Schema({
  items: [item]
});

const Supply = mongoose.model("Supply", supplySchema);
</code>```

Right now I just want to retrieve an array of item using mongoose.

I wish my data to look like this:

```<code>[
  {
    "name" : "Lemon",
    "qty" : 5
  },
  {
    "name": "Sugar",
    "qty": 5
  }
]

</code>```

But right now the data I get back looks something like this:

```<code>[
  {
    "_id": "5e4df1c1d48926133879f650",
    "costPrice": 0.4,
    "name": "Sugar",
    "qty": 5
  }
]
</code>```

I tried writing such a code below but it does not work:

```<code>const supplyDoc = await Supply.findOne();
const supplies = await supplyDoc.items.select("-_id");
return supplies;
</code>```

I thought I could somehow use projection on the items and specify that I don't want the _id property for each object in the array. But my code does not work. Is there a mongoose or MongoDB method I can utilize? Or do I have to use javascript to manipulate the array?

Hope to hear some advice. thank you!

答:
First of all you should use Model.find() instead of Model.findOne() if you want an array of items.

And yes you can use the projection parameter to select the fields you want.

So

const supplies = await Supply.find({}, "name qty").exec()
```

<p>Edit: So apparently you need to specifically exclude the _id field, you can do this using <code>-</code> as prefix.</p>

<pre class="lang-js prettyprint-override"><code>const supplies = await Supply.find({}, "-_id name qty").exec()
</code>```

Body:
I am just practicing Mongoose with JavaScript.

I have this mongoose schema below:

const item = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    unique: true
  },
  qty: {
    type: Number,
    required: true
  },
  costPrice: Number
});

const supplySchema = new mongoose.Schema({
  items: [item]
});

const Supply = mongoose.model("Supply", supplySchema);

Right now I just want to retrieve an array of item using mongoose.

I wish my data to look like this:

[
  {
    "name" : "Lemon",
    "qty" : 5
  },
  {
    "name": "Sugar",
    "qty": 5
  }
]

But right now the data I get back looks something like this:

[
  {
    "_id": "5e4df1c1d48926133879f650",
    "costPrice": 0.4,
    "name": "Sugar",
    "qty": 5
  }
]

I tried writing such a code below but it does not work:

const supplyDoc = await Supply.findOne();
const supplies = await supplyDoc.items.select("-_id");
return supplies;

I thought I could somehow use projection on the items and specify that I don't want the _id property for each object in the array. But my code does not work. Is there a mongoose or MongoDB method I can utilize? Or do I have to use javascript to manipulate the array?

Hope to hear some advice. thank you!

Body:
First of all you should use Model.find() instead of Model.findOne() if you want an array of items.

And yes you can use the projection parameter to select the fields you want.

So

const supplies = await Supply.find({}, "name qty").exec()

Edit: So apparently you need to specifically exclude the _id field, you can do this using - as prefix.

const supplies = await Supply.find({}, "-_id name qty").exec()


问:
Shell script mode automatically at each emacs start
Each time when I edit bash script I type a command M-x shell-script-mode. And then I get nice shell code higlighting. How to get it automatically each time I start emacs so I do not have to type the command. When I added (shell-script-mode) to init.el it did not help.

答:
One of the simplest ways to have Emacs set the desired mode for a buffer editing a file is to include a special comment in the first line of that file, e.g. for a shell script your first line might be:

```<code># -*-sh-*-
</code>```

For scripts it is also common, or and often even required, to have an interpreter file comment on the very first line of the file, which of course would preclude having an Emacs mode comment, so Emacs also looks for interpreter file comments and associates those with a major mode, so the first line of your shell script might be:

```<code>#!/bin/sh
</code>```

There are a number of other ways to tell Emacs how to set the buffer mode when visiting a file.  See, for example, Emacs Manual: Choosing File Modes

Body:
One of the simplest ways to have Emacs set the desired mode for a buffer editing a file is to include a special comment in the first line of that file, e.g. for a shell script your first line might be:

# -*-sh-*-

For scripts it is also common, or and often even required, to have an interpreter file comment on the very first line of the file, which of course would preclude having an Emacs mode comment, so Emacs also looks for interpreter file comments and associates those with a major mode, so the first line of your shell script might be:

#!/bin/sh

There are a number of other ways to tell Emacs how to set the buffer mode when visiting a file.  See, for example, Emacs Manual: Choosing File Modes


问:
Could someone explain why my code is not working properly?
i am doing a challenge but for some reason every time i run it says 3 outta of 7 test cases are incorrect and don't know why? everything seems in order. Here is the challenge if Task
Given an integer, , perform the following conditional actions:

If  is odd, print Weird
If  is even and in the inclusive 2 range of 5 to , print Not Weird
If  is even and in the inclusive range of 6 to 20, print Weird
If  is even and greater than 20, print Not Weird

My code below:

```<code>n = int(input().strip())
if n % 2 != 0:
    print("Weird")
else:
    if n % 2 == 1 and n in range(2,5):
        print("Not Weird")

    elif n % 2 == 1 and n in range(6,20):
        print("Weird")

    elif n > 20:
        print("Not Weird")
</code>```

答:
Try this</p>

```<code>n = int(input().strip())
if n % 2 != 0:
    print("Weird")
else:
    if n in range(2,6):
        print("Not Weird")

    elif n in range(6,21):
        print("Weird")

    elif n > 20:

 print("Not Weird"
</code>```

Body:
i am doing a challenge but for some reason every time i run it says 3 outta of 7 test cases are incorrect and don't know why? everything seems in order. Here is the challenge if Task
Given an integer, , perform the following conditional actions:

If  is odd, print Weird
If  is even and in the inclusive 2 range of 5 to , print Not Weird
If  is even and in the inclusive range of 6 to 20, print Weird
If  is even and greater than 20, print Not Weird

My code below:

n = int(input().strip())
if n % 2 != 0:
    print("Weird")
else:
    if n % 2 == 1 and n in range(2,5):
        print("Not Weird")

    elif n % 2 == 1 and n in range(6,20):
        print("Weird")

    elif n > 20:
        print("Not Weird")

Body:
Try this

n = int(input().strip())
if n % 2 != 0:
    print("Weird")
else:
    if n in range(2,6):
        print("Not Weird")

    elif n in range(6,21):
        print("Weird")

    elif n > 20:

 print("Not Weird"


问:
How to write to a .wav file using a generated wave, complex[] array?
I would like to know how to write to a .wav file, I have written the following code which supposedly writes data to the file. But when I try to play the sound file it says the file is corrupt / empty.

```<code> try
            {
                SaveFileDialog save = new SaveFileDialog();
                save.Filter = "Wave File (*.wav)|*.wav;";
                if (save.ShowDialog() != System.Windows.Forms.DialogResult.OK)
                    return;

                using (FileStream FS = new FileStream(save.FileName, FileMode.Open, FileAccess.Write))
                {
                    BinaryWriter wr = new BinaryWriter(FS);

                    int subchunk1Size = 16;
                    short audioFormat = 1;
                    short bitsPerSample = 64;
                    short numChannels = 2;
                    int sampleRate = Convert.ToInt32(samplingRateBox.Text);
                    int byteRate = sampleRate * numChannels * (bitsPerSample / 8);
                    short blockAlign = (short)(numChannels * (bitsPerSample / 8));
                    int numSamples = Convert.ToInt32(numberOfsamplesBox.Text);

                    int subChunk2Size = numSamples * numChannels * (bitsPerSample / 8);

                    int chunkSize = 4 + (8 + subchunk1Size) + (8 + subChunk2Size);

                    wr.Write(getBytes("RIFF"));
                    wr.Write(chunkSize);
                    wr.Write(getBytes("WAVE"));
                    wr.Write(getBytes("fmt"));
                    wr.Write((byte)32);
                    wr.Write(subchunk1Size);
                    wr.Write(audioFormat);
                    wr.Write(numChannels);
                    wr.Write(sampleRate);
                    wr.Write(byteRate);
                    wr.Write(blockAlign);
                    wr.Write(bitsPerSample);
                    wr.Write(getBytes("data"));
                    wr.Write(subChunk2Size);

                    double[] primArray = new double[samples.Length];
                    byte[] byteArray = new byte[samples.Length * 8];

                    for (int i = 0; i < samples.Length; i++)
                    {
                        primArray[i] = Convert.ToDouble(samples[i].Real);
                    }

                    byteArray = doubleToBytes(primArray);

                    for (int i = 0; i < samples.Length; i++)
                    {
                        wr.Write(byteArray[i]);
                    }

                    for (int i = 0; i < samples.Length; i++)
                    {
                        primArray[i] = Convert.ToDouble(samples[i].Imaginary);
                    }

                    byteArray = doubleToBytes(primArray);

                    for (int i = 0; i < samples.Length; i++)
                    {
                        wr.Write(byteArray[i]);
                    }

                    wr.Close();
                    wr.Dispose();
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
</code>```

As you can see I have tried converting from Complex to double, plus the header.
The sampling rate and number of samples all come from textboxes. Plus I am assuming the bit depth is that of a double.

答:
I have also tried using this method, however the length of the audio file is 0.

This used the NAudio library.

```<code>NAudio.Wave.WaveFileWriter waveWriter = null;
            WaveIn wi = new WaveIn();

            double[] primArray = new double[samples.Length];

            for (int i = 0; i < samples.Length; i++)
            {
                primArray[i] = Convert.ToDouble(samples[i].Real);
            }

            SaveFileDialog save = new SaveFileDialog();
            save.Filter = "Wave File (*.wav)|*.wav;";
            if (save.ShowDialog() != System.Windows.Forms.DialogResult.OK)
                return;

            wi = new NAudio.Wave.WaveIn();
            wi.WaveFormat = new WaveFormat(samplingRate,1);

            waveWriter = new WaveFileWriter(save.FileName, wi.WaveFormat);

            byte[] byteArray = new byte[samples.Length*8];

            byteArray = doubleToBytes(primArray);

            waveWriter.Write(byteArray, 0, byteArray.Length);
</code>```

Body:
I would like to know how to write to a .wav file, I have written the following code which supposedly writes data to the file. But when I try to play the sound file it says the file is corrupt / empty.

 try
            {
                SaveFileDialog save = new SaveFileDialog();
                save.Filter = "Wave File (*.wav)|*.wav;";
                if (save.ShowDialog() != System.Windows.Forms.DialogResult.OK)
                    return;

                using (FileStream FS = new FileStream(save.FileName, FileMode.Open, FileAccess.Write))
                {
                    BinaryWriter wr = new BinaryWriter(FS);

                    int subchunk1Size = 16;
                    short audioFormat = 1;
                    short bitsPerSample = 64;
                    short numChannels = 2;
                    int sampleRate = Convert.ToInt32(samplingRateBox.Text);
                    int byteRate = sampleRate * numChannels * (bitsPerSample / 8);
                    short blockAlign = (short)(numChannels * (bitsPerSample / 8));
                    int numSamples = Convert.ToInt32(numberOfsamplesBox.Text);

                    int subChunk2Size = numSamples * numChannels * (bitsPerSample / 8);

                    int chunkSize = 4 + (8 + subchunk1Size) + (8 + subChunk2Size);

                    wr.Write(getBytes("RIFF"));
                    wr.Write(chunkSize);
                    wr.Write(getBytes("WAVE"));
                    wr.Write(getBytes("fmt"));
                    wr.Write((byte)32);
                    wr.Write(subchunk1Size);
                    wr.Write(audioFormat);
                    wr.Write(numChannels);
                    wr.Write(sampleRate);
                    wr.Write(byteRate);
                    wr.Write(blockAlign);
                    wr.Write(bitsPerSample);
                    wr.Write(getBytes("data"));
                    wr.Write(subChunk2Size);

                    double[] primArray = new double[samples.Length];
                    byte[] byteArray = new byte[samples.Length * 8];

                    for (int i = 0; i < samples.Length; i++)
                    {
                        primArray[i] = Convert.ToDouble(samples[i].Real);
                    }

                    byteArray = doubleToBytes(primArray);

                    for (int i = 0; i < samples.Length; i++)
                    {
                        wr.Write(byteArray[i]);
                    }

                    for (int i = 0; i < samples.Length; i++)
                    {
                        primArray[i] = Convert.ToDouble(samples[i].Imaginary);
                    }

                    byteArray = doubleToBytes(primArray);

                    for (int i = 0; i < samples.Length; i++)
                    {
                        wr.Write(byteArray[i]);
                    }

                    wr.Close();
                    wr.Dispose();
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }

As you can see I have tried converting from Complex to double, plus the header.
The sampling rate and number of samples all come from textboxes. Plus I am assuming the bit depth is that of a double.

Body:
I have also tried using this method, however the length of the audio file is 0.

This used the NAudio library.

NAudio.Wave.WaveFileWriter waveWriter = null;
            WaveIn wi = new WaveIn();

            double[] primArray = new double[samples.Length];

            for (int i = 0; i < samples.Length; i++)
            {
                primArray[i] = Convert.ToDouble(samples[i].Real);
            }

            SaveFileDialog save = new SaveFileDialog();
            save.Filter = "Wave File (*.wav)|*.wav;";
            if (save.ShowDialog() != System.Windows.Forms.DialogResult.OK)
                return;

            wi = new NAudio.Wave.WaveIn();
            wi.WaveFormat = new WaveFormat(samplingRate,1);

            waveWriter = new WaveFileWriter(save.FileName, wi.WaveFormat);

            byte[] byteArray = new byte[samples.Length*8];

            byteArray = doubleToBytes(primArray);

            waveWriter.Write(byteArray, 0, byteArray.Length);


问:
get-azurekeyvaultkey does not return "public key"
I am just testing out Azure Key Vault with key/pairs and am attempting to retrieve the public key.

I first created a Key Vault (name = "VaultTest") using Azure portal.

I then created a Key (Name = "TestKey1") again using Azure portal.

I see the key in the portal and when I click on it I see the following information:

Properties:

```<code>Key Type: RSA

RSA Key Size 2048

Created: "date time"

Updated: "date time"

Key Identifier: //vault path/keys/TestKey1/Key identifier
</code>```

Settings:

```<code>Set activation date: "unchecked"

Set expiration date: "unchecked"

Enabled: True

Tags "none"

Permitted operations:

Encrypt: true

Decrypt: true

Sign: true

Verify: true

Wrap key: true

Unwrap key: true
</code>```

Notice that there is no public key information displayed so I switched over to Azure Cloud Shell and executed the following command:

```<code>Get-AzureKeyVaultKey -vaultname 'VaultTest' -name 'TestKey1'
</code>```

It returns VaultName, Name, Version, Id, Enabled, Expires, Not Before, Created, Updated, Purge Disabled and Tags, but no Key.

All the examples I read online (albeit somewhat old) show fields Attributes and Key being returned but those are not returning for me.

I read somewhere that if you call the URI it will return the public key info, so I copy/pasted the URI into a browser but this returns to me:

{"error":{"code":"Unauthorized","message":"Request is missing a Bearer or PoP token."}}

Am I doing something brain dead or has the function get-azurekeyvaultkey changed? If it has changed how does one get the public key information for a specific key stored in Key Vault?

答:
I can reproduce your issue with Get-AzureKeyVaultKey -vaultname 'VaultTest' -name 'TestKey1'.

But actually it returns the Attributes and Key that you want, just pass the | ConvertTo-Json like below.

```<code>Get-AzureKeyVaultKey -vaultname 'VaultTest' -name 'TestKey1' | ConvertTo-Json
</code>```

Body:
I am just testing out Azure Key Vault with key/pairs and am attempting to retrieve the public key.

I first created a Key Vault (name = "VaultTest") using Azure portal.

I then created a Key (Name = "TestKey1") again using Azure portal.

I see the key in the portal and when I click on it I see the following information:

Properties:

Key Type: RSA

RSA Key Size 2048

Created: "date time"

Updated: "date time"

Key Identifier: //vault path/keys/TestKey1/Key identifier

Settings:

Set activation date: "unchecked"

Set expiration date: "unchecked"

Enabled: True

Tags "none"

Permitted operations:

Encrypt: true

Decrypt: true

Sign: true

Verify: true

Wrap key: true

Unwrap key: true

Notice that there is no public key information displayed so I switched over to Azure Cloud Shell and executed the following command:

Get-AzureKeyVaultKey -vaultname 'VaultTest' -name 'TestKey1'

It returns VaultName, Name, Version, Id, Enabled, Expires, Not Before, Created, Updated, Purge Disabled and Tags, but no Key.

All the examples I read online (albeit somewhat old) show fields Attributes and Key being returned but those are not returning for me.

I read somewhere that if you call the URI it will return the public key info, so I copy/pasted the URI into a browser but this returns to me:

{"error":{"code":"Unauthorized","message":"Request is missing a Bearer or PoP token."}}

Am I doing something brain dead or has the function get-azurekeyvaultkey changed? If it has changed how does one get the public key information for a specific key stored in Key Vault?

Body:
I can reproduce your issue with Get-AzureKeyVaultKey -vaultname 'VaultTest' -name 'TestKey1'.

But actually it returns the Attributes and Key that you want, just pass the | ConvertTo-Json like below.

Get-AzureKeyVaultKey -vaultname 'VaultTest' -name 'TestKey1' | ConvertTo-Json


问:
UWP Native Compile - This object cannot be invoked because it was metadata-enabled for browsing only
With UWP Native compile, my sample is attached and have incredibile results:

http://www.fasthomestore.it/UwpDotNativeIssues-master.zip

Unzip attached sample

Rebuild all with VS 2019 in release mode native compile

All Working Well!!

Now

Stop debug

Enter in the Manage Nutget package for TestAutomapper Project

Remove “MyToolkit.Extended” package from project (this package is not used in the solution but it is crucial to make App work)

Now REBUILD ALL

Start the App

Exception is throw:

This object cannot be invoked because it was metadata-enabled for
  browsing only:
  'System.Func,AutoMapper.ResolutionContext,System.Collections.Generic.List>.Invoke(ClassLibrary3.AnagraficaBridge,ClassLibrary3.AnagraficheSinteticheBridge,System.Collections.Generic.List,AutoMapper.ResolutionContext)'
  For more information, please visit
  http://go.microsoft.com/fwlink/?LinkID=616867'

I have try to modify my default.rd.xml for without positive results.

How can i fix this problem ?

答:
If you want to create a map between these two different types: AnagraficaBridge and AnagraficheSinteticheBridge, you need to use the following method:

TDestination Map<TSource, TDestination>(TSource source, Action<IMappingOperationOptions<TSource, TDestination>> opts);

instead of

TDestination Map<TDestination>(object source, Action<IMappingOperationOptions> opts);

The second method is used for the same type of mapping.

Update:

In addition, by my testing, you can simply get the resolutionContext in the AfterMap method to assign the value to the lists from AnagraficheSinteticheBridge class. For example:

```<code>//Initialize
var config = new MapperConfiguration(cfg =>
{
    cfg.AddCollectionMappers();

    cfg.CreateMap<TelefonoEmailBridge, TelefonoEmailBridge>();

    cfg.CreateMap<AnagraficaBridge, AnagraficheSinteticheBridge>().AfterMap((src, dest,context) =>
    {
        dest.Cognome = src.Cognome;
        dest.Telefoni = (List<TelefonoEmailBridge>)context.Items["Telefoni"];
        dest.Email = (List<TelefonoEmailBridge>)context.Items["Email"];
    });

});

......

//map
var result = BridgeDataMapper.Map<AnagraficaBridge,AnagraficheSinteticheBridge>(AnagraficaDataForm, opts =>
{
    opts.Items["Telefoni"] = BridgeDataMapper.Map<IEnumerable<TelefonoEmailBridge>>(elencoTelefoni);
    opts.Items["Email"] = BridgeDataMapper.Map<IEnumerable<TelefonoEmailBridge>>(elencoEmail);
});
</code>```

Body:
If you want to create a map between these two different types: AnagraficaBridge and AnagraficheSinteticheBridge, you need to use the following method:

TDestination Map<TSource, TDestination>(TSource source, Action<IMappingOperationOptions<TSource, TDestination>> opts);

instead of

TDestination Map<TDestination>(object source, Action<IMappingOperationOptions> opts);

The second method is used for the same type of mapping.

Update:

In addition, by my testing, you can simply get the resolutionContext in the AfterMap method to assign the value to the lists from AnagraficheSinteticheBridge class. For example:

//Initialize
var config = new MapperConfiguration(cfg =>
{
    cfg.AddCollectionMappers();

    cfg.CreateMap<TelefonoEmailBridge, TelefonoEmailBridge>();

    cfg.CreateMap<AnagraficaBridge, AnagraficheSinteticheBridge>().AfterMap((src, dest,context) =>
    {
        dest.Cognome = src.Cognome;
        dest.Telefoni = (List<TelefonoEmailBridge>)context.Items["Telefoni"];
        dest.Email = (List<TelefonoEmailBridge>)context.Items["Email"];
    });

});

......

//map
var result = BridgeDataMapper.Map<AnagraficaBridge,AnagraficheSinteticheBridge>(AnagraficaDataForm, opts =>
{
    opts.Items["Telefoni"] = BridgeDataMapper.Map<IEnumerable<TelefonoEmailBridge>>(elencoTelefoni);
    opts.Items["Email"] = BridgeDataMapper.Map<IEnumerable<TelefonoEmailBridge>>(elencoEmail);
});


问:
how to pass encrypted query string in asp.net
I need to pass values between asp.net pages. How do i encrypt those values in the URL?
Example : Response.Redirect("customerAdd.aspx?customerId=" + custId);</p>

答:
Stupidly long code file that will do it for you using full encyption:

I suggest using the SessionID as the salt, then it changes for each user but is stable across postbacks.

```<code>///////////////////////////////////////////////////////////////////////////////
// SAMPLE: Symmetric key encryption and decryption using Rijndael algorithm.
//
// To run this sample, create a new Visual C# project using the Console
// Application template and replace the contents of the Class1.cs file with
// the code below.
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
// EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
//
// Copyright (C) 2002 Obviex(TM). All rights reserved.
//
using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;
namespace TDX.Portal.Utilities
{
    /// <summary>
    /// This class uses a symmetric key algorithm (Rijndael/AES) to encrypt and
    /// decrypt data. As long as encryption and decryption routines use the same
    /// parameters to generate the keys, the keys are guaranteed to be the same.
    /// The class uses static functions with duplicate code to make it easier to
    /// demonstrate encryption and decryption logic. In a real-life application,
    /// this may not be the most efficient way of handling encryption, so - as
    /// soon as you feel comfortable with it - you may want to redesign this class.
    /// </summary>
    public class RijndaelSimple
    {
        /// <summary>
        /// Encrypts specified plaintext using Rijndael symmetric key algorithm
        /// and returns a base64-encoded result.
        /// </summary>
        /// <param name="plainText">
        /// Plaintext value to be encrypted.
        /// </param>
        /// <param name="passPhrase">
        /// Passphrase from which a pseudo-random password will be derived. The
        /// derived password will be used to generate the encryption key.
        /// Passphrase can be any string. In this example we assume that this
        /// passphrase is an ASCII string.
        /// </param>
        /// <param name="saltValue">
        /// Salt value used along with passphrase to generate password. Salt can
        /// be any string. In this example we assume that salt is an ASCII string.
        /// </param>
        /// <param name="hashAlgorithm">
        /// Hash algorithm used to generate password. Allowed values are: "MD5" and
        /// "SHA1". SHA1 hashes are a bit slower, but more secure than MD5 hashes.
        /// </param>
        /// <param name="passwordIterations">
        /// Number of iterations used to generate password. One or two iterations
        /// should be enough.
        /// </param>
        /// <param name="initVector">
        /// Initialization vector (or IV). This value is required to encrypt the
        /// first block of plaintext data. For RijndaelManaged class IV must be
        /// exactly 16 ASCII characters long.
        /// </param>
        /// <param name="keySize">
        /// Size of encryption key in bits. Allowed values are: 128, 192, and 256.
        /// Longer keys are more secure than shorter keys.
        /// </param>
        /// <returns>
        /// Encrypted value formatted as a base64-encoded string.
        /// </returns>
        public static string Encrypt(string plainText,
                                     string passPhrase,
                                     string saltValue,
                                     string hashAlgorithm,
                                     int passwordIterations,
                                     string initVector,
                                     int keySize)
        {
            // Convert strings into byte arrays.
            // Let us assume that strings only contain ASCII codes.
            // If strings include Unicode characters, use Unicode, UTF7, or UTF8
            // encoding.
            byte[] initVectorBytes = Encoding.UTF8.GetBytes(initVector);
            byte[] saltValueBytes = Encoding.UTF8.GetBytes(saltValue);

            // Convert our plaintext into a byte array.
            // Let us assume that plaintext contains UTF8-encoded characters.
            byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

            // First, we must create a password, from which the key will be derived.
            // This password will be generated from the specified passphrase and
            // salt value. The password will be created using the specified hash
            // algorithm. Password creation can be done in several iterations.
            PasswordDeriveBytes password = new PasswordDeriveBytes(
                                                            passPhrase,
                                                            saltValueBytes,
                                                            hashAlgorithm,
                                                            passwordIterations);

            // Use the password to generate pseudo-random bytes for the encryption
            // key. Specify the size of the key in bytes (instead of bits).
            byte[] keyBytes = password.GetBytes(keySize / 8);

            // Create uninitialized Rijndael encryption object.
            RijndaelManaged symmetricKey = new RijndaelManaged();

            // It is reasonable to set encryption mode to Cipher Block Chaining
            // (CBC). Use default options for other symmetric key parameters.
            symmetricKey.Mode = CipherMode.CBC;

            // Generate encryptor from the existing key bytes and initialization
            // vector. Key size will be defined based on the number of the key
            // bytes.
            ICryptoTransform encryptor = symmetricKey.CreateEncryptor(
                                                             keyBytes,
                                                             initVectorBytes);

            // Define memory stream which will be used to hold encrypted data.
            MemoryStream memoryStream = new MemoryStream();

            // Define cryptographic stream (always use Write mode for encryption).
            CryptoStream cryptoStream = new CryptoStream(memoryStream,
                                                         encryptor,
                                                         CryptoStreamMode.Write);
            // Start encrypting.
            cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);

            // Finish encrypting.
            cryptoStream.FlushFinalBlock();

            // Convert our encrypted data from a memory stream into a byte array.
            byte[] cipherTextBytes = memoryStream.ToArray();

            // Close both streams.
            memoryStream.Close();
            cryptoStream.Close();

            // Convert encrypted data into a base64-encoded string.
            string cipherText = Convert.ToBase64String(cipherTextBytes);

            // Return encrypted string.
            return cipherText;
        }

        /// <summary>
        /// Decrypts specified ciphertext using Rijndael symmetric key algorithm.
        /// </summary>
        /// <param name="cipherText">
        /// Base64-formatted ciphertext value.
        /// </param>
        /// <param name="passPhrase">
        /// Passphrase from which a pseudo-random password will be derived. The
        /// derived password will be used to generate the encryption key.
        /// Passphrase can be any string. In this example we assume that this
        /// passphrase is an ASCII string.
        /// </param>
        /// <param name="saltValue">
        /// Salt value used along with passphrase to generate password. Salt can
        /// be any string. In this example we assume that salt is an ASCII string.
        /// </param>
        /// <param name="hashAlgorithm">
        /// Hash algorithm used to generate password. Allowed values are: "MD5" and
        /// "SHA1". SHA1 hashes are a bit slower, but more secure than MD5 hashes.
        /// </param>
        /// <param name="passwordIterations">
        /// Number of iterations used to generate password. One or two iterations
        /// should be enough.
        /// </param>
        /// <param name="initVector">
        /// Initialization vector (or IV). This value is required to encrypt the
        /// first block of plaintext data. For RijndaelManaged class IV must be
        /// exactly 16 ASCII characters long.
        /// </param>
        /// <param name="keySize">
        /// Size of encryption key in bits. Allowed values are: 128, 192, and 256.
        /// Longer keys are more secure than shorter keys.
        /// </param>
        /// <returns>
        /// Decrypted string value.
        /// </returns>
        /// <remarks>
        /// Most of the logic in this function is similar to the Encrypt
        /// logic. In order for decryption to work, all parameters of this function
        /// - except cipherText value - must match the corresponding parameters of
        /// the Encrypt function which was called to generate the
        /// ciphertext.
        /// </remarks>
        public static string Decrypt(string cipherText,
                                     string passPhrase,
                                     string saltValue,
                                     string hashAlgorithm,
                                     int passwordIterations,
                                     string initVector,
                                     int keySize)
        {
            // Convert strings defining encryption key characteristics into byte
            // arrays. Let us assume that strings only contain ASCII codes.
            // If strings include Unicode characters, use Unicode, UTF7, or UTF8
            // encoding.
            byte[] initVectorBytes = Encoding.UTF8.GetBytes(initVector);
            byte[] saltValueBytes = Encoding.UTF8.GetBytes(saltValue);

            // Convert our ciphertext into a byte array.
            byte[] cipherTextBytes = Convert.FromBase64String(cipherText);

            // First, we must create a password, from which the key will be
            // derived. This password will be generated from the specified
            // passphrase and salt value. The password will be created using
            // the specified hash algorithm. Password creation can be done in
            // several iterations.
            PasswordDeriveBytes password = new PasswordDeriveBytes(
                                                            passPhrase,
                                                            saltValueBytes,
                                                            hashAlgorithm,
                                                            passwordIterations);

            // Use the password to generate pseudo-random bytes for the encryption
            // key. Specify the size of the key in bytes (instead of bits).
            byte[] keyBytes = password.GetBytes(keySize / 8);

            // Create uninitialized Rijndael encryption object.
            RijndaelManaged symmetricKey = new RijndaelManaged();

            // It is reasonable to set encryption mode to Cipher Block Chaining
            // (CBC). Use default options for other symmetric key parameters.
            symmetricKey.Mode = CipherMode.CBC;

            // Generate decryptor from the existing key bytes and initialization
            // vector. Key size will be defined based on the number of the key
            // bytes.
            ICryptoTransform decryptor = symmetricKey.CreateDecryptor(
                                                             keyBytes,
                                                             initVectorBytes);

            // Define memory stream which will be used to hold encrypted data.
            MemoryStream memoryStream = new MemoryStream(cipherTextBytes);

            // Define cryptographic stream (always use Read mode for encryption).
            CryptoStream cryptoStream = new CryptoStream(memoryStream,
                                                          decryptor,
                                                          CryptoStreamMode.Read);

            // Since at this point we don't know what the size of decrypted data
            // will be, allocate the buffer long enough to hold ciphertext;
            // plaintext is never longer than ciphertext.
            byte[] plainTextBytes = new byte[cipherTextBytes.Length];

            // Start decrypting.
            int decryptedByteCount = cryptoStream.Read(plainTextBytes,
                                                       0,
                                                       plainTextBytes.Length);

            // Close both streams.
            memoryStream.Close();
            cryptoStream.Close();

            // Convert decrypted data into a string.
            // Let us assume that the original plaintext string was UTF8-encoded.
            string plainText = Encoding.UTF8.GetString(plainTextBytes,
                                                       0,
                                                       decryptedByteCount);

            // Return decrypted string.
            return plainText;
        }
    }
}
</code>```

OwnerDisplayName: Ksmps

ContentLicense: CC BY-SA 2.5

Body:
Stupidly long code file that will do it for you using full encyption:

I suggest using the SessionID as the salt, then it changes for each user but is stable across postbacks.

///////////////////////////////////////////////////////////////////////////////
// SAMPLE: Symmetric key encryption and decryption using Rijndael algorithm.
//
// To run this sample, create a new Visual C# project using the Console
// Application template and replace the contents of the Class1.cs file with
// the code below.
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
// EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
//
// Copyright (C) 2002 Obviex(TM). All rights reserved.
//
using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;
namespace TDX.Portal.Utilities
{
    /// <summary>
    /// This class uses a symmetric key algorithm (Rijndael/AES) to encrypt and
    /// decrypt data. As long as encryption and decryption routines use the same
    /// parameters to generate the keys, the keys are guaranteed to be the same.
    /// The class uses static functions with duplicate code to make it easier to
    /// demonstrate encryption and decryption logic. In a real-life application,
    /// this may not be the most efficient way of handling encryption, so - as
    /// soon as you feel comfortable with it - you may want to redesign this class.
    /// </summary>
    public class RijndaelSimple
    {
        /// <summary>
        /// Encrypts specified plaintext using Rijndael symmetric key algorithm
        /// and returns a base64-encoded result.
        /// </summary>
        /// <param name="plainText">
        /// Plaintext value to be encrypted.
        /// </param>
        /// <param name="passPhrase">
        /// Passphrase from which a pseudo-random password will be derived. The
        /// derived password will be used to generate the encryption key.
        /// Passphrase can be any string. In this example we assume that this
        /// passphrase is an ASCII string.
        /// </param>
        /// <param name="saltValue">
        /// Salt value used along with passphrase to generate password. Salt can
        /// be any string. In this example we assume that salt is an ASCII string.
        /// </param>
        /// <param name="hashAlgorithm">
        /// Hash algorithm used to generate password. Allowed values are: "MD5" and
        /// "SHA1". SHA1 hashes are a bit slower, but more secure than MD5 hashes.
        /// </param>
        /// <param name="passwordIterations">
        /// Number of iterations used to generate password. One or two iterations
        /// should be enough.
        /// </param>
        /// <param name="initVector">
        /// Initialization vector (or IV). This value is required to encrypt the
        /// first block of plaintext data. For RijndaelManaged class IV must be
        /// exactly 16 ASCII characters long.
        /// </param>
        /// <param name="keySize">
        /// Size of encryption key in bits. Allowed values are: 128, 192, and 256.
        /// Longer keys are more secure than shorter keys.
        /// </param>
        /// <returns>
        /// Encrypted value formatted as a base64-encoded string.
        /// </returns>
        public static string Encrypt(string plainText,
                                     string passPhrase,
                                     string saltValue,
                                     string hashAlgorithm,
                                     int passwordIterations,
                                     string initVector,
                                     int keySize)
        {
            // Convert strings into byte arrays.
            // Let us assume that strings only contain ASCII codes.
            // If strings include Unicode characters, use Unicode, UTF7, or UTF8
            // encoding.
            byte[] initVectorBytes = Encoding.UTF8.GetBytes(initVector);
            byte[] saltValueBytes = Encoding.UTF8.GetBytes(saltValue);

            // Convert our plaintext into a byte array.
            // Let us assume that plaintext contains UTF8-encoded characters.
            byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

            // First, we must create a password, from which the key will be derived.
            // This password will be generated from the specified passphrase and
            // salt value. The password will be created using the specified hash
            // algorithm. Password creation can be done in several iterations.
            PasswordDeriveBytes password = new PasswordDeriveBytes(
                                                            passPhrase,
                                                            saltValueBytes,
                                                            hashAlgorithm,
                                                            passwordIterations);

            // Use the password to generate pseudo-random bytes for the encryption
            // key. Specify the size of the key in bytes (instead of bits).
            byte[] keyBytes = password.GetBytes(keySize / 8);

            // Create uninitialized Rijndael encryption object.
            RijndaelManaged symmetricKey = new RijndaelManaged();

            // It is reasonable to set encryption mode to Cipher Block Chaining
            // (CBC). Use default options for other symmetric key parameters.
            symmetricKey.Mode = CipherMode.CBC;

            // Generate encryptor from the existing key bytes and initialization
            // vector. Key size will be defined based on the number of the key
            // bytes.
            ICryptoTransform encryptor = symmetricKey.CreateEncryptor(
                                                             keyBytes,
                                                             initVectorBytes);

            // Define memory stream which will be used to hold encrypted data.
            MemoryStream memoryStream = new MemoryStream();

            // Define cryptographic stream (always use Write mode for encryption).
            CryptoStream cryptoStream = new CryptoStream(memoryStream,
                                                         encryptor,
                                                         CryptoStreamMode.Write);
            // Start encrypting.
            cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);

            // Finish encrypting.
            cryptoStream.FlushFinalBlock();

            // Convert our encrypted data from a memory stream into a byte array.
            byte[] cipherTextBytes = memoryStream.ToArray();

            // Close both streams.
            memoryStream.Close();
            cryptoStream.Close();

            // Convert encrypted data into a base64-encoded string.
            string cipherText = Convert.ToBase64String(cipherTextBytes);

            // Return encrypted string.
            return cipherText;
        }

        /// <summary>
        /// Decrypts specified ciphertext using Rijndael symmetric key algorithm.
        /// </summary>
        /// <param name="cipherText">
        /// Base64-formatted ciphertext value.
        /// </param>
        /// <param name="passPhrase">
        /// Passphrase from which a pseudo-random password will be derived. The
        /// derived password will be used to generate the encryption key.
        /// Passphrase can be any string. In this example we assume that this
        /// passphrase is an ASCII string.
        /// </param>
        /// <param name="saltValue">
        /// Salt value used along with passphrase to generate password. Salt can
        /// be any string. In this example we assume that salt is an ASCII string.
        /// </param>
        /// <param name="hashAlgorithm">
        /// Hash algorithm used to generate password. Allowed values are: "MD5" and
        /// "SHA1". SHA1 hashes are a bit slower, but more secure than MD5 hashes.
        /// </param>
        /// <param name="passwordIterations">
        /// Number of iterations used to generate password. One or two iterations
        /// should be enough.
        /// </param>
        /// <param name="initVector">
        /// Initialization vector (or IV). This value is required to encrypt the
        /// first block of plaintext data. For RijndaelManaged class IV must be
        /// exactly 16 ASCII characters long.
        /// </param>
        /// <param name="keySize">
        /// Size of encryption key in bits. Allowed values are: 128, 192, and 256.
        /// Longer keys are more secure than shorter keys.
        /// </param>
        /// <returns>
        /// Decrypted string value.
        /// </returns>
        /// <remarks>
        /// Most of the logic in this function is similar to the Encrypt
        /// logic. In order for decryption to work, all parameters of this function
        /// - except cipherText value - must match the corresponding parameters of
        /// the Encrypt function which was called to generate the
        /// ciphertext.
        /// </remarks>
        public static string Decrypt(string cipherText,
                                     string passPhrase,
                                     string saltValue,
                                     string hashAlgorithm,
                                     int passwordIterations,
                                     string initVector,
                                     int keySize)
        {
            // Convert strings defining encryption key characteristics into byte
            // arrays. Let us assume that strings only contain ASCII codes.
            // If strings include Unicode characters, use Unicode, UTF7, or UTF8
            // encoding.
            byte[] initVectorBytes = Encoding.UTF8.GetBytes(initVector);
            byte[] saltValueBytes = Encoding.UTF8.GetBytes(saltValue);

            // Convert our ciphertext into a byte array.
            byte[] cipherTextBytes = Convert.FromBase64String(cipherText);

            // First, we must create a password, from which the key will be
            // derived. This password will be generated from the specified
            // passphrase and salt value. The password will be created using
            // the specified hash algorithm. Password creation can be done in
            // several iterations.
            PasswordDeriveBytes password = new PasswordDeriveBytes(
                                                            passPhrase,
                                                            saltValueBytes,
                                                            hashAlgorithm,
                                                            passwordIterations);

            // Use the password to generate pseudo-random bytes for the encryption
            // key. Specify the size of the key in bytes (instead of bits).
            byte[] keyBytes = password.GetBytes(keySize / 8);

            // Create uninitialized Rijndael encryption object.
            RijndaelManaged symmetricKey = new RijndaelManaged();

            // It is reasonable to set encryption mode to Cipher Block Chaining
            // (CBC). Use default options for other symmetric key parameters.
            symmetricKey.Mode = CipherMode.CBC;

            // Generate decryptor from the existing key bytes and initialization
            // vector. Key size will be defined based on the number of the key
            // bytes.
            ICryptoTransform decryptor = symmetricKey.CreateDecryptor(
                                                             keyBytes,
                                                             initVectorBytes);

            // Define memory stream which will be used to hold encrypted data.
            MemoryStream memoryStream = new MemoryStream(cipherTextBytes);

            // Define cryptographic stream (always use Read mode for encryption).
            CryptoStream cryptoStream = new CryptoStream(memoryStream,
                                                          decryptor,
                                                          CryptoStreamMode.Read);

            // Since at this point we don't know what the size of decrypted data
            // will be, allocate the buffer long enough to hold ciphertext;
            // plaintext is never longer than ciphertext.
            byte[] plainTextBytes = new byte[cipherTextBytes.Length];

            // Start decrypting.
            int decryptedByteCount = cryptoStream.Read(plainTextBytes,
                                                       0,
                                                       plainTextBytes.Length);

            // Close both streams.
            memoryStream.Close();
            cryptoStream.Close();

            // Convert decrypted data into a string.
            // Let us assume that the original plaintext string was UTF8-encoded.
            string plainText = Encoding.UTF8.GetString(plainTextBytes,
                                                       0,
                                                       decryptedByteCount);

            // Return decrypted string.
            return plainText;
        }
    }
}

OwnerDisplayName: ck


问:
Help with image-resizing methods gdi
So I'm in need of some resizing.

I found two different methods.

One looks like this:

```<code>public static Byte[] ResizeImageNew(System.Drawing.Image imageFile, int targetWidth, int targetHeight) {
        using(imageFile){
            Size newSize = CalculateDimensions(imageFile.Size, targetWidth, targetHeight);

            using (Bitmap newImage = new Bitmap(newSize.Width, newSize.Height, PixelFormat.Format32bppRgb)) {
                newImage.SetResolution(imageFile.HorizontalResolution, imageFile.VerticalResolution);
                using (Graphics canvas = Graphics.FromImage(newImage)) {
                    canvas.SmoothingMode = SmoothingMode.AntiAlias;
                    canvas.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    canvas.PixelOffsetMode = PixelOffsetMode.HighQuality;
                    canvas.DrawImage(imageFile, new Rectangle(new Point(0, 0), newSize));
                    MemoryStream m = new MemoryStream();
                    newImage.Save(m, ImageFormat.Jpeg);
                    return m.GetBuffer();
                }
            }
        }
    }
</code>```

And the other:

```<code>    public static System.Drawing.Image ResizeImage(System.Drawing.Image originalImage, int width, int maxHeight) {
        originalImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
        originalImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);

        int NewHeight = originalImage.Height * width / originalImage.Width;
        if (NewHeight > maxHeight) {
            // Resize with height instead
            width = originalImage.Width * maxHeight / originalImage.Height;
            NewHeight = maxHeight;
        }

        System.Drawing.Image newImage = originalImage.GetThumbnailImage(width, NewHeight, null, IntPtr.Zero);

        return newImage;
    }
</code>```

I basically 'borrowed' both methods, and just changed bits and pieces.

However - using the first one, whenever I resize to a little smaller picture, the size of the file is actually larger then the original (!?)

And the second while greatly improving size looks terrible :/

I'm of course leaning on merely improving image quality in the first method, if possible, but I can't see how, everything looks to be 'high quality' from my point of view ?

答:
You may have to set the JPEG compression level. Currently it probably saves at a very high quality level, which may not be what you desire.

See here for more info: http://msdn.microsoft.com/en-us/library/bb882583.aspx

Note, however, that just reducing the resolution of the image doesn't necessarily reduce filesize. Due to how compression works, a smaller resolution file that has been blurred due to interpolation modes can be significantly larger than the original, though with JPEG that's probably not a big concern due to the lossy algorithm. It can make a huge difference for PNGs, though, if the original file was very simple before (like "flat" webcomic or simple vector graphics) and has been blurred after resizing.

Title: Help with image-resizing methods gdi

Body:
So I'm in need of some resizing.

I found two different methods.

One looks like this:

public static Byte[] ResizeImageNew(System.Drawing.Image imageFile, int targetWidth, int targetHeight) {
        using(imageFile){
            Size newSize = CalculateDimensions(imageFile.Size, targetWidth, targetHeight);

            using (Bitmap newImage = new Bitmap(newSize.Width, newSize.Height, PixelFormat.Format32bppRgb)) {
                newImage.SetResolution(imageFile.HorizontalResolution, imageFile.VerticalResolution);
                using (Graphics canvas = Graphics.FromImage(newImage)) {
                    canvas.SmoothingMode = SmoothingMode.AntiAlias;
                    canvas.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    canvas.PixelOffsetMode = PixelOffsetMode.HighQuality;
                    canvas.DrawImage(imageFile, new Rectangle(new Point(0, 0), newSize));
                    MemoryStream m = new MemoryStream();
                    newImage.Save(m, ImageFormat.Jpeg);
                    return m.GetBuffer();
                }
            }
        }
    }

And the other:

    public static System.Drawing.Image ResizeImage(System.Drawing.Image originalImage, int width, int maxHeight) {
        originalImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
        originalImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);

        int NewHeight = originalImage.Height * width / originalImage.Width;
        if (NewHeight > maxHeight) {
            // Resize with height instead
            width = originalImage.Width * maxHeight / originalImage.Height;
            NewHeight = maxHeight;
        }

        System.Drawing.Image newImage = originalImage.GetThumbnailImage(width, NewHeight, null, IntPtr.Zero);

        return newImage;
    }

I basically 'borrowed' both methods, and just changed bits and pieces.

However - using the first one, whenever I resize to a little smaller picture, the size of the file is actually larger then the original (!?)

And the second while greatly improving size looks terrible :/

I'm of course leaning on merely improving image quality in the first method, if possible, but I can't see how, everything looks to be 'high quality' from my point of view ?


问:
Recycler View not overscrolling when used with CollapsingToolbarLayout
I have the following layout with collapsible toolbar layout and recycler view. Somehow, it is not allowing recyclerview to overscroll. How can I achieve that? Thanks!</p>

```<code><com.google.android.material.appbar.CollapsingToolbarLayout
        android:id="@+id/collapsing_toolbar_layout"
        android:layout_width="match_parent"
        app:layout_scrollFlags="scroll|exitUntilCollapsed">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            style="@style/ToolbarStyle"
            android:layout_width="match_parent"
            android:layout_height="?android:attr/actionBarSize">
    </com.google.android.material.appbar.CollapsingToolbarLayout>

</com.google.android.material.appbar.AppBarLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <View
        android:id="@+id/view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clipToPadding="false"/>

</LinearLayout>
</code>```

答:
try this, I'm currently using in an app

```<code><com.google.android.material.appbar.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:fitsSystemWindows="true"
    android:theme="@style/AppTheme.AppBarOverlay">

    <com.google.android.material.appbar.CollapsingToolbarLayout
        android:id="@+id/collapsing_toolbar_layout"
        android:layout_width="match_parent"
        android:layout_height="220dp"
        app:layout_scrollFlags="scroll|exitUntilCollapsed">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?android:attr/actionBarSize" />

    </com.google.android.material.appbar.CollapsingToolbarLayout>

</com.google.android.material.appbar.AppBarLayout>
</code>```

I think you are forgeting just this part:

```<code>app:layout_scrollFlags="scroll|exitUntilCollapsed"
</code>```

Body:
I have the following layout with collapsible toolbar layout and recycler view. Somehow, it is not allowing recyclerview to overscroll. How can I achieve that? Thanks!

<com.google.android.material.appbar.CollapsingToolbarLayout
        android:id="@+id/collapsing_toolbar_layout"
        android:layout_width="match_parent"
        app:layout_scrollFlags="scroll|exitUntilCollapsed">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            style="@style/ToolbarStyle"
            android:layout_width="match_parent"
            android:layout_height="?android:attr/actionBarSize">
    </com.google.android.material.appbar.CollapsingToolbarLayout>

</com.google.android.material.appbar.AppBarLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <View
        android:id="@+id/view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clipToPadding="false"/>

</LinearLayout>

Body:
try this, I'm currently using in an app

<com.google.android.material.appbar.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:fitsSystemWindows="true"
    android:theme="@style/AppTheme.AppBarOverlay">

    <com.google.android.material.appbar.CollapsingToolbarLayout
        android:id="@+id/collapsing_toolbar_layout"
        android:layout_width="match_parent"
        android:layout_height="220dp"
        app:layout_scrollFlags="scroll|exitUntilCollapsed">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?android:attr/actionBarSize" />

    </com.google.android.material.appbar.CollapsingToolbarLayout>

</com.google.android.material.appbar.AppBarLayout>

I think you are forgeting just this part:

app:layout_scrollFlags="scroll|exitUntilCollapsed"


问:
Why do you need div in the render function for ReactJS components?
I just started learning web dev and I'm a little confused by this one thing in ReactJS. In my App component's render function, if I return JSX without an overarching div:

```<code>render() {
  return (
    <h1 style={headerStyle}>Todo List</h1>
    <Todo todos={this.state.todos}/>
  );
 }
</code>```

I get an error:

```<code>./src/App.js
  Line 29:9:  Parsing error: Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...</>?

  27 |      return (
  28 |         <h1 style={headerStyle}>Todo List</h1>
> 29 |         <Todo todos={this.state.todos}/>
     |         ^
  30 |      );
  31 |   }
  32 | }
</code>```

but once I add a div:

```<code>render() {
     return (
        <div>
          <h1 style={headerStyle}>Todo List</h1>
          <Todo todos={this.state.todos}/>
        </div>
     );
  }
}
</code>```

everything works fine.

Why is the div necessary? Or if its not actually necessary, what else could I be doing wrong?

答:
A React element has to have a single root element. If you don’t want the div you can use a fragment:

```<code><>
  <h1 style={headerStyle}>Todo List</h1>
  <Todo todos={this.state.todos}/>
</>
</code>```

I’m not an expert on the internals of React, but my intuition is that the rendering requires a root node to get a handle on a list of children to iterate over. The tree has to have a root.

Body:
I just started learning web dev and I'm a little confused by this one thing in ReactJS. In my App component's render function, if I return JSX without an overarching div:

render() {
  return (

Todo List

    <Todo todos={this.state.todos}/>
  );
 }

I get an error:

./src/App.js
  Line 29:9:  Parsing error: Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...</>?

  27 |      return (
  28 |
Todo List

> 29 |         <Todo todos={this.state.todos}/>
     |         ^
  30 |      );
  31 |   }
  32 | }

but once I add a div:

render() {
     return (

Todo List

          <Todo todos={this.state.todos}/>

     );
  }
}

everything works fine.

Why is the div necessary? Or if its not actually necessary, what else could I be doing wrong?

Body:
A React element has to have a single root element. If you don’t want the div you can use a fragment:

<>
  <h1 style={headerStyle}>Todo List</h1>
  <Todo todos={this.state.todos}/>
</>

I’m not an expert on the internals of React, but my intuition is that the rendering requires a root node to get a handle on a list of children to iterate over. The tree has to have a root.


问:
Randomly grab 3 items from an array, where the 3rd item can be a “restaurant" but does not have to be
I apologize for the poorly written title. I was not sure how exactly to write it. I have an array. I need to randomly grab three items from the array. Only one item can be a "restaurant" and the restaurant can ONLY ever go in the third position.

Let me explain with an example. here is a sample array

```<code>el 1 - restaurant = false
el 2 - restaurant = true
el 3 - restaurant = true
el 4 - restaurant = false
el 5 - restaurant = false
el 6 - restaurant = false
el 7 - restaurant = true
el 8 - restaurant = false
el 9 - restaurant = false
</code>```

My current code loops through this array and randomly grabs three items. Positions 1 and 2 can NEVER have a restaurant in them so they have to be taken from the items with the restaurant property set to false. The 3rd position can have a restaurant but I don't want it to always be a restaurant.

Here is my current code:

```<code>const amountOfLocations = 3

// have list of locations
// shuffle it
for (let i = locations.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [locations[i], locations[j]] = [locations[j], locations[i]];
}

let selectedLocations = locations.slice(0, amountOfLocations)
</code>```

My initial thought is I need to grab only 2 items from this current loop instead of 3, then using the original array remove these two items and shuffle the array up again to randomly grab one more item which will then be placed in the 3rd position.

答:
Use a whole loop. randomly select an element — if you are not choosing the third element and a restaurant is picked, don’t save the choice and let the whole loop run again (until you have three elements).

Or

Make a temporary array without the restaurants in it, and then randomly select from that array twice. Then randomly select from the normal array. If it matches one of the two you already have, then get it again (use a while loop).

Body:
I apologize for the poorly written title. I was not sure how exactly to write it. I have an array. I need to randomly grab three items from the array. Only one item can be a "restaurant" and the restaurant can ONLY ever go in the third position.

Let me explain with an example. here is a sample array

el 1 - restaurant = false
el 2 - restaurant = true
el 3 - restaurant = true
el 4 - restaurant = false
el 5 - restaurant = false
el 6 - restaurant = false
el 7 - restaurant = true
el 8 - restaurant = false
el 9 - restaurant = false

My current code loops through this array and randomly grabs three items. Positions 1 and 2 can NEVER have a restaurant in them so they have to be taken from the items with the restaurant property set to false. The 3rd position can have a restaurant but I don't want it to always be a restaurant.

Here is my current code:

const amountOfLocations = 3

// have list of locations
// shuffle it
for (let i = locations.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [locations[i], locations[j]] = [locations[j], locations[i]];
}

let selectedLocations = locations.slice(0, amountOfLocations)

My initial thought is I need to grab only 2 items from this current loop instead of 3, then using the original array remove these two items and shuffle the array up again to randomly grab one more item which will then be placed in the 3rd position.


答:
You cannot have sibling html elements at root level. If you do not want the parent element, use array

```<code>render() {
  return ([
    <h1 style={headerStyle}>Todo List</h1>,
    <Todo todos={this.state.todos}/>,
  ]);
}
</code>```

See - Reference

Title: Why do you need div in the render function for ReactJS components?

Body:
You cannot have sibling html elements at root level. If you do not want the parent element, use array

render() {
  return ([
    <h1 style={headerStyle}>Todo List</h1>,
    <Todo todos={this.state.todos}/>,
  ]);
}

See - Reference


问:
Re-use argument or use self
When defining a class and you need to use an argument twice is it better to keep using the argument or use the self version as soon as it is made?

```<code>class Example:
    def __init__(self, name):
        self.name = name
        self.name_upper = name.upper()
</code>```

or

```<code>class Example:
    def __init__(self, name):
        self.name = name
        self.name_upper = self.name.upper()
</code>```

And what about with list?

```<code>class Example:
    def __init__(self, name):
        self.name = name
        self.name_list = [name,name,name]
</code>```

```<code>class Example:
    def __init__(self, name):
        self.name = name
        self.name_list = [self.name,self.name,self.name]
</code>```

答:
It's a question of scope. In the example below, the variable 'name' is only visible with in the method '__init__' whereas the variable 'self.name_list' can be used in any method within the class.

```<code>class Example :
    def __init__ (self, name) :
        self.name_list = [name] * 3

    def show_variables (self) :
        print (self.name_list)
        print (name)      # gives 'name' is not defined error

this = Example ('This example')
this.show_variables ()
</code>```

Title: Re-use argument or use self

Body:
When defining a class and you need to use an argument twice is it better to keep using the argument or use the self version as soon as it is made?

class Example:
    def __init__(self, name):
        self.name = name
        self.name_upper = name.upper()

or

class Example:
    def __init__(self, name):
        self.name = name
        self.name_upper = self.name.upper()

And what about with list?

class Example:
    def __init__(self, name):
        self.name = name
        self.name_list = [name,name,name]

class Example:
    def __init__(self, name):
        self.name = name
        self.name_list = [self.name,self.name,self.name]

Body:
It's a question of scope. In the example below, the variable 'name' is only visible with in the method '__init__' whereas the variable 'self.name_list' can be used in any method within the class.

class Example :
    def __init__ (self, name) :
        self.name_list = [name] * 3

    def show_variables (self) :
        print (self.name_list)
        print (name)      # gives 'name' is not defined error

this = Example ('This example')
this.show_variables ()


问:
Pattern matching with Alternative empty or Applicative pure
I know it is possible, to pattern match against (named) constructors like so:

f1 :: Maybe a -> Bool
f1 Nothing = False
f1 (Just x) = True -- in reality have something that uses x here

f2 :: [a] -> Int
f2 [] = False
f2 x = True
```

<p>How can I write such a function for general <code>Alternative</code>s similar to</p>

<pre class="lang-hs prettyprint-override"><code>f :: (Alternative m) => m a -> Bool
f empty = False
f x = True
</code>```

If I try this, I get the error Parse error in pattern: empty. Which makes sense, I guess, as empty as a function here and not a constructor. But how can I accomplish this for general Alternatives idiomatically?

Edit 1:
My actual goal is to define a Monad instance (and probably also a MonadPlus instance) for a custom result type. Instead of the basic Either Error Result type, it should support a Maybe Error (and if possible also other Alternatives like [Error]) as error type and also some Applicative as result type in order to support lazy evaluation, for example with the result type (Maybe Error, [Tokens]) of a tokenizer.

I'd like something similar to

instance (Alterantive mErr, Applicative mRes) => Monad (mErr e, mRes a) where
  return x = (empty, pure x)
  (empty, pure x) >>= f = f x
  (err, x) >>= f = (err, x)
```

答:
Slipping in an Eq constraint, as in mithrandi's answer, is indeed the best that can be done. In any case, it is worth emphasising that it comes at a cost: we are now stuck with an Eq constant that would be unnecessary were we merely pattern match against, say, [] or Nothing. A common way to avoid this problem is using null :: Foldable t => t a -> Bool. Here, however, that option is not great either, as Foldable is largely unrelated to Alternative and rather alien to your use case. In particular, there is no guarantee that, in the general case, there will be just one value for which null holds, which means it might conceivably hold for values that aren't the empty of the relevant Alternative instance.

Ultimately, then, the only tool that would fully fit the requirements might well be some Alternative subclass with an isEmpty method. I don't think that exists anywhere, and the power-to-weight ratio doesn't seem encouraging when it comes to conjuring such a thing.

Body:
I know it is possible, to pattern match against (named) constructors like so:

f1 :: Maybe a -> Bool
f1 Nothing = False
f1 (Just x) = True -- in reality have something that uses x here

f2 :: [a] -> Int
f2 [] = False
f2 x = True

How can I write such a function for general Alternatives similar to

f :: (Alternative m) => m a -> Bool
f empty = False
f x = True

If I try this, I get the error Parse error in pattern: empty. Which makes sense, I guess, as empty as a function here and not a constructor. But how can I accomplish this for general Alternatives idiomatically?

Edit 1:
My actual goal is to define a Monad instance (and probably also a MonadPlus instance) for a custom result type. Instead of the basic Either Error Result type, it should support a Maybe Error (and if possible also other Alternatives like [Error]) as error type and also some Applicative as result type in order to support lazy evaluation, for example with the result type (Maybe Error, [Tokens]) of a tokenizer.

I'd like something similar to

instance (Alterantive mErr, Applicative mRes) => Monad (mErr e, mRes a) where
  return x = (empty, pure x)
  (empty, pure x) >>= f = f x
  (err, x) >>= f = (err, x)


答: You can only return a single expression in JavaScript, so react needs you to return a single parent element. You should use fragments in this case if you don't need the parent div https://reactjs.org/docs/fragments.html</p>


答:
In react you must have a wrapper.

Either you can use html tag like- div or fragment

```<code>return (
        <div>
          <h1 style={headerStyle}>Todo List</h1>
          <Todo todos={this.state.todos}/>
        </div>
     );
</code>```

or fragment if you don't want any additional html tag

```<code>return (
        <>
          <h1 style={headerStyle}>Todo List</h1>
          <Todo todos={this.state.todos}/>
        </>
     );
</code>```

or

```<code> return (
        <React.Fragment>
          <h1 style={headerStyle}>Todo List</h1>
          <Todo todos={this.state.todos}/>
        </React.Fragment>
     );
</code>```

for reference https://reactjs.org/docs/fragments.html

Body:
In react you must have a wrapper.

Either you can use html tag like- div or fragment

return (
        <div>
          <h1 style={headerStyle}>Todo List</h1>
          <Todo todos={this.state.todos}/>
        </div>
     );

or fragment if you don't want any additional html tag

return (
        <>
          <h1 style={headerStyle}>Todo List</h1>
          <Todo todos={this.state.todos}/>
        </>
     );

or

 return (
        <React.Fragment>
          <h1 style={headerStyle}>Todo List</h1>
          <Todo todos={this.state.todos}/>
        </React.Fragment>
     );

for reference https://reactjs.org/docs/fragments.html


问:
How can I have two goroutines of the same function which look at each others' values?
I am trying to achieve a function which I can call with two goroutines and different parameters. Each will manipulate its own string, and they will send their strings to each other through a channel and compare results. Here is my attempt at this (Go Playground linked) :

```<code>func swap_values(str string, strChan1 chan string, strChan2 chan string, done chan bool) {
  str += "test"
  strChan1 <- str
  <-strChan2
  done <- true
}
</code>```

and this is deadlocking. For my two calls to the function, I swap the channels so strChan1 is a different channel for each. How can I fix this to not deadlock and accomplish what I want? Again, I will be comparing the strings and doing additional manipulation, this is just a proof of concept for getting both.

答:
It is deadlocking because both goroutines try to write to channels that nobody is listening to. The first goroutine tries to write one channel, and since the second is not reading from it, it is stuck there. The second goroutine does the same, so they both stop, waiting for each other.

Simplest way to deal with this is to use a channel with size 1, so write can proceed without waiting for a reader.

```<code>strChan1 := make(chan string,1)
strChan2 := make(chan string,1)
</code>```

If you have to use 0-length channels, you need to use a select to accommodate different orderings of the goroutines:

```<code>select {
  case strChan1 <- str:
     <-strChan2
  case <-strChan2:
     strChan1 <- str
}
</code>```

Body:
I am trying to achieve a function which I can call with two goroutines and different parameters. Each will manipulate its own string, and they will send their strings to each other through a channel and compare results. Here is my attempt at this (Go Playground linked) :

func swap_values(str string, strChan1 chan string, strChan2 chan string, done chan bool) {
  str += "test"
  strChan1 <- str
  <-strChan2
  done <- true
}

and this is deadlocking. For my two calls to the function, I swap the channels so strChan1 is a different channel for each. How can I fix this to not deadlock and accomplish what I want? Again, I will be comparing the strings and doing additional manipulation, this is just a proof of concept for getting both.

Body:
It is deadlocking because both goroutines try to write to channels that nobody is listening to. The first goroutine tries to write one channel, and since the second is not reading from it, it is stuck there. The second goroutine does the same, so they both stop, waiting for each other.

Simplest way to deal with this is to use a channel with size 1, so write can proceed without waiting for a reader.

strChan1 := make(chan string,1)
strChan2 := make(chan string,1)

If you have to use 0-length channels, you need to use a select to accommodate different orderings of the goroutines:

select {
  case strChan1 <- str:
     <-strChan2
  case <-strChan2:
     strChan1 <- str
}


问:
Hex string passed to php script in $_REQUEST array isn't being interpreted?
Here's a really simple example:

```<code>$val = "";

if(array_key_exists("param", $_REQUEST)) {
    $val = $_REQUEST["param"];
}

print "echo \"$val\"";
passthru("echo \"$val\"");
</code>```

I'm expecting the passthru() to print A if I pass test.php?param=\x41. However, it doesn't look like PHP is interpreting the escape sequence and passing "\x41" to passthru. I know that the \xAA shorthand only works on double quoted strings in PHP, but that condition should be satisfied in the example above. Does reading a variable out of $_REQUEST modify anything?

答:
Escape sequences aren't expanded in strings, they're only expanded in string literals in code.

The shell command printf will process escape sequences in its format string argument, so you can do:

```<code>passthru("printf '$val'");
</code>```

You can also use a shell string quoted with $'' to process escape sequences.

```<code>passthru("echo \$'$val'");
</code>```

Body:
Here's a really simple example:

$val = "";

if(array_key_exists("param", $_REQUEST)) {
    $val = $_REQUEST["param"];
}

print "echo \"$val\"";
passthru("echo \"$val\"");

I'm expecting the passthru() to print A if I pass test.php?param=\x41. However, it doesn't look like PHP is interpreting the escape sequence and passing "\x41" to passthru. I know that the \xAA shorthand only works on double quoted strings in PHP, but that condition should be satisfied in the example above. Does reading a variable out of $_REQUEST modify anything?

Body:
Escape sequences aren't expanded in strings, they're only expanded in string literals in code.

The shell command printf will process escape sequences in its format string argument, so you can do:

passthru("printf '$val'");

You can also use a shell string quoted with $'' to process escape sequences.

passthru("echo \$'$val'");


问:
Persist cell value in excel
This is my current excel document

```<code>Balance      Deposit       Withdrawal
$45.00       $100.00       $50.00
             $25.00        $30.00
</code>```

The function for cell A1 is ==SUM(B2:B) - SUM(C2:C). However, when I delete the values from columns B and C, the value of balance goes back to 0. I want the value to stay at $45.

I have tried many forms and here is one of my thoughts: =A2 + SUM(B2:B) - SUM(C2:C). But this doest work either...

答: As long as the cell has a formula, it will count even if there are no numbers in columns B and C. To get rid of a formula, select a cell (A1 in this case), then Copy, then Paste special -> Values. Then you can delete the values in columns B and C.

Title: Persist cell value in excel

Body:
This is my current excel document

Balance      Deposit       Withdrawal
$45.00       $100.00       $50.00
             $25.00        $30.00

The function for cell A1 is ==SUM(B2:B) - SUM(C2:C). However, when I delete the values from columns B and C, the value of balance goes back to 0. I want the value to stay at $45.

I have tried many forms and here is one of my thoughts: =A2 + SUM(B2:B) - SUM(C2:C). But this doest work either...


问:
How to clean completely select2 control?
I'm working with the awesome select2 control.

I'm trying to clean and disable the select2 with the content too so I do this:

```<code>$("#select2id").empty();
$("#select2id").select2("disable");
</code>```

Ok, it works, but if i had a value selected all the items are removed, the control is disabled, but the selected value is still displayed. I want to clear all content so the placeholder would be showed. Here is a example I did where you can see the issue: http://jsfiddle.net/BSEXM/

HTML:

```<code><select id="sel" data-placeholder="This is my placeholder">
    <option></option>
    <option value="a">hello</option>
    <option value="b">all</option>
    <option value="c">stack</option>
    <option value="c">overflow</option>
</select>
<br>
<button id="pres">Disable and clear</button>
<button id="ena">Enable</button>
</code>```

Code:

```<code>$(document).ready(function () {
    $("#sel").select2();

    $("#pres").click(function () {
        $("#sel").empty();
        $("#sel").select2("disable");
    });

    $("#ena").click(function () {
        $("#sel").select2("enable");
    });
});
</code>```

CSS:

```<code>#sel {
    margin: 20px;
}
</code>```

Do you have any idea or advice to this?

答:
As per the doc here, you need to use the code as below</p>

```<code>$('#mySelect2').val(null).trigger('change');
</code>```

Body:
I'm working with the awesome select2 control.

I'm trying to clean and disable the select2 with the content too so I do this:

$("#select2id").empty();
$("#select2id").select2("disable");

Ok, it works, but if i had a value selected all the items are removed, the control is disabled, but the selected value is still displayed. I want to clear all content so the placeholder would be showed. Here is a example I did where you can see the issue: http://jsfiddle.net/BSEXM/

HTML:

<select id="sel" data-placeholder="This is my placeholder">
    <option></option>
    <option value="a">hello</option>
    <option value="b">all</option>
    <option value="c">stack</option>
    <option value="c">overflow</option>
</select>

<button id="pres">Disable and clear</button>
<button id="ena">Enable</button>

Code:

$(document).ready(function () {
    $("#sel").select2();

    $("#pres").click(function () {
        $("#sel").empty();
        $("#sel").select2("disable");
    });

    $("#ena").click(function () {
        $("#sel").select2("enable");
    });
});

CSS:

#sel {
    margin: 20px;
}

Do you have any idea or advice to this?

Body:
As per the doc here, you need to use the code as below

$('#mySelect2').val(null).trigger('change');


问:
Help with SQLite (Join tables with subquery)
Guys I am going mad with this one...
I have two tables:

```<code>1. UniquePrefixes
2. Operator
</code>```

UniquePrefixes contains 'Prefix' field only.
Example:

```<code>Prefix
------
1
12
123
12345
</code>```

The 'Operator' table have a lot of data, including a 'Prefix' field as well.
Example:

```<code>..... Prefix ......
----- ------ ------
      1
      12
</code>```

What I am trying to achieve is:

```<code>(pseudo)

foreach unique 'prefix'
select the 'Prefix' from 'Operator' if is equal to a unique 'prefix'
OR
select the 'closest' match that fits into that
</code>```

Example:

```<code>unique prefix = 1 (exists on 'Operator' so I am fine)
unique prefix = 12345 (doesnt exist on 'Operator' so I must get '12')
</code>```

What I have done so far is:

```<code>SELECT
    *
FROM
    UniquePrefixes
LEFT OUTER JOIN Operator
on
    Operator.Prefix =(
        SELECT
            Operator.Prefix
        FROM
            Operator,
            UniquePrefixes
        WHERE
            length(Operator.Prefix)<= UniquePrefixes.prefix
        AND UniquePrefixes.prefix LIKE(
            Operator.Prefix || '%'
        )
        ORDER BY
            Operator.Prefix DESC
        LIMIT 1
    )
</code>```

But it doesnt work since the subselect gets executed first (obviously) :(

I hope that this makes sense and will really appreciate any help

答:
```<code>    SELECT UniquePrefixes.Prefix, Operator.Prefix
      FROM UniquePrefixes
 LEFT JOIN Operator ON UniquePrefixes.Prefix LIKE Operator.Prefix || '%'
                   AND length(Operator.Prefix) <= length(UniquePrefixes.prefix)
     ORDER BY length(Operator.Prefix) desc
</code>```

Body:
Guys I am going mad with this one...
I have two tables:

1. UniquePrefixes
2. Operator

UniquePrefixes contains 'Prefix' field only.
Example:

Prefix
------
1
12
123
12345

The 'Operator' table have a lot of data, including a 'Prefix' field as well.
Example:

..... Prefix ......
----- ------ ------
      1
      12

What I am trying to achieve is:

(pseudo)

foreach unique 'prefix'
select the 'Prefix' from 'Operator' if is equal to a unique 'prefix'
OR
select the 'closest' match that fits into that

Example:

unique prefix = 1 (exists on 'Operator' so I am fine)
unique prefix = 12345 (doesnt exist on 'Operator' so I must get '12')

What I have done so far is:

SELECT
    *
FROM
    UniquePrefixes
LEFT OUTER JOIN Operator
on
    Operator.Prefix =(
        SELECT
            Operator.Prefix
        FROM
            Operator,
            UniquePrefixes
        WHERE
            length(Operator.Prefix)<= UniquePrefixes.prefix
        AND UniquePrefixes.prefix LIKE(
            Operator.Prefix || '%'
        )
        ORDER BY
            Operator.Prefix DESC
        LIMIT 1
    )

But it doesnt work since the subselect gets executed first (obviously) :(

I hope that this makes sense and will really appreciate any help