问:
centos rsync No space left on device
Hint on centos7 when writing to file. No space left on device (28), but I checked the disk and Inodes both have space. I don't know why. Has this ever happened to anyone?</p>

```<code>[root@GDI2390 sync_backup]# df
Filesystem               1K-blocks      Used  Available Use% Mounted on
/dev/mapper/centos-root   52403200   2595000   49808200   5% /
devtmpfs                  32867708         0   32867708   0% /dev
tmpfs                     32874076        24   32874052   1% /dev/shm
tmpfs                     32874076    279528   32594548   1% /run
tmpfs                     32874076         0   32874076   0% /sys/fs/cgroup
/dev/sda1                   508588     98124     410464  20% /boot
/dev/mapper/centos-home 4797426908 902326816 3895100092  19% /home
tmpfs                      6574816         0    6574816   0% /run/user/0

[root@GDI2390 sync_backup]# df -i
Filesystem                  Inodes    IUsed      IFree IUse% Mounted on
/dev/mapper/centos-root   52428800    89274   52339526    1% /
devtmpfs                   8216927      562    8216365    1% /dev
tmpfs                      8218519        2    8218517    1% /dev/shm
tmpfs                      8218519      734    8217785    1% /run
tmpfs                      8218519       13    8218506    1% /sys/fs/cgroup
/dev/sda1                   512000      330     511670    1% /boot
/dev/mapper/centos-home 4797861888 26409024 4771452864    1% /home
tmpfs                      8218519        1    8218518    1% /run/user/0
</code>```

答:
check "Disk space vs Inode usage"

df -h vs df -i

check also - No space left on device

Title: centos rsync No space left on device

Body:
Hint on centos7 when writing to file. No space left on device (28), but I checked the disk and Inodes both have space. I don't know why. Has this ever happened to anyone?

[root@GDI2390 sync_backup]# df
Filesystem               1K-blocks      Used  Available Use% Mounted on
/dev/mapper/centos-root   52403200   2595000   49808200   5% /
devtmpfs                  32867708         0   32867708   0% /dev
tmpfs                     32874076        24   32874052   1% /dev/shm
tmpfs                     32874076    279528   32594548   1% /run
tmpfs                     32874076         0   32874076   0% /sys/fs/cgroup
/dev/sda1                   508588     98124     410464  20% /boot
/dev/mapper/centos-home 4797426908 902326816 3895100092  19% /home
tmpfs                      6574816         0    6574816   0% /run/user/0

[root@GDI2390 sync_backup]# df -i
Filesystem                  Inodes    IUsed      IFree IUse% Mounted on
/dev/mapper/centos-root   52428800    89274   52339526    1% /
devtmpfs                   8216927      562    8216365    1% /dev
tmpfs                      8218519        2    8218517    1% /dev/shm
tmpfs                      8218519      734    8217785    1% /run
tmpfs                      8218519       13    8218506    1% /sys/fs/cgroup
/dev/sda1                   512000      330     511670    1% /boot
/dev/mapper/centos-home 4797861888 26409024 4771452864    1% /home
tmpfs                      8218519        1    8218518    1% /run/user/0


来源: stackexchange

问:
Is there any best way to implement Encryption in Flex 3
we have one application where we are pulling some confidential information from one of the product design tools. So we have used HTTPS as the channel and also we are encrypting the Request Parameters and Some data before we sent it to Web Services. So, Everything seems OK.

But when we gave the application for Security auditing they found we have hard coded the encryption key in source code. They have used Sothink SWF Decompiler to look into my SWF file. They caught the key and raised concern over it.

We have developed this application using Flex 3(SDK 3.4). Is there any best way to use Secret key without being hard coded in source code. If anybody come across this kind of problem, please let me know.

Anyone, please suggest me the best way to use the secret keys in SourceCode without being Hard coded.

Here is my sample code:

```<code>var currentResult:String = "";
        var strDataToEncrypt:String = "";
        var kdata:ByteArray;

        var todayDate:Date = new Date();

        kdata = Hex.toArray(Hex.fromString("secretKey here"));
        strDataToEncrypt =username.toUpperCase() + "#$#" + password + "#$#"  + todayDate.getTime().toString();
        var data:ByteArray;
        data = Hex.toArray(Hex.fromString(strDataToEncrypt))
        var name:String = "des3-ecb";
        var pad:IPad = new PKCS5;
        var mode:ICipher = Crypto.getCipher(name, kdata, pad);
        pad.setBlockSize(mode.getBlockSize());
        mode.encrypt(data);
        currentResult = Base64.encodeByteArray(data);
        var token:String = currentResult;
</code>```

答:
There is no such thing as complete protection with Flash.  Your keys have to be either in the code or loaded externally, and at some point anyone who is determined enough will be able to get them.  All you can do is make this process so complex that it's not worth the hassle.

Have a look at this question for ways to make your source harder to decompile and read: How to protect swf file from being decompiled?

ContentLicense: CC BY-SA 3.0

Body:
we have one application where we are pulling some confidential information from one of the product design tools. So we have used HTTPS as the channel and also we are encrypting the Request Parameters and Some data before we sent it to Web Services. So, Everything seems OK.

But when we gave the application for Security auditing they found we have hard coded the encryption key in source code. They have used Sothink SWF Decompiler to look into my SWF file. They caught the key and raised concern over it.

We have developed this application using Flex 3(SDK 3.4). Is there any best way to use Secret key without being hard coded in source code. If anybody come across this kind of problem, please let me know.

Anyone, please suggest me the best way to use the secret keys in SourceCode without being Hard coded.

Here is my sample code:

var currentResult:String = "";
        var strDataToEncrypt:String = "";
        var kdata:ByteArray;

        var todayDate:Date = new Date();

        kdata = Hex.toArray(Hex.fromString("secretKey here"));
        strDataToEncrypt =username.toUpperCase() + "#$#" + password + "#$#"  + todayDate.getTime().toString();
        var data:ByteArray;
        data = Hex.toArray(Hex.fromString(strDataToEncrypt))
        var name:String = "des3-ecb";
        var pad:IPad = new PKCS5;
        var mode:ICipher = Crypto.getCipher(name, kdata, pad);
        pad.setBlockSize(mode.getBlockSize());
        mode.encrypt(data);
        currentResult = Base64.encodeByteArray(data);
        var token:String = currentResult;


问:
How to convert an editbox to a number assembly?
In TASM for Win32, I have this code:

```<code>;------- Edit1 Create ----------------
push    L 0
push    [hInstEdit1]
push    idEdit1
push    [newhwnd]
push    L 20
push    L 200
push    L 50
push    L 130
push    L WS_CHILD+WS_VISIBLE+WS_BORDER+ES_LEFT+ES_NOHIDESEL+ES_AUTOHSCROLL
push    L 0
push    offset EClassName
push    L 0
call    CreateWindowEx
mov [hEdit1],EAX

push    L SW_SHOW
push    [hEdit1]
call    ShowWindow
push    [hEdit1]
call    UpdateWindow
</code>```

I need to get the number entered by the user in this editbox.
The number must be placed in the register.
Who knows how to do this?

PS I think you need to use the function GetDlgItemInt

答:
Here is the way found on the Internet</p>

```<code>                            ; Input:
    mov esi, offset szMsg1  ; esi - str
    dec msgLength
    mov ecx, msgLength      ; ecx - length str
                            ; Output:
                            ; EAX = integer value
string_to_int:
    xor ebx,ebx             ; clear ebx
next_digit:
    movzx eax, byte ptr [esi]
    inc esi
    sub al,'0'              ; convert from ASCII to number
    imul ebx,10
    add ebx,eax             ; ebx = ebx*10 + eax
    loop next_digit         ; while (--ecx)
    mov eax,ebx
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In TASM for Win32, I have this code:

;------- Edit1 Create ----------------
push    L 0
push    [hInstEdit1]
push    idEdit1
push    [newhwnd]
push    L 20
push    L 200
push    L 50
push    L 130
push    L WS_CHILD+WS_VISIBLE+WS_BORDER+ES_LEFT+ES_NOHIDESEL+ES_AUTOHSCROLL
push    L 0
push    offset EClassName
push    L 0
call    CreateWindowEx
mov [hEdit1],EAX

push    L SW_SHOW
push    [hEdit1]
call    ShowWindow
push    [hEdit1]
call    UpdateWindow

I need to get the number entered by the user in this editbox.
The number must be placed in the register.
Who knows how to do this?

PS I think you need to use the function GetDlgItemInt

Body:
Here is the way found on the Internet

                            ; Input:
    mov esi, offset szMsg1  ; esi - str
    dec msgLength
    mov ecx, msgLength      ; ecx - length str
                            ; Output:
                            ; EAX = integer value
string_to_int:
    xor ebx,ebx             ; clear ebx
next_digit:
    movzx eax, byte ptr [esi]
    inc esi
    sub al,'0'              ; convert from ASCII to number
    imul ebx,10
    add ebx,eax             ; ebx = ebx*10 + eax
    loop next_digit         ; while (--ecx)
    mov eax,ebx


问:
Connect to boost named pipe
I have this code:

```<code>  boost::asio::io_service ios;
  std::vector<char> buf(20);
  bp::async_pipe ap(ios, "\\\\.\\pipe\\SamplePipe");
  boost::asio::async_read(ap, boost::asio::buffer(buf),
    [](const boost::system::error_code &ec, std::size_t size) {});
  ios.run();
</code>```

Now, I execute echo 42 > \\.\pipe\SamplePipe in the cmd and expect an asynchronous read to the buffer to occur. But instead I get the following error: "All pipe instances are busy." Can somebody please explain to me why this is happening and how i can fix it?

答: In the new version of the boost it's fixed. See this.</p>

Title: Connect to boost named pipe

Body:
I have this code:

  boost::asio::io_service ios;
  std::vector<char> buf(20);
  bp::async_pipe ap(ios, "\\\\.\\pipe\\SamplePipe");
  boost::asio::async_read(ap, boost::asio::buffer(buf),
    [](const boost::system::error_code &ec, std::size_t size) {});
  ios.run();

Now, I execute echo 42 > \\.\pipe\SamplePipe in the cmd and expect an asynchronous read to the buffer to occur. But instead I get the following error: "All pipe instances are busy." Can somebody please explain to me why this is happening and how i can fix it?


问:
Query to subtract same column value at different interval of day with SQL database
In MySQL, I want to subtract one of column value at different interval of time based on another column 'timestamp'.

```<code>table structure is :
id | generator_id | timestamp             | generated_value
1  |  1           | 2019-05-27 06:55:20   | 123456
2  |  1           | 2019-05-27 07:55:20   | 234566
3  |  1           | 2019-05-27 08:55:20   | 333456
..
..
20  |  1           | 2019-05-27 19:55:20   | 9876908

</code>```

From above table I want to fetch the generated_value column value which should be difference of first timestamp fo day and timestamp of last value of day.

In above example I am looking query which should give me output as 9,753,452 (9876908 - 123456).

In general to fetch the single record of first value and last value of day I use below query

```<code>// Below will give me end day value
SELECT * FROM generator_meters where generator_id=1 and timestamp like '2019-05-27%' order by timestamp desc limit 1 ;

//this will give me last day value
SELECT * FROM generator_meters where generator_id=1 and timestamp like '2019-05-27%' order by timestamp  limit 1 ;

</code>```

Question is how should I get the final generated_value by doing minus of first value of day from last value of day.

```<code>Expected Output
 generator_id | generated_value
  1           | 9753452
</code>```

Thanks in advance !!

答:
This following script will return your expected results for the filtered ID and Date-

```<code>SELECT generator_id,CAST(timestamp AS DATE) ,
(
    SELECT generated_value
    FROM sun_electric.generator_meters B
    WHERE timestamp = max(timestamp)
)
-
(
    SELECT generated_value
    FROM sun_electric.generator_meters B
    WHERE timestamp = min(timestamp)
) AS Diff
FROM sun_electric.generator_meters
WHERE generator_id = 1
AND CAST(timestamp AS DATE) = '2019-05-27'
GROUP BY generator_id,CAST(timestamp AS DATE) ;
</code>```

If you want the same result with GROUP BY ID and Date just remove the filter as below-

```<code>SELECT generator_id,CAST(timestamp AS DATE) ,
(
    SELECT generated_value
    FROM sun_electric.generator_meters B
    WHERE timestamp = max(timestamp)
)
-
(
    SELECT generated_value
    FROM sun_electric.generator_meters B
    WHERE timestamp = min(timestamp)
) AS Diff
FROM sun_electric.generator_meters
GROUP BY generator_id,CAST(timestamp AS DATE) ;
</code>```

Body:
In MySQL, I want to subtract one of column value at different interval of time based on another column 'timestamp'.

table structure is :
id | generator_id | timestamp             | generated_value
1  |  1           | 2019-05-27 06:55:20   | 123456
2  |  1           | 2019-05-27 07:55:20   | 234566
3  |  1           | 2019-05-27 08:55:20   | 333456
..
..
20  |  1           | 2019-05-27 19:55:20   | 9876908

From above table I want to fetch the generated_value column value which should be difference of first timestamp fo day and timestamp of last value of day.

In above example I am looking query which should give me output as 9,753,452 (9876908 - 123456).

In general to fetch the single record of first value and last value of day I use below query

// Below will give me end day value
SELECT * FROM generator_meters where generator_id=1 and timestamp like '2019-05-27%' order by timestamp desc limit 1 ;

//this will give me last day value
SELECT * FROM generator_meters where generator_id=1 and timestamp like '2019-05-27%' order by timestamp  limit 1 ;

Question is how should I get the final generated_value by doing minus of first value of day from last value of day.

Expected Output
 generator_id | generated_value
  1           | 9753452

Thanks in advance !!

Body:
This following script will return your expected results for the filtered ID and Date-

SELECT generator_id,CAST(timestamp AS DATE) ,
(
    SELECT generated_value
    FROM sun_electric.generator_meters B
    WHERE timestamp = max(timestamp)
)
-
(
    SELECT generated_value
    FROM sun_electric.generator_meters B
    WHERE timestamp = min(timestamp)
) AS Diff
FROM sun_electric.generator_meters
WHERE generator_id = 1
AND CAST(timestamp AS DATE) = '2019-05-27'
GROUP BY generator_id,CAST(timestamp AS DATE) ;

If you want the same result with GROUP BY ID and Date just remove the filter as below-

SELECT generator_id,CAST(timestamp AS DATE) ,
(
    SELECT generated_value
    FROM sun_electric.generator_meters B
    WHERE timestamp = max(timestamp)
)
-
(
    SELECT generated_value
    FROM sun_electric.generator_meters B
    WHERE timestamp = min(timestamp)
) AS Diff
FROM sun_electric.generator_meters
GROUP BY generator_id,CAST(timestamp AS DATE) ;


问:
get parentNode STYLE
When drop any component onto other then I want to interchange the CSS styles of parentNode of component.

Example :

Before

```<code> <div class="parentDIV_1" Style="HOrizontal_interchange CSS">
      Component_1
    </div>

    <div class="parentDIV_2" Style="Vertical_interchange CSS">
       Component_2
    </div>
</code>```

Now i want to interchange the CSS of both class at run time(when drag & Drop)

After

```<code><div class="parentDIV_1" **Style="Vertical_interchange CSS"**>
      Component_1
    </div>

    <div class="parentDIV_2" **Style="HOrizontal_interchange CSS"**>
       Component_2
    </div>
</code>```

答:
Try this too :</p>

```<code>$("#id").removeClass().addClass("Whatever_you_want_to_swap_ClassName");
</code>```

Title: get parentNode STYLE

Body:
When drop any component onto other then I want to interchange the CSS styles of parentNode of component.

Example :

Before

      Component_1

       Component_2

Now i want to interchange the CSS of both class at run time(when drag & Drop)

After

      Component_1

       Component_2

Body:
Try this too :

$("#id").removeClass().addClass("Whatever_you_want_to_swap_ClassName");


问:
WHMCS Problem when add order via LocalAPI
I have 2 problem with WHMCS LocalAPI.

(1) I have a problem when I add order to client via LocalAPI.

I use a webservice where I must send my request to a web service and if returned true then I must add a order to client, but when I use addorder API the WHMCS apply credit automatically and it is not suitable for me. I want to add order and DO NOT paid invoice through credit.

(2)

I have a additional domain field in domainadditionalfields in whmcs database that fieldname as figure, but I do not know what syntax is true I use this code but value field is empty:

```<code>$command = 'AddOrder';
$postData = array(
    'clientid' => 701,
    'domain' => array($domain),
    'domaintype' => array('register'),
    'regperiod' => array($period),
    'nameserver1' => $ns1,
    'nameserver2' => $ns2,
    'additionalfields["irnichandle"]' => "ABC",
    'paymentmethod' => 'mailin',
    'applycredit' => false,
);
$adminUsername = 'adminuser'; // Optional for WHMCS 7.2 and later

$results = localAPI($command, $postData, $adminUsername);
$orderid = $result['orderid'];
$invoiceid = $result['invoiceid'];
print_r($results);
</code>```

答:
(1) There is an option to disable auto applying credit, Setup > General Settings > Credit > Automatic Credit Use (untick it)

(2)  For additional fields, you should use domainfields parameter in the AddOrder function as following:

'domainfields' => array(base64_encode(serialize(array($firstFieldValue))))

Docs:

Additional Domain Fields

Automatic Credit Application.

Body:
I have 2 problem with WHMCS LocalAPI.

(1) I have a problem when I add order to client via LocalAPI.

I use a webservice where I must send my request to a web service and if returned true then I must add a order to client, but when I use addorder API the WHMCS apply credit automatically and it is not suitable for me. I want to add order and DO NOT paid invoice through credit.

(2)

I have a additional domain field in domainadditionalfields in whmcs database that fieldname as figure, but I do not know what syntax is true I use this code but value field is empty:

$command = 'AddOrder';
$postData = array(
    'clientid' => 701,
    'domain' => array($domain),
    'domaintype' => array('register'),
    'regperiod' => array($period),
    'nameserver1' => $ns1,
    'nameserver2' => $ns2,
    'additionalfields["irnichandle"]' => "ABC",
    'paymentmethod' => 'mailin',
    'applycredit' => false,
);
$adminUsername = 'adminuser'; // Optional for WHMCS 7.2 and later

$results = localAPI($command, $postData, $adminUsername);
$orderid = $result['orderid'];
$invoiceid = $result['invoiceid'];
print_r($results);


问:
Time series values not matching the horizontal axis on my Excel chart
SOLVED BY USING X-Y PLOT INSTEAD OF LINE CHART

I want to create a chart in Excel that contains multiple series that are linked in terms of date (i.e. one series ends on 2018/12/31 the next begins 2018/12/31). The raw data is taken from a sheet with two columns; the date column and the value column.

The chart in question here is called 'Beta' and contains 3 time series.
This is my attempt:

```<code>Sub UpdateGraph
Dim ws             As Worksheet
Dim rng_NF3        As Range
Dim rng_Barra      As Range
Dim rng_NF3_Date   As Range
Dim rng_Barra_Date As Range
Dim rng_Total_Date As Range
Dim rng_Total_Val  As Range
Dim cht_Name       As String
Dim ArrDate        As Variant
Dim arrValues      As Variant

        cht_Name = "Beta"  ' Example
        Set ws = Activesheet
        Set cht = ws.ChartObjects(cht_Name)
        Set rng_NF3 = ws.Range(ws.Cells(2, 4), ws.Cells(200, 4)) ' Set range of values from NF3 (GEM3)
        Set rng_Barra = ws.Range(ws.Cells(201, 4), ws.Cells(500, 4)) ' Set range of values Barra
        Set rng_NF3_Date = rng_NF3.Offset(0, -1) ' Set range of date for NF3 observations
        Set rng_Barra_Date = rng_Barra.Offset(0, -1) ' Set range of date for Barra observations
        Set rng_Total_Date = Union(rng_NF3_Date, rng_Barra_Date)
        Set rng_Total_Val = Union(rng_NF3, rng_Barra)
        ArrDate = rng_Total_Date.Value
        arrValues = rng_Total_Val.Value
        With cht.Chart
            .FullSeriesCollection(1).Format.Line.ForeColor.RGB = ws.Cells(1, 20).Interior.Color
            .FullSeriesCollection(2).Format.Line.ForeColor.RGB = ws.Cells(2, 20).Interior.Color
            .FullSeriesCollection(1).Values = rng_NF3 ' Value series for NF3
            .FullSeriesCollection(2).Values = rng_Barra ' Value series for Barra
            .FullSeriesCollection(1).XValues = rng_NF3_Date
            .FullSeriesCollection(2).XValues = rng_Barra_Date
             If cht_Name = "Beta" Then ' Defining Beta = 1
             .FullSeriesCollection(3).Format.Line.ForeColor.RGB = ws.Cells(1, 21).Interior.Color '  Color
             .FullSeriesCollection(3).Values = 1 ' Should be a range with the same number in all elements, not working but another issue.
             .FullSeriesCollection(3).XValues = rng_Total_Date
             End If
             ' X-axis
             With cht.Chart.Axes(xlCategory)
                .CategoryType = xlTimeScale
                '.MajorUnitScale = xlMonths
                .MinimumScale = ArrDate(LBound(ArrDate, 1), 1)
                .MaximumScale = ArrDate(UBound(ArrDate, 1), 1)
                .MajorUnit = 3 ' Manually set x-axis unit scale
                '.MajorUnitIsAuto = True
             End With
            ' Y-axis
            With cht.Chart.Axes(xlValue)
                .MinimumScaleIsAuto = True
                .MaximumScaleIsAuto = True
                .MajorUnitIsAuto = True
            End With
        End With

End sub
</code>```

I wanted the series to continue after each other but instead they both begin at the first date of the horizontal axis. I suspect Excel does not recognize my attempt to match the date of my time series to the date of the x-axis.

Here is how my figure looks. I am using a line chart.

答:
Answer provided by @TimWilliams, if he doesn't create a post I will mark this as the answer when possible.

The solution is to use X-Y scatter plot (line option available) instead of the line chart I originally used.

Body:
SOLVED BY USING X-Y PLOT INSTEAD OF LINE CHART

I want to create a chart in Excel that contains multiple series that are linked in terms of date (i.e. one series ends on 2018/12/31 the next begins 2018/12/31). The raw data is taken from a sheet with two columns; the date column and the value column.

The chart in question here is called 'Beta' and contains 3 time series.
This is my attempt:

Sub UpdateGraph
Dim ws             As Worksheet
Dim rng_NF3        As Range
Dim rng_Barra      As Range
Dim rng_NF3_Date   As Range
Dim rng_Barra_Date As Range
Dim rng_Total_Date As Range
Dim rng_Total_Val  As Range
Dim cht_Name       As String
Dim ArrDate        As Variant
Dim arrValues      As Variant

        cht_Name = "Beta"  ' Example
        Set ws = Activesheet
        Set cht = ws.ChartObjects(cht_Name)
        Set rng_NF3 = ws.Range(ws.Cells(2, 4), ws.Cells(200, 4)) ' Set range of values from NF3 (GEM3)
        Set rng_Barra = ws.Range(ws.Cells(201, 4), ws.Cells(500, 4)) ' Set range of values Barra
        Set rng_NF3_Date = rng_NF3.Offset(0, -1) ' Set range of date for NF3 observations
        Set rng_Barra_Date = rng_Barra.Offset(0, -1) ' Set range of date for Barra observations
        Set rng_Total_Date = Union(rng_NF3_Date, rng_Barra_Date)
        Set rng_Total_Val = Union(rng_NF3, rng_Barra)
        ArrDate = rng_Total_Date.Value
        arrValues = rng_Total_Val.Value
        With cht.Chart
            .FullSeriesCollection(1).Format.Line.ForeColor.RGB = ws.Cells(1, 20).Interior.Color
            .FullSeriesCollection(2).Format.Line.ForeColor.RGB = ws.Cells(2, 20).Interior.Color
            .FullSeriesCollection(1).Values = rng_NF3 ' Value series for NF3
            .FullSeriesCollection(2).Values = rng_Barra ' Value series for Barra
            .FullSeriesCollection(1).XValues = rng_NF3_Date
            .FullSeriesCollection(2).XValues = rng_Barra_Date
             If cht_Name = "Beta" Then ' Defining Beta = 1
             .FullSeriesCollection(3).Format.Line.ForeColor.RGB = ws.Cells(1, 21).Interior.Color '  Color
             .FullSeriesCollection(3).Values = 1 ' Should be a range with the same number in all elements, not working but another issue.
             .FullSeriesCollection(3).XValues = rng_Total_Date
             End If
             ' X-axis
             With cht.Chart.Axes(xlCategory)
                .CategoryType = xlTimeScale
                '.MajorUnitScale = xlMonths
                .MinimumScale = ArrDate(LBound(ArrDate, 1), 1)
                .MaximumScale = ArrDate(UBound(ArrDate, 1), 1)
                .MajorUnit = 3 ' Manually set x-axis unit scale
                '.MajorUnitIsAuto = True
             End With
            ' Y-axis
            With cht.Chart.Axes(xlValue)
                .MinimumScaleIsAuto = True
                .MaximumScaleIsAuto = True
                .MajorUnitIsAuto = True
            End With
        End With

End sub

I wanted the series to continue after each other but instead they both begin at the first date of the horizontal axis. I suspect Excel does not recognize my attempt to match the date of my time series to the date of the x-axis.

Here is how my figure looks. I am using a line chart.


问:
How to update user data in MongoDB using node.js
I have a simple express app with MongoDB connection where I can register a user. Registering and logging in and out works fine but now I'm trying to add possibility to edit user data. My code doesn't throw any errors but it doesn't update the data in database neither.

I've tried to read the MongoDB documentation and similar problems from stackoverflow. But I just can't seem to get it work.

This is my route for update:

```<code>    User.updateOne({ id: req.session.passport.user}, {
        name: req.body.name,
        email: req.body.email,
        password: req.body.password
    }, function (err, user){
        if (err) return next(err);
        User.findById(req.user._id, function(err, user) {
            if (err) return next(err);
            return res.render('user', {
            name: user.name,
            email: user.email
        });
    });
});
});
</code>```

I expect it to update my database data but it just renders the user -page and nothing else happens.

EDIT.
Thank you for your answers, I tried those but it still just goes through but nothing happens in database.
I've also tried to make the edit work based on how I handle the registration and I actually got it to save the data but my problem with this solution is that it doesn't hash the password, it is saved as a string in my db. With registration hashing works fine. I also need to do the email validation somehow else because now it requires it to be changed every time I edit my data. Here's the code:

```<code>router.post('/update/:name', ensureAuthenticated, function(req, res, next){
  const { name, email, password, password2 } = req.body;
  let errors = [];

  //check required fields
  if (!name || !email || !password || !password2) {
    errors.push({ msg: 'Please fill in all fields' });
  }

  //check passwords match
  if (password !== password2) {
    errors.push({ msg: 'Passwords do not match' });
  }

  //check pass length
  if (password.length < 6) {
    errors.push({ msg: 'Password should be at least 6 characters' });
  }

  if (errors.length > 0) {
    res.render('update', {
      errors,
      name,
      email,
      password,
      password2
    });
  } else {
    //validation passed
    User.updateOne({ name: name, email: email, password: password })
      .then(user => {
        if (user) {
          //user exists
          errors.push({ msg: 'Email is already registered'});
          res.render('update', {
            errors,
            name,
            email,
            password,
            password2
          });
        } else {
          const updateUser = new User({
            name,
            email,
            password
          });

          //Hash password
          bcrypt.genSalt(10, (err, salt) =>
            bcrypt.hash(updateUser.password, salt, (err, hash) => {
              if (err) throw err;
              //set password to hashed
              updateUser.password = hash;
              //save user
              updateUser
                .save()
                .then(user => {
                  req.flash('success_msg', 'Info updatet, log in');
                  res.redirect('/users/login');
                })
                .catch(err => console.log(err));
          }));
        }
      });
  }
});
</code>```

答:
You need to use $set options with the modified property and it's value. Also be careful with the id parameter, in my case it's an ObjectId. May be in your case it is auto number or something. Anyways you need to pass _id instead of id value.

```<code>> db.users.find()
{ "_id" : ObjectId("5ceba75af8372745b2f6b861"), "name" : "allen", "email" : "email@gmail.com", "pass" : "kdsjds" }
{ "_id" : ObjectId("5ceba76cf8372745b2f6b862"), "name" : "sasmal", "email" : "sasmal@gmail.com", "pass" : "abc" }
</code>```

If you go ahead with only id property the way you have mentioned in the questions, it is not gonna update the record.

```<code>> db.users.updateOne({id: ObjectId("5ceba75af8372745b2f6b861")}, { $set: {name: 'update', email: 'update@gmail.com', pass:'pass'}});
{ "acknowledged" : true, "matchedCount" : 0, "modifiedCount" : 0 }
</code>```

it says it acknowledged but didn't able to match or modify anything.

But if you change the id to _id, you see a change in the message

```<code>> db.users.updateOne({_id: ObjectId("5ceba75af8372745b2f6b861")}, { $set: {name: 'update', email: 'update@gmail.com', pass:'pass'}});
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
</code>```

Now let's verify if it has changed the values in the database or not.

```<code>> db.users.find().pretty()
{
    "_id" : ObjectId("5ceba75af8372745b2f6b861"),
    "name" : "update",
    "email" : "update@gmail.com",
    "pass" : "pass"
}
{
    "_id" : ObjectId("5ceba76cf8372745b2f6b862"),
    "name" : "sasmal",
    "email" : "sasmal@gmail.com",
    "pass" : "abc"
}
</code>```

NOTE: I have used mongo shell here, if you are using mongodb js driver for nodejs then everything is same.

Hope it helps!

Body:
I have a simple express app with MongoDB connection where I can register a user. Registering and logging in and out works fine but now I'm trying to add possibility to edit user data. My code doesn't throw any errors but it doesn't update the data in database neither.

I've tried to read the MongoDB documentation and similar problems from stackoverflow. But I just can't seem to get it work.

This is my route for update:

    User.updateOne({ id: req.session.passport.user}, {
        name: req.body.name,
        email: req.body.email,
        password: req.body.password
    }, function (err, user){
        if (err) return next(err);
        User.findById(req.user._id, function(err, user) {
            if (err) return next(err);
            return res.render('user', {
            name: user.name,
            email: user.email
        });
    });
});
});

I expect it to update my database data but it just renders the user -page and nothing else happens.

EDIT.
Thank you for your answers, I tried those but it still just goes through but nothing happens in database.
I've also tried to make the edit work based on how I handle the registration and I actually got it to save the data but my problem with this solution is that it doesn't hash the password, it is saved as a string in my db. With registration hashing works fine. I also need to do the email validation somehow else because now it requires it to be changed every time I edit my data. Here's the code:

router.post('/update/:name', ensureAuthenticated, function(req, res, next){
  const { name, email, password, password2 } = req.body;
  let errors = [];

  //check required fields
  if (!name || !email || !password || !password2) {
    errors.push({ msg: 'Please fill in all fields' });
  }

  //check passwords match
  if (password !== password2) {
    errors.push({ msg: 'Passwords do not match' });
  }

  //check pass length
  if (password.length < 6) {
    errors.push({ msg: 'Password should be at least 6 characters' });
  }

  if (errors.length > 0) {
    res.render('update', {
      errors,
      name,
      email,
      password,
      password2
    });
  } else {
    //validation passed
    User.updateOne({ name: name, email: email, password: password })
      .then(user => {
        if (user) {
          //user exists
          errors.push({ msg: 'Email is already registered'});
          res.render('update', {
            errors,
            name,
            email,
            password,
            password2
          });
        } else {
          const updateUser = new User({
            name,
            email,
            password
          });

          //Hash password
          bcrypt.genSalt(10, (err, salt) =>
            bcrypt.hash(updateUser.password, salt, (err, hash) => {
              if (err) throw err;
              //set password to hashed
              updateUser.password = hash;
              //save user
              updateUser
                .save()
                .then(user => {
                  req.flash('success_msg', 'Info updatet, log in');
                  res.redirect('/users/login');
                })
                .catch(err => console.log(err));
          }));
        }
      });
  }
});

Body:
You need to use $set options with the modified property and it's value. Also be careful with the id parameter, in my case it's an ObjectId. May be in your case it is auto number or something. Anyways you need to pass _id instead of id value.

> db.users.find()
{ "_id" : ObjectId("5ceba75af8372745b2f6b861"), "name" : "allen", "email" : "email@gmail.com", "pass" : "kdsjds" }
{ "_id" : ObjectId("5ceba76cf8372745b2f6b862"), "name" : "sasmal", "email" : "sasmal@gmail.com", "pass" : "abc" }

If you go ahead with only id property the way you have mentioned in the questions, it is not gonna update the record.

> db.users.updateOne({id: ObjectId("5ceba75af8372745b2f6b861")}, { $set: {name: 'update', email: 'update@gmail.com', pass:'pass'}});
{ "acknowledged" : true, "matchedCount" : 0, "modifiedCount" : 0 }

it says it acknowledged but didn't able to match or modify anything.

But if you change the id to _id, you see a change in the message

> db.users.updateOne({_id: ObjectId("5ceba75af8372745b2f6b861")}, { $set: {name: 'update', email: 'update@gmail.com', pass:'pass'}});
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }

Now let's verify if it has changed the values in the database or not.

> db.users.find().pretty()
{
    "_id" : ObjectId("5ceba75af8372745b2f6b861"),
    "name" : "update",
    "email" : "update@gmail.com",
    "pass" : "pass"
}
{
    "_id" : ObjectId("5ceba76cf8372745b2f6b862"),
    "name" : "sasmal",
    "email" : "sasmal@gmail.com",
    "pass" : "abc"
}

NOTE: I have used mongo shell here, if you are using mongodb js driver for nodejs then everything is same.

Hope it helps!


问:
Android Get Keys from preferences.xml
I have a PreferencesActivity that shows a preferences.xml with checkboxes.

preferences.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory android:title="Keywords">
    <CheckBoxPreference android:key="Essen"
                        android:title="Essen"
                        android:selectable="true"
                        android:enabled="true"
                        android:persistent="false">
    </CheckBoxPreference>
    <CheckBoxPreference android:key="Kleidung"
                        android:title="Kleidung"
                        android:selectable="true"
                        android:enabled="true"
                        android:persistent="false">
    </CheckBoxPreference>
</PreferenceCategory>
</PreferenceScreen>
</code>```

PreferencesActivity:

```<code>public class PreferencesViewController extends PreferenceActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);
    }
}
</code>```

Now in a different ListActivity I want to show all Keys/Titles from the checked checkboxes.

I try to access the Preferences with

```<code>SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
</code>```

or

```<code>SharedPreferences prefs = getSharedPreferences("mypackage_preferences", 0);
</code>```

But both dont really work.

When I call prefs.getAll().size() the result is 0.

I can access the Keys/Title with getPreferenceScreen().getPreference(i).… but it doesn't work from a different Activity, only from the PreferenceActivity.

Does anybody have a solution how to get this work?

答:
You don't need a PreferenceActivity to accomplish this.

To access the preferences, that are used in your PreferenceActivity, you should use

```<code>SharedPreferences prefs =
    PreferenceManager.getDefaultSharedPreferences(getBaseContext());
</code>```

If your list of data comes from the server, than you can use a ListActivity / ExpandableListActivity / any custom activity to visualize it, but this way you need to write the handlers that change the preferences.

The common way to do this would be:

```<code>private void saveStringPreference(final String key, final String value)
{
    SharedPreferences.Editor editor = prefs.edit();
    editor.putString(key, value);
    editor.commit();
}
</code>```

If you need, you should create similar wrappers to deal with int, boolean, etc. values.

ContentLicense: CC BY-SA 2.5

Title: Android Get Keys from preferences.xml

Body:
I have a PreferencesActivity that shows a preferences.xml with checkboxes.

preferences.xml:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory android:title="Keywords">
    <CheckBoxPreference android:key="Essen"
                        android:title="Essen"
                        android:selectable="true"
                        android:enabled="true"
                        android:persistent="false">
    </CheckBoxPreference>
    <CheckBoxPreference android:key="Kleidung"
                        android:title="Kleidung"
                        android:selectable="true"
                        android:enabled="true"
                        android:persistent="false">
    </CheckBoxPreference>
</PreferenceCategory>
</PreferenceScreen>

PreferencesActivity:

public class PreferencesViewController extends PreferenceActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);
    }
}

Now in a different ListActivity I want to show all Keys/Titles from the checked checkboxes.

I try to access the Preferences with

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

or

SharedPreferences prefs = getSharedPreferences("mypackage_preferences", 0);

But both dont really work.

When I call prefs.getAll().size() the result is 0.

I can access the Keys/Title with getPreferenceScreen().getPreference(i).… but it doesn't work from a different Activity, only from the PreferenceActivity.

Does anybody have a solution how to get this work?

Body:
You don't need a PreferenceActivity to accomplish this.

To access the preferences, that are used in your PreferenceActivity, you should use

SharedPreferences prefs =
    PreferenceManager.getDefaultSharedPreferences(getBaseContext());

If your list of data comes from the server, than you can use a ListActivity / ExpandableListActivity / any custom activity to visualize it, but this way you need to write the handlers that change the preferences.

The common way to do this would be:

private void saveStringPreference(final String key, final String value)
{
    SharedPreferences.Editor editor = prefs.edit();
    editor.putString(key, value);
    editor.commit();
}

If you need, you should create similar wrappers to deal with int, boolean, etc. values.


问:
Multiply each pixel in an image by a factor
I have an image that is created by using a bayer filter and the colors are slightly off.  I need to multiply RG and B of each pixel by a certain factor ( a different factor for R, G and B each) to get the correct color.  I am using the python imaging library and of course writing in python.  is there any way to do this efficiently?

Thanks!

答:
You can do this pretty efficiently and simply using a simple transform matrix with the convert() function:

```<code>#!/usr/bin/env python3

from PIL import Image

# Open image
im = Image.open('tree.jpg')

# Make transform matrix, to multiply R by 1.5, leaving G and B unchanged
Matrix = ( 1.5, 0,  0, 0,
           0,   1,  0, 0,
           0,   0,  1, 0)

# Apply transform and save
im = im.convert("RGB", Matrix)
im.save('result.png')
</code>```

Input image:

Result image:

You can read that matrix as saying:

```<code>newRed   = 1.5*oldRed + 0.0*oldGreen + 0.0*oldGreen + 0.0
newGreen = 0.0*oldRed + 1.0*oldGreen + 0.0*oldBlue  + 0.0
newBlue  = 0.0*oldRed + 0.0*oldGreen + 1.0*oldBlue  + 0.0
</code>```

Keywords: Python, PIL, Pillow, color matrix, colour matrix, transform, multiply channel, scale channel, separate, separately, individual channels, bands, components, individually, split channels, merge channels, image, image processing.

Body:
You can do this pretty efficiently and simply using a simple transform matrix with the convert() function:

#!/usr/bin/env python3

from PIL import Image

# Open image
im = Image.open('tree.jpg')

# Make transform matrix, to multiply R by 1.5, leaving G and B unchanged
Matrix = ( 1.5, 0,  0, 0,
           0,   1,  0, 0,
           0,   0,  1, 0)

# Apply transform and save
im = im.convert("RGB", Matrix)
im.save('result.png')

Input image:

Result image:

You can read that matrix as saying:

newRed   = 1.5*oldRed + 0.0*oldGreen + 0.0*oldGreen + 0.0
newGreen = 0.0*oldRed + 1.0*oldGreen + 0.0*oldBlue  + 0.0
newBlue  = 0.0*oldRed + 0.0*oldGreen + 1.0*oldBlue  + 0.0

Keywords: Python, PIL, Pillow, color matrix, colour matrix, transform, multiply channel, scale channel, separate, separately, individual channels, bands, components, individually, split channels, merge channels, image, image processing.


问:
Removing all duplicates in data.table, adding column with list of identifiers
Building on my previous question, I have the following data.table:

```<code>> dt = data.table(V1 = c(1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 4),
                  V2 = c(4, 4, 4, 5, 5, 6, 6, 7, 7, 4, 5),
                  ID = c(1, 2, 3, 1, 2, 2, 2, 1, 3, 1, 1))
    V1 V2 ID
 1:  1  4  1
 2:  1  4  2
 3:  1  4  3
 4:  2  5  1
 5:  2  5  2
 6:  2  6  2
 7:  2  6  2
 8:  2  7  1
 9:  2  7  3
10:  3  4  1
11:  4  5  1
</code>```

with many duplicate rows (when looking at V1 and V2).

I want to remove all the "entirely duplicate" rows (those where V2 is always the same for a given V1), including the ones with a unique V1 (since all one V2 is equal to itself).

I was given many solutions in the previous question linked above, including @akrun's (modified for this new table):

```<code>> newDT = unique(dt[dt[, .(i1 = .I[uniqueN(V2) > 1]), V1]$i1], by = c("V1", "V2"))
   V1 V2 ID
1:  2  5  1
2:  2  6  2
3:  2  7  3
</code>```

However, I actually need to store a list of IDs which had a given result. I can collect the list of IDs for a given pair of (V1, V2) trivially with

```<code>> unique(dt[V1 == 2 & V2 == 5, ID])
[1] 1 2
</code>```

(unique is necessary because a given (V1,V2) pair may also have duplicate ID, see dt rows 6:7) and add it with

```<code>newDT[, ID := .(.(unique(dt[V1 == 2 & V2 == 5, ID])))]
</code>```

but I can't figure out how to "iterate" over each (V1,V2) pair.

In summary, I need the output to be

```<code>> newDT
   V1 V2      ID
1:  2  5  (1, 2)
2:  2  6     (2)
3:  2  7  (1, 3)
</code>```

答:
```<code>dt[, .(ID = .(unique(ID))), by = .(V1, V2)
   ][dt[, .(V2 = if (uniqueN(V2) > 1) unique(V2) else numeric(0)), by = V1], on = .(V1, V2)]
</code>```

Broken down into steps:

```<code># Extract our pairs of interests first
our_pairs <- dt[, .(V2 = if (uniqueN(V2) > 1) unique(V2) else numeric(0)), by = V1]
our_pairs
#    V1 V2
# 1:  2  5
# 2:  2  6
# 3:  2  7

# Aggregate all ID's for each pair on original data
ids_forpairs <- dt[, .(ID = .(unique(ID))), by = .(V1, V2)]
ids_forpairs
#    V1 V2    ID
# 1:  1  4 1,2,3
# 2:  2  5   1,2
# 3:  2  6     2
# 4:  2  7   1,3
# 5:  3  4     1
# 6:  4  5     1

# Then filter by our pairs of interest
ids_forpairs[our_pairs, on = .(V1, V2)]
#    V1 V2  ID
# 1:  2  5 1,2
# 2:  2  6   2
# 3:  2  7 1,3
</code>```

Body:
Building on my previous question, I have the following data.table:

> dt = data.table(V1 = c(1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 4),
                  V2 = c(4, 4, 4, 5, 5, 6, 6, 7, 7, 4, 5),
                  ID = c(1, 2, 3, 1, 2, 2, 2, 1, 3, 1, 1))
    V1 V2 ID
 1:  1  4  1
 2:  1  4  2
 3:  1  4  3
 4:  2  5  1
 5:  2  5  2
 6:  2  6  2
 7:  2  6  2
 8:  2  7  1
 9:  2  7  3
10:  3  4  1
11:  4  5  1

with many duplicate rows (when looking at V1 and V2).

I want to remove all the "entirely duplicate" rows (those where V2 is always the same for a given V1), including the ones with a unique V1 (since all one V2 is equal to itself).

I was given many solutions in the previous question linked above, including @akrun's (modified for this new table):

> newDT = unique(dt[dt[, .(i1 = .I[uniqueN(V2) > 1]), V1]$i1], by = c("V1", "V2"))
   V1 V2 ID
1:  2  5  1
2:  2  6  2
3:  2  7  3

However, I actually need to store a list of IDs which had a given result. I can collect the list of IDs for a given pair of (V1, V2) trivially with

> unique(dt[V1 == 2 & V2 == 5, ID])
[1] 1 2

(unique is necessary because a given (V1,V2) pair may also have duplicate ID, see dt rows 6:7) and add it with

newDT[, ID := .(.(unique(dt[V1 == 2 & V2 == 5, ID])))]

but I can't figure out how to "iterate" over each (V1,V2) pair.

In summary, I need the output to be

> newDT
   V1 V2      ID
1:  2  5  (1, 2)
2:  2  6     (2)
3:  2  7  (1, 3)

Body:
dt[, .(ID = .(unique(ID))), by = .(V1, V2)
   ][dt[, .(V2 = if (uniqueN(V2) > 1) unique(V2) else numeric(0)), by = V1], on = .(V1, V2)]

Broken down into steps:

# Extract our pairs of interests first
our_pairs <- dt[, .(V2 = if (uniqueN(V2) > 1) unique(V2) else numeric(0)), by = V1]
our_pairs
#    V1 V2
# 1:  2  5
# 2:  2  6
# 3:  2  7

# Aggregate all ID's for each pair on original data
ids_forpairs <- dt[, .(ID = .(unique(ID))), by = .(V1, V2)]
ids_forpairs
#    V1 V2    ID
# 1:  1  4 1,2,3
# 2:  2  5   1,2
# 3:  2  6     2
# 4:  2  7   1,3
# 5:  3  4     1
# 6:  4  5     1

# Then filter by our pairs of interest
ids_forpairs[our_pairs, on = .(V1, V2)]
#    V1 V2  ID
# 1:  2  5 1,2
# 2:  2  6   2
# 3:  2  7 1,3


问:
Shifting from iterator to for each
I have a panel1 function that returns an iterator that works with the following program:

```<code>public static void main(String[] args) {

     Iterator<Integer> it = panel1(1,5);
     for(;it.hasNext();)
        System.out.println(it.next()); // return 1 2 3 4 5
}
</code>```

For simplicity, I want to facilitate this by using the Java foreach syntax as shown in the following example.

```<code>for(int i:panel2(1,5))
    System.out.println(i); // would return 1 2 3 4 5
</code>```

Here is the Panel class I did so far with an anonym class:

```<code>import java.util.Iterator;
import java.util.NoSuchElementException;

public class Panel{

    public static Iterator<Integer> panel1(final int begin,final int end){
        Iterator<Integer> it = new Iterator<Integer>(){

            private int nextValue = begin;
            private final int max = end;

            public boolean hasNext() {
                return nextValue <= max;
            }

            public Integer next() {
                if (!hasNext()) {
                    throw new NoSuchElementException();
                }
                return Integer.valueOf(nextValue++);
            }

            public void remove() {
                throw new UnsupportedOperationException();
            }
        };
        return it;
    }

    public static void main(String[] args) {

         Iterator<Integer> it = panel1(1,5);
         for(;it.hasNext();)
            System.out.println(it.next()); // affiche 1 2 3 4 5
    }
}
</code>```

答:
Use Iterable instead of Iterator in the method signature:

```<code>public static Iterable<Integer> panel1(final int begin,final int end) {
  ...
  return () -> it;

}
</code>```

Title: Shifting from iterator to for each

Body:
I have a panel1 function that returns an iterator that works with the following program:

public static void main(String[] args) {

     Iterator<Integer> it = panel1(1,5);
     for(;it.hasNext();)
        System.out.println(it.next()); // return 1 2 3 4 5
}

For simplicity, I want to facilitate this by using the Java foreach syntax as shown in the following example.

for(int i:panel2(1,5))
    System.out.println(i); // would return 1 2 3 4 5

Here is the Panel class I did so far with an anonym class:

import java.util.Iterator;
import java.util.NoSuchElementException;

public class Panel{

    public static Iterator<Integer> panel1(final int begin,final int end){
        Iterator<Integer> it = new Iterator<Integer>(){

            private int nextValue = begin;
            private final int max = end;

            public boolean hasNext() {
                return nextValue <= max;
            }

            public Integer next() {
                if (!hasNext()) {
                    throw new NoSuchElementException();
                }
                return Integer.valueOf(nextValue++);
            }

            public void remove() {
                throw new UnsupportedOperationException();
            }
        };
        return it;
    }

    public static void main(String[] args) {

         Iterator<Integer> it = panel1(1,5);
         for(;it.hasNext();)
            System.out.println(it.next()); // affiche 1 2 3 4 5
    }
}

Body:
Use Iterable instead of Iterator in the method signature:

public static Iterable<Integer> panel1(final int begin,final int end) {
  ...
  return () -> it;

}


问:
How to properly add an object to a list when the list is a custom class object?
I get a null reference exception when I try to add a region to the list and have no idea what I'm doing wrong. I simply can't figure it and I've done this a million times.</p>

```<code>public List<Region> regions;

public class Region
{
    public int x_size;
    public int y_size;

    public enum terrain
    {
        desert,
        lowlands,
        crater,
        city
    };

    public terrain ground;
}

private void NewRegion()
{
    Region thisRegion = new Region();
    thisRegion.x_size = Random.Range(25, 50);
    thisRegion.y_size = Random.Range(25, 50);
    thisRegion.ground = Region.terrain.desert;
    regions.Add(thisRegion);
}
</code>```

答:
You should make Region a [Serilizable] type:

```<code>[Serializable]
public class Region
{
    public int x_size;
    public int y_size;

    public enum terrain
    {
        desert,
        lowlands,
        crater,
        city
    };

    public terrain ground;
}
</code>```

Since the field regions is public it would be automatically serilaized and initialized by the Unity Inspector anyway if the Region was serializable.

So now the upper code would have two advantages

You don't have to have the code

```<code>region = new List<Region>();
</code>```

nowhere. It would be initaialized automatically by Unity.

It is still recommneded to have it, though, but I wouldn't do it in Start but simply like

```<code>public List<Region> regions = new List<Region>();
</code>```

The other really huge advantage is that now you should actually see that list in the Unity Inspector so you can directly from the Editor add and adjust elements without having to hardcode them via a script.

Body:
I get a null reference exception when I try to add a region to the list and have no idea what I'm doing wrong. I simply can't figure it and I've done this a million times.

public List<Region> regions;

public class Region
{
    public int x_size;
    public int y_size;

    public enum terrain
    {
        desert,
        lowlands,
        crater,
        city
    };

    public terrain ground;
}

private void NewRegion()
{
    Region thisRegion = new Region();
    thisRegion.x_size = Random.Range(25, 50);
    thisRegion.y_size = Random.Range(25, 50);
    thisRegion.ground = Region.terrain.desert;
    regions.Add(thisRegion);
}

Body:
You should make Region a [Serilizable] type:

[Serializable]
public class Region
{
    public int x_size;
    public int y_size;

    public enum terrain
    {
        desert,
        lowlands,
        crater,
        city
    };

    public terrain ground;
}

Since the field regions is public it would be automatically serilaized and initialized by the Unity Inspector anyway if the Region was serializable.

So now the upper code would have two advantages

You don't have to have the code

region = new List<Region>();

nowhere. It would be initaialized automatically by Unity.

It is still recommneded to have it, though, but I wouldn't do it in Start but simply like

public List<Region> regions = new List<Region>();

The other really huge advantage is that now you should actually see that list in the Unity Inspector so you can directly from the Editor add and adjust elements without having to hardcode them via a script.


问:
ASP.NET MVC to ASP.NET CORE 2.2 migration: How to send messages (SMS, email, etc.)
MVC Assembly: Microsoft.AspNet.Identity.UserManager

CORE Assembly: Microsoft.Extensions.Identity.Core

I am migrating from MVC to .NET CORE 2.2. I have created a MyManager class that inherits from UserManager. The UserManager class in MVC has the following properties:

public IIdentityMessageService EmailService { get; set; }

public IIdentityMessageService SmsService { get; set; }

In .NET CORE 2.2., the UserManager does not have these properties. I am guessing that the MVC UserManager uses those properties to automatically send messages. It looks like it uses the EmailService to automatically send the message that verifies the email address. However, this behavior does not appear to happen in .NET CORE. So, it looks like the UserManager no longer handles this.

The question is this: How do you verify a user's email address?

Is this being handled in a different Microsoft assembly or has Microsoft gotten out of that business and farmed it off to a 3rd-party assembly? Or, is there something else?

答:
this is how i send email verification using Sendgrid in asp.net core.

step 1 : Create a class called EmailSender that implements IEmailSender Interface(need to include using Microsoft.AspNetCore.Identity.UI.Services; for IEmailSender) :

```<code> public class EmailSender : IEmailSender
{
    public async Task SendEmailAsync(string email, string subject, string htmlMessage)
    {
        var apiKey = "send grid api key";
        //it looks like this  :
        // var apiKey = "SG.2MpCzyTvIQ.WhHMg6-VBjuqbn9k-8P9m6X9cHM73fk2fzAT5sA4zKc";

        var client = new SendGridClient(apiKey);
        var from = new EmailAddress($"noreply@domaimName.com", "Email title");
        var to = new EmailAddress(email, email);
        var plainTextContent = htmlMessage;
        var htmlContent = htmlMessage;
        var msg = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
        try
        {
            var response = await client.SendEmailAsync(msg);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        //return Task.CompletedTask;
    }
}
</code>```

Step 2 :  You need to add it as a service using Dependency Injection inside the Startup.cs file

```<code> services.AddTransient<IEmailSender, EmailSender>();
</code>```

Step 3 : Inject it into the constructor of the class you want to use it in.

```<code>   [AllowAnonymous]
public class RegisterModel : PageModel
{
      private readonly IEmailSender _emailSender;

    public RegisterModel(IEmailSender emailSender)
    {
        _emailSender = emailSender;
    }

     public async Task<IActionResult> OnPostAsync(string returnUrl = null)
    {
        returnUrl = returnUrl ?? Url.Content("~/");
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser
                           {
                                UserName = Input.Email,
                                Email = Input.Email,
                                DateCreated = DateTime.Now
                            };
            var result = await _userManager.CreateAsync(user, Input.Password);
            if (result.Succeeded)
            {
                _logger.LogInformation("User created a new account with password.");
                returnUrl = Url.Action("ConfirmEmail", "Home");
                var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                await _userManager.AddToRoleAsync(user,"ROleName");
                var callbackUrl = Url.Page(
                    "/Account/ConfirmEmail",
                    pageHandler: null,
                    values: new { userId = user.Id, code = code },
                    protocol: Request.Scheme);
</code>```

```<code>               await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                    $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");
</code>```

```<code>                return LocalRedirect(returnUrl);
            }
            foreach (var error in result.Errors)
            {
                ModelState.AddModelError(string.Empty, error.Description);
            }
        }

        // If we got this far, something failed, redisplay form
        return Page();
    }
</code>```

and this should send your email. it works for me and it should for you too.

Body:
this is how i send email verification using Sendgrid in asp.net core.

step 1 : Create a class called EmailSender that implements IEmailSender Interface(need to include using Microsoft.AspNetCore.Identity.UI.Services; for IEmailSender) :

 public class EmailSender : IEmailSender
{
    public async Task SendEmailAsync(string email, string subject, string htmlMessage)
    {
        var apiKey = "send grid api key";
        //it looks like this  :
        // var apiKey = "SG.2MpCzyTvIQ.WhHMg6-VBjuqbn9k-8P9m6X9cHM73fk2fzAT5sA4zKc";

        var client = new SendGridClient(apiKey);
        var from = new EmailAddress($"noreply@domaimName.com", "Email title");
        var to = new EmailAddress(email, email);
        var plainTextContent = htmlMessage;
        var htmlContent = htmlMessage;
        var msg = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
        try
        {
            var response = await client.SendEmailAsync(msg);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        //return Task.CompletedTask;
    }
}

Step 2 :  You need to add it as a service using Dependency Injection inside the Startup.cs file

 services.AddTransient<IEmailSender, EmailSender>();

Step 3 : Inject it into the constructor of the class you want to use it in.

   [AllowAnonymous]
public class RegisterModel : PageModel
{
      private readonly IEmailSender _emailSender;

    public RegisterModel(IEmailSender emailSender)
    {
        _emailSender = emailSender;
    }

     public async Task<IActionResult> OnPostAsync(string returnUrl = null)
    {
        returnUrl = returnUrl ?? Url.Content("~/");
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser
                           {
                                UserName = Input.Email,
                                Email = Input.Email,
                                DateCreated = DateTime.Now
                            };
            var result = await _userManager.CreateAsync(user, Input.Password);
            if (result.Succeeded)
            {
                _logger.LogInformation("User created a new account with password.");
                returnUrl = Url.Action("ConfirmEmail", "Home");
                var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                await _userManager.AddToRoleAsync(user,"ROleName");
                var callbackUrl = Url.Page(
                    "/Account/ConfirmEmail",
                    pageHandler: null,
                    values: new { userId = user.Id, code = code },
                    protocol: Request.Scheme);

               await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                    $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                return LocalRedirect(returnUrl);
            }
            foreach (var error in result.Errors)
            {
                ModelState.AddModelError(string.Empty, error.Description);
            }
        }

        // If we got this far, something failed, redisplay form
        return Page();
    }

and this should send your email. it works for me and it should for you too.


问:
graphql query to json query
Given this GraphQL example, how can I in Javascript do a similar request with JSON?

Using GraphQL the query in the example is:

```<code>{
  trip(
    from: {place: "NSR:StopPlace:5533" },
    to: {place:"NSR:StopPlace:5532"}
  )
    {
    tripPatterns{duration}
  }
}
</code>```

According to the documentation the URL to query is https://api.entur.io/journey-planner/v2/graphql .

Here is what I tried in Javascript:

```<code>var url = "https://api.entur.io/journey-planner/v2/graphql";

var tripquery =
{
    trip:
    {
        __args: {
            from : {place :"NSR:StopPlace:5533" },
            to : {place :"NSR:StopPlace:5532" }
        },
        tripPatterns: {
            duration : true
        }
    }
};

function jsonQuery(){

    var qry = JSON.stringify(tripquery);
    var url_qry = url + "?query=" + qry;

    var xhttp = new XMLHttpRequest();
    xhttp.open("POST", url_qry, true);
    xhttp.setRequestHeader("Content-Type", "application/json");

    xhttp.onreadystatechange = function(){
        console.log("onreadystatechange");
        if(xhttp.readyState === 4 && xhttp.status === 200){
            console.log("json-query-OK");
            console.log(xhttp.responseText);
        }
        else{
            console.log("xhttp.status      : " + xhttp.status);
            console.log("xhttp.statusText  : " + xhttp.statusText);
            console.log("xhttp.readyState  : " + xhttp.readyState);
            console.log("xhttp.responseType: " + xhttp.responseType);
            console.log("xhttp.responseText: " + xhttp.responseText);
            console.log("xhttp.responseURL : " + xhttp.responseURL);
            console.log("json-not-ok");
        }
    };

    xhttp.send();
    console.log("query sent");
}
</code>```

The code above will result in this output in the console:

```<code>query sent
api.entur.io/journey-planner/v2/graphql?query={%22trip%22:{%22__args%22:{%22from%22:{%22place%22:%22NSR:StopPlace:5533%22},%22to%22:{%22place%22:%22NSR:StopPlace:5532%22}},%22tripPatterns%22:{%22duration%22:true}}}:1 POST https://api.entur.io/journey-planner/v2/graphql?query={%22trip%22:{%22__args%22:{%22from%22:{%22place%22:%22NSR:StopPlace:5533%22},%22to%22:{%22place%22:%22NSR:StopPlace:5532%22}},%22tripPatterns%22:{%22duration%22:true}}} 400 (Bad Request)
query.js:29 onreadystatechange
query.js:35 xhttp.status      : 400
query.js:36 xhttp.statusText  : Bad Request
query.js:37 xhttp.readyState  : 2
query.js:38 xhttp.responseType:
query.js:39 xhttp.responseText:
query.js:40 xhttp.responseURL : https://api.entur.io/journey-planner/v2/graphql?query={%22trip%22:{%22__args%22:{%22from%22:{%22place%22:%22NSR:StopPlace:5533%22},%22to%22:{%22place%22:%22NSR:StopPlace:5532%22}},%22tripPatterns%22:{%22duration%22:true}}}
query.js:41 json-not-ok
query.js:29 onreadystatechange
query.js:35 xhttp.status      : 400
query.js:36 xhttp.statusText  : Bad Request
query.js:37 xhttp.readyState  : 3
query.js:38 xhttp.responseType:
query.js:39 xhttp.responseText: No query found in body
query.js:40 xhttp.responseURL : https://api.entur.io/journey-planner/v2/graphql?query={%22trip%22:{%22__args%22:{%22from%22:{%22place%22:%22NSR:StopPlace:5533%22},%22to%22:{%22place%22:%22NSR:StopPlace:5532%22}},%22tripPatterns%22:{%22duration%22:true}}}
query.js:41 json-not-ok
query.js:29 onreadystatechange
query.js:35 xhttp.status      : 400
query.js:36 xhttp.statusText  : Bad Request
query.js:37 xhttp.readyState  : 4
query.js:38 xhttp.responseType:
query.js:39 xhttp.responseText: No query found in body
query.js:40 xhttp.responseURL : https://api.entur.io/journey-planner/v2/graphql?query={%22trip%22:{%22__args%22:{%22from%22:{%22place%22:%22NSR:StopPlace:5533%22},%22to%22:{%22place%22:%22NSR:StopPlace:5532%22}},%22tripPatterns%22:{%22duration%22:true}}}
query.js:41 json-not-ok
</code>```

The __args in the Json object is something I got from an example online, but I haven't really understood it.

Maybe I'm not sure what exactly to search for, but I can't find some good explanation of how to translate this GraphQL query to a JSON object.

答:
I had the same problem and I did it like this:

```<code>{
  c_con_tic_PTF(dz: CR, docmanId: 123) {
    docmanId
    dz
    data
  }
}
</code>```

I tried sending this request as curl command in OS X How to use CURL in OS X:

```<code>curl \
      -X POST \
      -H "Content-Type: application/json" \
      --data '{ "query": "{  c_con_tic_PTF(docmanId: 123, dz: CR) { docmanId, dz, data }}" }' \

   *my-graphicQL endpoint url*
</code>```

And I got the response I wanted.

So you want to make something like this from your graphQL query:

```<code>{ "query": "{  cz_atlascon_etic_PTF(docmanId: 123, dz: CR) { docmanId, dz, data }}" }
</code>```

And now just send request with JS.
If it helps you in any way, this is how my request looked in Java:

```<code>HttpRequest mainRequest =
HttpRequest.newBuilder()
.uri(URI.create("my graphQL endpoint"))
.POST(HttpRequest.BodyPublishers.ofString("{ \"query\": \"{  c_con_tic_PTF(docmanId: 123, dz: CR) { docmanId, dz, data }}\" }"))
.build();
</code>```

Title: graphql query to json query

Body:
Given this GraphQL example, how can I in Javascript do a similar request with JSON?

Using GraphQL the query in the example is:

{
  trip(
    from: {place: "NSR:StopPlace:5533" },
    to: {place:"NSR:StopPlace:5532"}
  )
    {
    tripPatterns{duration}
  }
}

According to the documentation the URL to query is https://api.entur.io/journey-planner/v2/graphql .

Here is what I tried in Javascript:

var url = "https://api.entur.io/journey-planner/v2/graphql";

var tripquery =
{
    trip:
    {
        __args: {
            from : {place :"NSR:StopPlace:5533" },
            to : {place :"NSR:StopPlace:5532" }
        },
        tripPatterns: {
            duration : true
        }
    }
};

function jsonQuery(){

    var qry = JSON.stringify(tripquery);
    var url_qry = url + "?query=" + qry;

    var xhttp = new XMLHttpRequest();
    xhttp.open("POST", url_qry, true);
    xhttp.setRequestHeader("Content-Type", "application/json");

    xhttp.onreadystatechange = function(){
        console.log("onreadystatechange");
        if(xhttp.readyState === 4 && xhttp.status === 200){
            console.log("json-query-OK");
            console.log(xhttp.responseText);
        }
        else{
            console.log("xhttp.status      : " + xhttp.status);
            console.log("xhttp.statusText  : " + xhttp.statusText);
            console.log("xhttp.readyState  : " + xhttp.readyState);
            console.log("xhttp.responseType: " + xhttp.responseType);
            console.log("xhttp.responseText: " + xhttp.responseText);
            console.log("xhttp.responseURL : " + xhttp.responseURL);
            console.log("json-not-ok");
        }
    };

    xhttp.send();
    console.log("query sent");
}

The code above will result in this output in the console:

query sent
api.entur.io/journey-planner/v2/graphql?query={%22trip%22:{%22__args%22:{%22from%22:{%22place%22:%22NSR:StopPlace:5533%22},%22to%22:{%22place%22:%22NSR:StopPlace:5532%22}},%22tripPatterns%22:{%22duration%22:true}}}:1 POST https://api.entur.io/journey-planner/v2/graphql?query={%22trip%22:{%22__args%22:{%22from%22:{%22place%22:%22NSR:StopPlace:5533%22},%22to%22:{%22place%22:%22NSR:StopPlace:5532%22}},%22tripPatterns%22:{%22duration%22:true}}} 400 (Bad Request)
query.js:29 onreadystatechange
query.js:35 xhttp.status      : 400
query.js:36 xhttp.statusText  : Bad Request
query.js:37 xhttp.readyState  : 2
query.js:38 xhttp.responseType:
query.js:39 xhttp.responseText:
query.js:40 xhttp.responseURL : https://api.entur.io/journey-planner/v2/graphql?query={%22trip%22:{%22__args%22:{%22from%22:{%22place%22:%22NSR:StopPlace:5533%22},%22to%22:{%22place%22:%22NSR:StopPlace:5532%22}},%22tripPatterns%22:{%22duration%22:true}}}
query.js:41 json-not-ok
query.js:29 onreadystatechange
query.js:35 xhttp.status      : 400
query.js:36 xhttp.statusText  : Bad Request
query.js:37 xhttp.readyState  : 3
query.js:38 xhttp.responseType:
query.js:39 xhttp.responseText: No query found in body
query.js:40 xhttp.responseURL : https://api.entur.io/journey-planner/v2/graphql?query={%22trip%22:{%22__args%22:{%22from%22:{%22place%22:%22NSR:StopPlace:5533%22},%22to%22:{%22place%22:%22NSR:StopPlace:5532%22}},%22tripPatterns%22:{%22duration%22:true}}}
query.js:41 json-not-ok
query.js:29 onreadystatechange
query.js:35 xhttp.status      : 400
query.js:36 xhttp.statusText  : Bad Request
query.js:37 xhttp.readyState  : 4
query.js:38 xhttp.responseType:
query.js:39 xhttp.responseText: No query found in body
query.js:40 xhttp.responseURL : https://api.entur.io/journey-planner/v2/graphql?query={%22trip%22:{%22__args%22:{%22from%22:{%22place%22:%22NSR:StopPlace:5533%22},%22to%22:{%22place%22:%22NSR:StopPlace:5532%22}},%22tripPatterns%22:{%22duration%22:true}}}
query.js:41 json-not-ok

The __args in the Json object is something I got from an example online, but I haven't really understood it.

Maybe I'm not sure what exactly to search for, but I can't find some good explanation of how to translate this GraphQL query to a JSON object.

Body:
I had the same problem and I did it like this:

{
  c_con_tic_PTF(dz: CR, docmanId: 123) {
    docmanId
    dz
    data
  }
}

I tried sending this request as curl command in OS X How to use CURL in OS X:

curl \
      -X POST \
      -H "Content-Type: application/json" \
      --data '{ "query": "{  c_con_tic_PTF(docmanId: 123, dz: CR) { docmanId, dz, data }}" }' \

   *my-graphicQL endpoint url*

And I got the response I wanted.

So you want to make something like this from your graphQL query:

{ "query": "{  cz_atlascon_etic_PTF(docmanId: 123, dz: CR) { docmanId, dz, data }}" }

And now just send request with JS.
If it helps you in any way, this is how my request looked in Java:

HttpRequest mainRequest =
HttpRequest.newBuilder()
.uri(URI.create("my graphQL endpoint"))
.POST(HttpRequest.BodyPublishers.ofString("{ \"query\": \"{  c_con_tic_PTF(docmanId: 123, dz: CR) { docmanId, dz, data }}\" }"))
.build();


问:
What is php's performance on directly accessing array's row with key specified
I have a question regarding array's performance.... how does php handle array keys? I mean if I do something like $my_city = $cities[15]; .... does php directly access the exact row item in $cities array or does php iterate trough array until it finds the matched row?

and if it access the row directly... is there a difference in performance between an array with 100 rows and array with 100,000 rows?

like in this example
$my_city = $cities[15];

答:
It depends on what is inside the array too.

```<code>// $my_city is a reference to the variable
$cities[15] = new stdobj();
$my_city = $cities[15];

// $my_city is a copy of the array row
$cities[15] = 'foobar';
$my_city = $cities[15];
</code>```

May not be a direct answer to you question, but a reference to an object usually uses less memory than a variable copy.

Body:
It depends on what is inside the array too.

// $my_city is a reference to the variable
$cities[15] = new stdobj();
$my_city = $cities[15];

// $my_city is a copy of the array row
$cities[15] = 'foobar';
$my_city = $cities[15];

May not be a direct answer to you question, but a reference to an object usually uses less memory than a variable copy.


问:
Unable to connect to any servers
I have lost connection to Cassandra server and I am not able to restore it back.

When I run: sudo service cassandra status I can see service is running:

```<code>● cassandra.service - LSB: distributed storage system for structured data
   Loaded: loaded (/etc/init.d/cassandra; generated; vendor preset: enabled)
   Active: active (exited) since Fri 2018-04-27 13:06:21 UTC; 4min 5s ago
     Docs: man:systemd-sysv-generator(8)
  Process: 18479 ExecStop=/etc/init.d/cassandra stop (code=exited, status=0/SUCCESS)
  Process: 18539 ExecStart=/etc/init.d/cassandra start (code=exited, status=0/SUCCESS)
    Tasks: 0 (limit: 4915)
   CGroup: /system.slice/cassandra.service

Apr 27 13:06:21 serveur-1 systemd[1]: Starting LSB: distributed storage system for structured data...
Apr 27 13:06:21 serveur-1 systemd[1]: Started LSB: distributed storage system for structured data.
</code>```

But When I run  > cqlsh, I got the following:

```<code>Connection error: ('Unable to connect to any servers', {'127.0.0.1': error(111, "Tried connecting to [('127.0.0.1', 9042)]. Last error: Connection refused")})
</code>```

答: Delete all content from commitlog and it will work.</p>

Title: Unable to connect to any servers

Body:
I have lost connection to Cassandra server and I am not able to restore it back.

When I run: sudo service cassandra status I can see service is running:

● cassandra.service - LSB: distributed storage system for structured data
   Loaded: loaded (/etc/init.d/cassandra; generated; vendor preset: enabled)
   Active: active (exited) since Fri 2018-04-27 13:06:21 UTC; 4min 5s ago
     Docs: man:systemd-sysv-generator(8)
  Process: 18479 ExecStop=/etc/init.d/cassandra stop (code=exited, status=0/SUCCESS)
  Process: 18539 ExecStart=/etc/init.d/cassandra start (code=exited, status=0/SUCCESS)
    Tasks: 0 (limit: 4915)
   CGroup: /system.slice/cassandra.service

Apr 27 13:06:21 serveur-1 systemd[1]: Starting LSB: distributed storage system for structured data...
Apr 27 13:06:21 serveur-1 systemd[1]: Started LSB: distributed storage system for structured data.

But When I run  > cqlsh, I got the following:

Connection error: ('Unable to connect to any servers', {'127.0.0.1': error(111, "Tried connecting to [('127.0.0.1', 9042)]. Last error: Connection refused")})


问:
Jade conditional based on page url?
Is it possible to setup a jade conditional in my layout template based on page path? Is there a page path variable? I am looking to do things like:

```<code>if page = "/about"
  link(rel='stylesheet', href='css/about')
else
  link(rel='stylesheet', href='css/main')
</code>```

Where this is part of the layout template. Where and how do I define the variables to drive this?

答:
I would set the path dynamically with req.path in express:

```<code>res.locals.path = req.path;
res.render('about');
</code>```

and then using path in jade file:

```<code>if path === "/about/"
   link(rel='stylesheet', href='css/about.css')
else
   link(rel='stylesheet', href='css/main.css')
</code>```

Title: Jade conditional based on page url?

Body:
Is it possible to setup a jade conditional in my layout template based on page path? Is there a page path variable? I am looking to do things like:

if page = "/about"
  link(rel='stylesheet', href='css/about')
else
  link(rel='stylesheet', href='css/main')

Where this is part of the layout template. Where and how do I define the variables to drive this?

Body:
I would set the path dynamically with req.path in express:

res.locals.path = req.path;
res.render('about');

and then using path in jade file:

if path === "/about/"
   link(rel='stylesheet', href='css/about.css')
else
   link(rel='stylesheet', href='css/main.css')


问:
Create R data with a dynamic variable name from function for package?
I am working on a function which is part of a package.
This package contains a template for a new package, and a function which creates R data for the new package which has to have a dynamic name provided to this function.

At the moment I am doing the following:

```<code>makedata <- function(schemeName, data) {
  rdsFile <- paste0(schemeName, ".rds")
  varName <- paste0(schemeName)
  saveRDS(
    data,
    file = file.path( ".", "data", rdsFile )
  )
  cat(
    paste0(varName, " <- readRDS(\"./", rdsFile, "\")"),
    file = file.path( ".", "data", paste0(varName, ".R") )
  )
}

makedata(name = "test", data = letters)
</code>```

which results in two files in the data directory:

a file test.rds containing letters but which is not loaded by R when the package is loaded (rds is not supported)

a file test.R which has the code test <- readRDS("./test.rds") and which causes, when the package is loaded, the data in test.rds to be loaded in the variable test which than contains letters.

Now CRAN does not like rds files in the data directory.

Is there another way that I can use the standard formats (preferably RData) to achieve this?

答:
A possible alternative with eval parse, as discussed in the comments.

```<code>makedata <- function(schemeName, data) {
  rdaFile <- paste0(schemeName, ".rda")
  fileLocation <- file.path( ".", "data", rdaFile )
  varName <- paste0(schemeName)

  assign(varName, data)
  eval(parse(text = sprintf("save(%s, file = '%s')", varName, fileLocation)))

  cat(sprintf("%s <- load(%s, file = '%s')",
              varName, varName,
              fileLocation
              ),
      file = file.path( ".", "data", paste0(varName, ".R") ))
}
</code>```

Off topic:
Also, since you're developing packages, one convenient option might be using system.file instead of file.path due to option system.file('data/test.R', package = 'yourPackage') which allows to look in your package directory, wherever it is installed. Haven't tested your previous solution, it might be working fine too.

Body:
I am working on a function which is part of a package.
This package contains a template for a new package, and a function which creates R data for the new package which has to have a dynamic name provided to this function.

At the moment I am doing the following:

makedata <- function(schemeName, data) {
  rdsFile <- paste0(schemeName, ".rds")
  varName <- paste0(schemeName)
  saveRDS(
    data,
    file = file.path( ".", "data", rdsFile )
  )
  cat(
    paste0(varName, " <- readRDS(\"./", rdsFile, "\")"),
    file = file.path( ".", "data", paste0(varName, ".R") )
  )
}

makedata(name = "test", data = letters)

which results in two files in the data directory:

a file test.rds containing letters but which is not loaded by R when the package is loaded (rds is not supported)

a file test.R which has the code test <- readRDS("./test.rds") and which causes, when the package is loaded, the data in test.rds to be loaded in the variable test which than contains letters.

Now CRAN does not like rds files in the data directory.

Is there another way that I can use the standard formats (preferably RData) to achieve this?

Body:
A possible alternative with eval parse, as discussed in the comments.

makedata <- function(schemeName, data) {
  rdaFile <- paste0(schemeName, ".rda")
  fileLocation <- file.path( ".", "data", rdaFile )
  varName <- paste0(schemeName)

  assign(varName, data)
  eval(parse(text = sprintf("save(%s, file = '%s')", varName, fileLocation)))

  cat(sprintf("%s <- load(%s, file = '%s')",
              varName, varName,
              fileLocation
              ),
      file = file.path( ".", "data", paste0(varName, ".R") ))
}

Off topic:
Also, since you're developing packages, one convenient option might be using system.file instead of file.path due to option system.file('data/test.R', package = 'yourPackage') which allows to look in your package directory, wherever it is installed. Haven't tested your previous solution, it might be working fine too.


问:
Android Navigation Architecture Component - Get current visible fragment
Before trying the Navigation component I used to manually do fragment transactions and used the fragment tag in order to fetch the current fragment.

val fragment:MyFragment = supportFragmentManager.findFragmentByTag(tag):MyFragment

Now in my main activity layout I have something like:

```<code><fragment
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/nav_host"
        app:navGraph= "@navigation/nav_item"
        android:name="androidx.navigation.fragment.NavHostFragment"
        app:defaultNavHost= "true"
        />
</code>```

How can I retrieve the current displayed fragment by the Navigation component?
Doing

supportFragmentManager.findFragmentById(R.id.nav_host)

returns a NavHostFragment and I want to retrieve my shown 'MyFragment`.

Thank you.

答:
this might be late but for anyone who's still looking

```<code>val currentFragment = NavHostFragment.findNavController(nav_host_fragment).currentDestination?.id
</code>```

then you can do something like

```<code>if(currentFragment == R.id.myFragment){
     //do something
}
</code>```

note that this is for kotlin, java code should be almost the same

Body:
Before trying the Navigation component I used to manually do fragment transactions and used the fragment tag in order to fetch the current fragment.

val fragment:MyFragment = supportFragmentManager.findFragmentByTag(tag):MyFragment

Now in my main activity layout I have something like:

<fragment
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/nav_host"
        app:navGraph= "@navigation/nav_item"
        android:name="androidx.navigation.fragment.NavHostFragment"
        app:defaultNavHost= "true"
        />

How can I retrieve the current displayed fragment by the Navigation component?
Doing

supportFragmentManager.findFragmentById(R.id.nav_host)

returns a NavHostFragment and I want to retrieve my shown 'MyFragment`.

Thank you.

Body:
this might be late but for anyone who's still looking

val currentFragment = NavHostFragment.findNavController(nav_host_fragment).currentDestination?.id

then you can do something like

if(currentFragment == R.id.myFragment){
     //do something
}

note that this is for kotlin, java code should be almost the same


问:
Uploading photo without changing its original size does not function
```<code>$resizeObj = new resize($routePath.$imgPathLease.$photosrc);

$resizeObj->resizeImage(1024, 768, 'auto');
$resizeObj->saveImage($routePath.$imgPathLease.'detail-'.$leaseid.'-'.$uploadnum.'-'.$photosrc, 80);

$detailImg = $leaseid.'-'.$uploadnum.'-'.$photosrc;
$mcProperty->InsertLeasePhoto($db, $leaseid, $detailImg);

$resizeObj->resizeImage(300, 300, 'crop');
$resizeObj->saveImage($routePath.$imgPathLease.'thumb-'.$leaseid.'-'.$uploadnum.'-'.$photosrc, 80);
</code>```

Basically the code above functions as am upload for a larger image and a cropped our 300x300 thumbnail version of itself.

What I want is the first upload will follow through without any resizing.

My issue is that if I take out

$resizeObj->resizeImage(1024, 768, 'auto');

, the larger image does not upload. So im assuming I will just keep that line for this function to work.

Also, the photo name is what i am aiming for thats why the saveImage code exists.

Is there any code that can go like this?:

$resizeObj->resizeImage("width=100%", "width=100%", 'auto');

Thanks

答:
first check the size of photo you are uploading , and also check $_Files array to check whether there is any error in $_Files['error'].

If yes then you need to increase max_upload limit in PHP.ini file or simple by using ini_set() function in php.

And then try if your uploading is complete or not.If still there is a problem then please provide the logs for the same.

Body:
$resizeObj = new resize($routePath.$imgPathLease.$photosrc);

$resizeObj->resizeImage(1024, 768, 'auto');
$resizeObj->saveImage($routePath.$imgPathLease.'detail-'.$leaseid.'-'.$uploadnum.'-'.$photosrc, 80);

$detailImg = $leaseid.'-'.$uploadnum.'-'.$photosrc;
$mcProperty->InsertLeasePhoto($db, $leaseid, $detailImg);

$resizeObj->resizeImage(300, 300, 'crop');
$resizeObj->saveImage($routePath.$imgPathLease.'thumb-'.$leaseid.'-'.$uploadnum.'-'.$photosrc, 80);

Basically the code above functions as am upload for a larger image and a cropped our 300x300 thumbnail version of itself.

What I want is the first upload will follow through without any resizing.

My issue is that if I take out

$resizeObj->resizeImage(1024, 768, 'auto');

, the larger image does not upload. So im assuming I will just keep that line for this function to work.

Also, the photo name is what i am aiming for thats why the saveImage code exists.

Is there any code that can go like this?:

$resizeObj->resizeImage("width=100%", "width=100%", 'auto');

Thanks


问:
Append values from dataframe column to list
I have a dataframe with several columns, and I want to append to an empty list the values of one column, so that the desired output would be the following:

```<code>empty_list = [value_1,value_2,value_3...]
</code>```

I have tried the following:

```<code>df = pd.DataFrame({'country':['a','b','c','d'],
      'gdp':[1,2,3,4],
      'iso':['x','y','z','w']})
a_list = []

a_list.append(df['iso'])
a_list.append(df['iso'].values)
a_list.append(df['iso'].tolist())
</code>```

Either way, I get a list with lists, numpy arrays or series inside it, and I would like to have directly the records.

答:
To access the data of each row of the Pandas dataframe we can use DataFrame.iat attribute and then we can append the data of each row to the end of the list.
In first for loop iterate over each row and create a list to store the data of the current row
In second for loop iterate over all the columns and append the data of each column to the list  after that append the current row to the list</p>

```<code>df = pd.DataFrame({'country':['a','b','c','d'],'gdp':[1,2,3,4],'iso':['x','y','z','w']})
a_list = []
for i in range((df.shape[0])):
cur_row =[]
for j in range(df.shape[1]):
    cur_row.append(df.iat[i, j])
a_list.append(cur_row)
</code>```

Body:
I have a dataframe with several columns, and I want to append to an empty list the values of one column, so that the desired output would be the following:

empty_list = [value_1,value_2,value_3...]

I have tried the following:

df = pd.DataFrame({'country':['a','b','c','d'],
      'gdp':[1,2,3,4],
      'iso':['x','y','z','w']})
a_list = []

a_list.append(df['iso'])
a_list.append(df['iso'].values)
a_list.append(df['iso'].tolist())

Either way, I get a list with lists, numpy arrays or series inside it, and I would like to have directly the records.

Body:
To access the data of each row of the Pandas dataframe we can use DataFrame.iat attribute and then we can append the data of each row to the end of the list.
In first for loop iterate over each row and create a list to store the data of the current row
In second for loop iterate over all the columns and append the data of each column to the list  after that append the current row to the list

df = pd.DataFrame({'country':['a','b','c','d'],'gdp':[1,2,3,4],'iso':['x','y','z','w']})
a_list = []
for i in range((df.shape[0])):
cur_row =[]
for j in range(df.shape[1]):
    cur_row.append(df.iat[i, j])
a_list.append(cur_row)


问:
Query to subtract same column value at different interval of day with SQL database
In MySQL, I want to subtract one of column value at different interval of time based on another column 'timestamp'.

```<code>table structure is :
id | generator_id | timestamp             | generated_value
1  |  1           | 2019-05-27 06:55:20   | 123456
2  |  1           | 2019-05-27 07:55:20   | 234566
3  |  1           | 2019-05-27 08:55:20   | 333456
..
..
20  |  1           | 2019-05-27 19:55:20   | 9876908

</code>```

From above table I want to fetch the generated_value column value which should be difference of first timestamp fo day and timestamp of last value of day.

In above example I am looking query which should give me output as 9,753,452 (9876908 - 123456).

In general to fetch the single record of first value and last value of day I use below query

```<code>// Below will give me end day value
SELECT * FROM generator_meters where generator_id=1 and timestamp like '2019-05-27%' order by timestamp desc limit 1 ;

//this will give me last day value
SELECT * FROM generator_meters where generator_id=1 and timestamp like '2019-05-27%' order by timestamp  limit 1 ;

</code>```

Question is how should I get the final generated_value by doing minus of first value of day from last value of day.

```<code>Expected Output
 generator_id | generated_value
  1           | 9753452
</code>```

Thanks in advance !!

答:
In your example the value gets bigger and bigger. If this is guaranteed to be so, you can use

```<code>select max(generated_value) - min(generated_value) as result
from sun_electric.generator_meters
where generator_id = 1
and date(timestamp) = date '2019-05-27';
</code>```

Or for multiple IDs:

```<code>select generator_id, max(generated_value) - min(generated_value) as result
from sun_electric.generator_meters
and date(timestamp) = date '2019-05-27'
group by generator_id
order by generator_id;
</code>```

If the value is not ascending, then you can use the following query for ID 1:

```<code>select last_row.generated_value - first_row.generated_value as result
from
(
  select *
  from sun_electric.generator_meters
  where generator_id = 1
  and date(timestamp) = date '2019-05-27'
  order by timestamp
  limit 1
) first_row
cross join
(
  select *
  from sun_electric.generator_meters
  where generator_id = 1
  and date(timestamp) = date '2019-05-27'
  order by timestamp desc
  limit 1
) last_row;
</code>```

Here is one way to get a result for multiple IDs:

```<code>select
  minmax.generator_id,
  (
    select generated_value
    from sun_electric.generator_meters gm
    where gm.generator_id = minmax.generator_id
    and gm.timestamp = minmax.max_ts
  ) -
  (
    select generated_value
    from sun_electric.generator_meters gm
    where gm.generator_id = minmax.generator_id
    and gm.timestamp = minmax.min_ts
  ) as result
from
(
  select generator_id, min(timestamp) as min_ts, max(timestamp) as max_ts
  from sun_electric.generator_meters
  where date(timestamp) = date '2019-05-27'
  group by generator_id
) minmax
order by minmax.generator_id;
</code>```

You can also move the subqueries to the from clause and join them, if you like this better. Yet another approach would be to use window functions, available as of MySQL 8.

Body:
In MySQL, I want to subtract one of column value at different interval of time based on another column 'timestamp'.

table structure is :
id | generator_id | timestamp             | generated_value
1  |  1           | 2019-05-27 06:55:20   | 123456
2  |  1           | 2019-05-27 07:55:20   | 234566
3  |  1           | 2019-05-27 08:55:20   | 333456
..
..
20  |  1           | 2019-05-27 19:55:20   | 9876908

From above table I want to fetch the generated_value column value which should be difference of first timestamp fo day and timestamp of last value of day.

In above example I am looking query which should give me output as 9,753,452 (9876908 - 123456).

In general to fetch the single record of first value and last value of day I use below query

// Below will give me end day value
SELECT * FROM generator_meters where generator_id=1 and timestamp like '2019-05-27%' order by timestamp desc limit 1 ;

//this will give me last day value
SELECT * FROM generator_meters where generator_id=1 and timestamp like '2019-05-27%' order by timestamp  limit 1 ;

Question is how should I get the final generated_value by doing minus of first value of day from last value of day.

Expected Output
 generator_id | generated_value
  1           | 9753452

Thanks in advance !!

Body:
In your example the value gets bigger and bigger. If this is guaranteed to be so, you can use

select max(generated_value) - min(generated_value) as result
from sun_electric.generator_meters
where generator_id = 1
and date(timestamp) = date '2019-05-27';

Or for multiple IDs:

select generator_id, max(generated_value) - min(generated_value) as result
from sun_electric.generator_meters
and date(timestamp) = date '2019-05-27'
group by generator_id
order by generator_id;

If the value is not ascending, then you can use the following query for ID 1:

select last_row.generated_value - first_row.generated_value as result
from
(
  select *
  from sun_electric.generator_meters
  where generator_id = 1
  and date(timestamp) = date '2019-05-27'
  order by timestamp
  limit 1
) first_row
cross join
(
  select *
  from sun_electric.generator_meters
  where generator_id = 1
  and date(timestamp) = date '2019-05-27'
  order by timestamp desc
  limit 1
) last_row;

Here is one way to get a result for multiple IDs:

select
  minmax.generator_id,
  (
    select generated_value
    from sun_electric.generator_meters gm
    where gm.generator_id = minmax.generator_id
    and gm.timestamp = minmax.max_ts
  ) -
  (
    select generated_value
    from sun_electric.generator_meters gm
    where gm.generator_id = minmax.generator_id
    and gm.timestamp = minmax.min_ts
  ) as result
from
(
  select generator_id, min(timestamp) as min_ts, max(timestamp) as max_ts
  from sun_electric.generator_meters
  where date(timestamp) = date '2019-05-27'
  group by generator_id
) minmax
order by minmax.generator_id;

You can also move the subqueries to the from clause and join them, if you like this better. Yet another approach would be to use window functions, available as of MySQL 8.


问:
Open a portrait page from Pivot Page Listbox with "LineThree" text in it
As the title says...
If I start my app project with a pivot page(MainPage.xaml) and then choose to click for example the "design two" link in the databinded listbox. Is it possible to bind the "LineThree" text for the "design two" link in to a separate portrait page?

Do I have to make new portrait page for every "LineThree"-link? Or can I just generate the "MainViewModelSampleData.xaml" data to a single portrait page depending on what "LineOne"-link I click in the pivot page in the start?

Hope my question is understandable... :P

答:
How is what you're trying to do different from what is created by default in a new DataBound Application? That lets you select an item in the list on the main page and then displays another page which includes the text from LineThree.

I suggest you look at the sample code created as part of a new DataBound Application.