问:
Integrate Wordpress into node.js application
I had a client, who required a real-time video chatting website. I've successfully completed the job using node.js. Now, the client is asking to install WordPress so he can, add or remove plugins (like SEO, visit counter) on his own, and I don't know how to do it.

So, how can install Wordpress in my site, so when the client visits example.com the chatting application loads, and when client visits example.com/login Wordpress Admin Dashboard is loaded.

答: It is quite simple. You have a node application and when it routes to example.com/login that is where your wordpress application is placed (you have developed it locally or online so just copy those files to that route, it will load the index. You will need to have wordpress dependencies installed, or install them from the browser. It is important to remember you are essentially installing two sites under the same url prefix though.</p>


来源: stackexchange

问:
Default zoom Mapbox when used in Power BI
Does anyone know how to set a default point when zooming out using the MapBox app in Power BI? Currently, when I deselect the location in a slicer connected to the map, it will zoom out to the very middle of the world map. I would like set a custom marker to zoom out to if possible.</p>

答:
At the moment, there is no out of the box feature within the Mapbox visual for Power BI that prevents you from zooming past a certain point, as the default zoom level is set to include all of your data. For instance, if I create a report with a choropleth map of US states, when using the slicer, the map will zoom into the state I select. When I deselect the state, the map will zoom back out to show all of the states.

If you have data spanning multiple regions (or if the data is only visible at higher zoom levels), when you deselect the location in the slicer, the map will zoom out to incorporate all data. While the Mapbox visual is currently available as is, please stay tuned for updates.

ContentLicense: CC BY-SA 4.0


问:
Multiple fields with the same name in AJAX and PHP
Everyone.

I got some good help a couple of days ago, so I'm hoping that someone can show me where I'm going wrong here.  Basically, what I'm trying to do is update a MySQL database in the background when a user clicks a button.  The form is a series of records, and the records have common field names (ID, DSA_Number, Manager_Review, etc.)  Right now, the code doesn't even seem to return success or failure messages.

Here's the script on the main page:

```<code><script>
                $(document).ready(function(){

                    $("#button").click(function(){

                        var DDD_Number=$("#DDD_Number").val();
                        var Manager_Review=$("#Manager_Review").val();
                        var RID=$("#RID").val();
                        var Services=$("Services").val();
                        var Dues_List=$("Dues_List").val();
                        var ID=$("ID").val();
                        var myrid=$("myrid").val();
                        var Manager_Comments=$("Manager_Comments").val();
                        var President_Comments=$("President_Comments").val();
                        var dataTosend='?DDD_Number='+DDD_Number+'&Manager_Review='+Manager_Review+'&RID='+RID+'&Services='+Services+'&Dues_List='+Dues_List+'&Manager_Comments='+Manager_Comments+'&President_Comments='+President_Comments;
                        $.ajax({
                            type: "GET",
                            url:'baseupdater-test.php' + dataTosend,
                            data:dataTosend,
                            async: true,
                          success:function(data){
                                document.getElementById('stuffhere').innerHTML.text = "Success.";
                                document.getElementById('stuffhere').innerHTML.text = data;
                            },
                            error: function(data){
                               document.getElementById('stuffhere').innerHTML.text = "Failure.";
                           }
                        });
                    });
        </script>
</code>```

Here's the code that draws the rows on the table:

```<code><?php

/*  This code writes the rows in the table for baserecord.php */

$n = 0;
$o = $n + 1;

$firstday = date('m/1/Y');
if(isset($_GET['MR']))  // If $_GET['MR'] is set ...
{
    $MR = $_GET['MR'];  // Set the variables.
    $PR = $Pres_Rev;
}
else  // If not, select the maximum (latest) Manager Review Date.
{
    $getmr = "select max(STR_TO_DATE(Manager_Review_Date, '%m/%d/%Y')) as Manager_Review_Date,
    President_Review_Date from clientdb.MRS2_test
    inner join clients_MRS
    on clientdb.clients_MRS.DDD_Case = clientdb.MRS2_test.DDD_Number
    where SCID = '$ID';";

    $rs2 = mysqli_query($con,$getmr);
    $rvd = mysqli_fetch_assoc($rs2);
    $MR = date('m/d/Y', strtotime($rvd['Manager_Review_Date']));
    echo "MR: $MR<br>";
    $PR = date('m/d/Y', strtotime($rvd['President_Review_Date']));
}

// The following query select the data for the row and orders it by the latest Manager Review Date.

$cliselect    = "select distinct clientdb.Plans.Client_ID, clientdb.clients_MRS.DSA_Status, clientdb.clients_MRS.DSA_Status_Date, clientdb.clients_MRS.First_Name, clients_MRS.Last_Name, clientdb.clients_MRS.County, clientdb.Plans.DDD_Case, RID, Plans.Program, max(Plans.Plan) as MPlan, Tier, Plan_End_Date, clientdb.MRS2_test.RID, clientdb.MRS2_test.President_Comments, clientdb.MRS2_test.Manager_Comments, clientdb.MRS2_test.Services_Issues, clientdb.MRS2_test.Dues_List
     from clientdb.Plans
     inner join clientdb.clients_MRS on clientdb.clients_MRS.DDD_Case = clientdb.Plans.DDD_Case
     inner join clientdb.MRS2_test on clientdb.MRS2_test.DDD_Number = clientdb.Plans.DDD_Case
     where SCID = '$ID' and (DSA_Status = 'Active' OR (DSA_Status <> 'Active' AND STR_TO_DATE(DSA_Status_Date, '%d/%m/%Y') > STR_TO_DATE($firstday, '%m/%d/%Y'))) AND (Manager_Review_Date = '$MR')
     group by clientdb.Plans.DDD_Case order by STR_TO_DATE(clientdb.MRS2_test.Manager_Review_Date, '%m/%d/%Y') DESC, clientdb.Plans.Last_Name;";

     //echo "cliselect $cliselect<br>";

    $cres         = mysqli_query($con, $cliselect);

while ($dddr = mysqli_fetch_assoc($cres)) {
    $DDD_Case              = $dddr['DDD_Case'];
    $First_Name            = $dddr['First_Name'];
    $Last_Name             = $dddr['Last_Name'];
    $County                = $dddr['County'];
    $Tier                  = $dddr['Tier'];
    if($ddr['Plan_End_Date'] <> '')
        {
            $Plan_End_Date         = $dddr['Plan_End_Date'];
        }

    $Pres_Comments         = $dddr['President_Comments'];
    $Mgr_Comments          = $dddr['Manager_Comments'];
    $Dues                  = $dddr['Dues_List'];
    $Services              = $dddr['Services_Issues'];
    $RID = $dddr['RID'];

    $mxselect              = "select max(Plan) as MPlan from clientdb.Plans where clientdb.Plans.DDD_Case = '$DDD_Case';";
    $rens                  = mysqli_query($con, $mxselect);
    $rmm                   = mysqli_fetch_assoc($rens);
    $MPlan                 = $rmm['MPlan'];
    $endsel                = "select Plan_End_Date, Program from clientdb.Plans where clientdb.Plans.DDD_Case = $DDD_Case and clientdb.Plans.Plan = $MPlan;";
    $rsel                  = mysqli_query($con, $endsel);
    $end                   = mysqli_fetch_assoc($rsel);
    $Plan_End_Date         = $end['Plan_End_Date'];
    $Program               = $end['Program'];
//The purpose of ths quer s to get the RID for each row.

    $mrselect = "select * from MRS2_test where DDD_Number = '$DDD_Case' and Manager_Review_Date = '$MR'
                group by DDD_Number, RID
                order by RID DESC
                Limit 1 ;";

    $run = mysqli_query($con,$mrselect);

    $mrss = mysqli_fetch_assoc($run);

    $Manager_Review_Date   = $mrss['Manager_Review_Date'];
    $President_Review_Date = $mrss['President_Review_Date'];
    $myRID = $mrss['RID'][$n];

    echo "<tr><td>$o</td><td sorttable_customkey='$DDD_Case'><input class='ddd' type = 'text' value = '$DDD_Case' name = 'DDD_Number[]' size='6'></td><td sorttable_customkey='$Last_Name'>$First_Name $Last_Name</td><td>$County</td><td>$Program</td><td>$Tier</td><td sorttable_customkey='";
    ?>
<?php echo strtotime($Plan_End_Date);

echo "'>$Plan_End_Date</td><td><textarea class='expnd' name='Services[]'>$Services</textarea></td><td><input name='Dues_List[]'' type = 'text' value = '$Dues'></td><td><textarea class='expnd' name='Manager_Comments[]'>$Mgr_Comments</textarea></td><td><textarea class='expnd' name='President_Comments[]'>$Pres_Comments</textarea></td><td><input type='text' size='4' name = 'myrid[]' value='$RID' readonly></td><input type='hidden' name = 'manreview-orig' value='$Manager_Review_Date'></tr>";

    $n = $n++;
    $o++;
}
?>
</code>```

And finally, this is the code that does the update:

```<code><?php

include 'config.php';

$con = mysqli_connect($DB_server, $DB_user, $DB_password, $DB_database);

$Manager_Review   = $_GET['Manager_Review'];
$Old_MR = $_GET['manreview-orig'];
//echo "OLD MR: $Old_MR<br>";

if($_GET['President_Review'] == '12/31/1969')
{
    $President_Review = '';
}

if($_GET['President_Review'] <> '')
{
    $President_Review = $_GET['President_Review'];
}
else
{
    $President_Review = '';
}

$ID               = $_GET['ID'];
$Services = $_GET['Services'];

echo "New Content!<br>";

$n = 0;

while ($n <= sizeof($_GET)) {

    $ridselect = "select clientdb.MRS2_test.RID, clientdb.clients_MRS.DDD_Case, clientdb.clients_MRS.SCID from clientdb.MRS2_test
            inner join clientdb.clients_MRS
            on clientdb.clients_MRS.DDD_Case = clientdb.MRS2_test.DDD_Number
            where Manager_Review_Date = '$Old_MR' and clientdb.clients_MRS.DDD_Case = clientdb.MRS2_test.DDD_Number
            order by RID;";
    $rsc       = mysqli_query($con, $ridselect);
    $rowrid    = mysqli_fetch_assoc($rsc);
    $RID       = $_GET['myrid'][$n];
  //  echo "RID: $RID<br>";
    $MDD = $_GET['RID'];
    $myrid = $_GET['myrid'][$n];
    $DDD_Case = $_GET['DDD_Number'][$n];

    $Period             = ltrim(substr($Manager_Review,0,2), "0");

    $Services           = mysqli_real_escape_string($con, $_GET['Services'][$n]);
    $Manager_Comments   = mysqli_real_escape_string($con, $_GET['Manager_Comments'][$n]);
    $President_Comments = mysqli_real_escape_string($con, $_GET['President_Comments'][$n]);
    $Dues_List          = mysqli_real_escape_string($con, $_GET['Dues_List'][$n]);
    $DDD_Case           = $_GET['DDD_Number'][$n];

    $updater = "update clientdb.MRS2_test set clientdb.MRS2_test.Services_Issues = '$Services',
    clientdb.MRS2_test.Manager_Comments = '$Manager_Comments', clientdb.MRS2_test.President_Comments = '$President_Comments',
    clientdb.MRS2_test.Dues_List = '$Dues_List', Period = '$Period' where DDD_Number = '$DDD_Case' and RID = '$RID';";
echo $updater . "<br>";

        $date_updater = "update clientdb.MRS2_test set clientdb.MRS2_test.Manager_Review_Date = '$Manager_Review',
    clientdb.MRS2_test.President_Review_Date = '$President_Review' where RID = '$RID';";
    echo "dateupdater: $date_updater<br>";
    if(!mysqli_query($con, $date_updater))
        {
          echo "That failed miserably.<br>";
        }
        else
            {
                $rws = mysqli_affected_rows($con);
                echo "affected rows: $rws<br>";
                echo "Success.<br>";
            }

    mysqli_query($con, $updater);

    $datestamp = date('Y-m-d h:i:s');

    $upstamp = "update clientdb.MRS2_test set Update_Time = '$datestamp' where DDD_Case = '$DDD_Case' and RID = '$RID';";
    mysqli_query($con,$upstamp);

    $n++;
}

echo "<script language='Javascript'>document.getElementById('stuffhere').InnerHTML = '<?php echo $updater; ?>';</script>";

?>
</code>```

I've tried serializing the form, and I haven't had any success there.  Any suggestions would be greatly welcome.  Sorry for the long post, but I'm just not sure where the error is at this point.

答:
Your code

```<code>var data= [DDD_Number,Manager_Review,RID,Services,Dues_List,ID,myrid,Manager_Comments,President_Comments];
var datatosend = JSON.stringify(data);
$.ajax({
type: "GET",
url:'baseupdater-test.php',
data:dataTosend,
async: true,
success:function(data){
document.getElementById('stuffhere').innerHTML.text = "Success.";
document.getElementById('stuffhere').innerHTML.text = data;
 },
error: function(data){
document.getElementById('stuffhere').innerHTML.text = "Failure.";
 }
});
</code>```

As i can see you are trying to send the data twice, first through url and second with the ajax data method please fix that i think its a wrong approach to do that you should send it only once.

And moreover you must convert the data into json format to make the ajax request work
and now what's happening is as your data is not in the correct format your code must be stuck at the data in ajax you can see it in console the ajax request would not show you any value passing to another and that is the main reason the Success or Failure are not being show.

Body:
Everyone.

I got some good help a couple of days ago, so I'm hoping that someone can show me where I'm going wrong here.  Basically, what I'm trying to do is update a MySQL database in the background when a user clicks a button.  The form is a series of records, and the records have common field names (ID, DSA_Number, Manager_Review, etc.)  Right now, the code doesn't even seem to return success or failure messages.

Here's the script on the main page:

Here's the code that draws the rows on the table:

<?php

/*  This code writes the rows in the table for baserecord.php */

$n = 0;
$o = $n + 1;

$firstday = date('m/1/Y');
if(isset($_GET['MR']))  // If $_GET['MR'] is set ...
{
    $MR = $_GET['MR'];  // Set the variables.
    $PR = $Pres_Rev;
}
else  // If not, select the maximum (latest) Manager Review Date.
{
    $getmr = "select max(STR_TO_DATE(Manager_Review_Date, '%m/%d/%Y')) as Manager_Review_Date,
    President_Review_Date from clientdb.MRS2_test
    inner join clients_MRS
    on clientdb.clients_MRS.DDD_Case = clientdb.MRS2_test.DDD_Number
    where SCID = '$ID';";

    $rs2 = mysqli_query($con,$getmr);
    $rvd = mysqli_fetch_assoc($rs2);
    $MR = date('m/d/Y', strtotime($rvd['Manager_Review_Date']));
    echo "MR: $MR
";
    $PR = date('m/d/Y', strtotime($rvd['President_Review_Date']));
}

// The following query select the data for the row and orders it by the latest Manager Review Date.

$cliselect    = "select distinct clientdb.Plans.Client_ID, clientdb.clients_MRS.DSA_Status, clientdb.clients_MRS.DSA_Status_Date, clientdb.clients_MRS.First_Name, clients_MRS.Last_Name, clientdb.clients_MRS.County, clientdb.Plans.DDD_Case, RID, Plans.Program, max(Plans.Plan) as MPlan, Tier, Plan_End_Date, clientdb.MRS2_test.RID, clientdb.MRS2_test.President_Comments, clientdb.MRS2_test.Manager_Comments, clientdb.MRS2_test.Services_Issues, clientdb.MRS2_test.Dues_List
     from clientdb.Plans
     inner join clientdb.clients_MRS on clientdb.clients_MRS.DDD_Case = clientdb.Plans.DDD_Case
     inner join clientdb.MRS2_test on clientdb.MRS2_test.DDD_Number = clientdb.Plans.DDD_Case
     where SCID = '$ID' and (DSA_Status = 'Active' OR (DSA_Status <> 'Active' AND STR_TO_DATE(DSA_Status_Date, '%d/%m/%Y') > STR_TO_DATE($firstday, '%m/%d/%Y'))) AND (Manager_Review_Date = '$MR')
     group by clientdb.Plans.DDD_Case order by STR_TO_DATE(clientdb.MRS2_test.Manager_Review_Date, '%m/%d/%Y') DESC, clientdb.Plans.Last_Name;";

     //echo "cliselect $cliselect
";

    $cres         = mysqli_query($con, $cliselect);

while ($dddr = mysqli_fetch_assoc($cres)) {
    $DDD_Case              = $dddr['DDD_Case'];
    $First_Name            = $dddr['First_Name'];
    $Last_Name             = $dddr['Last_Name'];
    $County                = $dddr['County'];
    $Tier                  = $dddr['Tier'];
    if($ddr['Plan_End_Date'] <> '')
        {
            $Plan_End_Date         = $dddr['Plan_End_Date'];
        }

    $Pres_Comments         = $dddr['President_Comments'];
    $Mgr_Comments          = $dddr['Manager_Comments'];
    $Dues                  = $dddr['Dues_List'];
    $Services              = $dddr['Services_Issues'];
    $RID = $dddr['RID'];

    $mxselect              = "select max(Plan) as MPlan from clientdb.Plans where clientdb.Plans.DDD_Case = '$DDD_Case';";
    $rens                  = mysqli_query($con, $mxselect);
    $rmm                   = mysqli_fetch_assoc($rens);
    $MPlan                 = $rmm['MPlan'];
    $endsel                = "select Plan_End_Date, Program from clientdb.Plans where clientdb.Plans.DDD_Case = $DDD_Case and clientdb.Plans.Plan = $MPlan;";
    $rsel                  = mysqli_query($con, $endsel);
    $end                   = mysqli_fetch_assoc($rsel);
    $Plan_End_Date         = $end['Plan_End_Date'];
    $Program               = $end['Program'];
//The purpose of ths quer s to get the RID for each row.

    $mrselect = "select * from MRS2_test where DDD_Number = '$DDD_Case' and Manager_Review_Date = '$MR'
                group by DDD_Number, RID
                order by RID DESC
                Limit 1 ;";

    $run = mysqli_query($con,$mrselect);

    $mrss = mysqli_fetch_assoc($run);

    $Manager_Review_Date   = $mrss['Manager_Review_Date'];
    $President_Review_Date = $mrss['President_Review_Date'];
    $myRID = $mrss['RID'][$n];

    echo "
$o	<input class='ddd' type = 'text' value = '$DDD_Case' name = 'DDD_Number[]' size='6'>	$First_Name $Last_Name	$County	$Program	$Tier
<?php echo strtotime($Plan_End_Date);

echo "'>$Plan_End_Date	<textarea class='expnd' name='Services[]'>$Services</textarea>	<input name='Dues_List[]'' type = 'text' value = '$Dues'>	<textarea class='expnd' name='Manager_Comments[]'>$Mgr_Comments</textarea>	<textarea class='expnd' name='President_Comments[]'>$Pres_Comments</textarea>	<input type='text' size='4' name = 'myrid[]' value='$RID' readonly>	<input type='hidden' name = 'manreview-orig' value='$Manager_Review_Date'>
";

    $n = $n++;
    $o++;
}
?>

And finally, this is the code that does the update:

<?php

include 'config.php';

$con = mysqli_connect($DB_server, $DB_user, $DB_password, $DB_database);

$Manager_Review   = $_GET['Manager_Review'];
$Old_MR = $_GET['manreview-orig'];
//echo "OLD MR: $Old_MR
";

if($_GET['President_Review'] == '12/31/1969')
{
    $President_Review = '';
}

if($_GET['President_Review'] <> '')
{
    $President_Review = $_GET['President_Review'];
}
else
{
    $President_Review = '';
}

$ID               = $_GET['ID'];
$Services = $_GET['Services'];

echo "New Content!
";

$n = 0;

while ($n <= sizeof($_GET)) {

    $ridselect = "select clientdb.MRS2_test.RID, clientdb.clients_MRS.DDD_Case, clientdb.clients_MRS.SCID from clientdb.MRS2_test
            inner join clientdb.clients_MRS
            on clientdb.clients_MRS.DDD_Case = clientdb.MRS2_test.DDD_Number
            where Manager_Review_Date = '$Old_MR' and clientdb.clients_MRS.DDD_Case = clientdb.MRS2_test.DDD_Number
            order by RID;";
    $rsc       = mysqli_query($con, $ridselect);
    $rowrid    = mysqli_fetch_assoc($rsc);
    $RID       = $_GET['myrid'][$n];
  //  echo "RID: $RID
";
    $MDD = $_GET['RID'];
    $myrid = $_GET['myrid'][$n];
    $DDD_Case = $_GET['DDD_Number'][$n];

    $Period             = ltrim(substr($Manager_Review,0,2), "0");

    $Services           = mysqli_real_escape_string($con, $_GET['Services'][$n]);
    $Manager_Comments   = mysqli_real_escape_string($con, $_GET['Manager_Comments'][$n]);
    $President_Comments = mysqli_real_escape_string($con, $_GET['President_Comments'][$n]);
    $Dues_List          = mysqli_real_escape_string($con, $_GET['Dues_List'][$n]);
    $DDD_Case           = $_GET['DDD_Number'][$n];

    $updater = "update clientdb.MRS2_test set clientdb.MRS2_test.Services_Issues = '$Services',
    clientdb.MRS2_test.Manager_Comments = '$Manager_Comments', clientdb.MRS2_test.President_Comments = '$President_Comments',
    clientdb.MRS2_test.Dues_List = '$Dues_List', Period = '$Period' where DDD_Number = '$DDD_Case' and RID = '$RID';";
echo $updater . "
";

        $date_updater = "update clientdb.MRS2_test set clientdb.MRS2_test.Manager_Review_Date = '$Manager_Review',
    clientdb.MRS2_test.President_Review_Date = '$President_Review' where RID = '$RID';";
    echo "dateupdater: $date_updater
";
    if(!mysqli_query($con, $date_updater))
        {
          echo "That failed miserably.
";
        }
        else
            {
                $rws = mysqli_affected_rows($con);
                echo "affected rows: $rws
";
                echo "Success.
";
            }

    mysqli_query($con, $updater);

    $datestamp = date('Y-m-d h:i:s');

    $upstamp = "update clientdb.MRS2_test set Update_Time = '$datestamp' where DDD_Case = '$DDD_Case' and RID = '$RID';";
    mysqli_query($con,$upstamp);

    $n++;
}

echo "";

?>

I've tried serializing the form, and I haven't had any success there.  Any suggestions would be greatly welcome.  Sorry for the long post, but I'm just not sure where the error is at this point.

Body:
Your code

var data= [DDD_Number,Manager_Review,RID,Services,Dues_List,ID,myrid,Manager_Comments,President_Comments];
var datatosend = JSON.stringify(data);
$.ajax({
type: "GET",
url:'baseupdater-test.php',
data:dataTosend,
async: true,
success:function(data){
document.getElementById('stuffhere').innerHTML.text = "Success.";
document.getElementById('stuffhere').innerHTML.text = data;
 },
error: function(data){
document.getElementById('stuffhere').innerHTML.text = "Failure.";
 }
});

As i can see you are trying to send the data twice, first through url and second with the ajax data method please fix that i think its a wrong approach to do that you should send it only once.

And moreover you must convert the data into json format to make the ajax request work
and now what's happening is as your data is not in the correct format your code must be stuck at the data in ajax you can see it in console the ajax request would not show you any value passing to another and that is the main reason the Success or Failure are not being show.


问:
Filter data for last 24 hours using c#?
Here i am calculating the server restart count.

i need the server restart count for last 24 hours.

```<code>string logType = "System";
EventLog ev = new EventLog(logType, System.Environment.MachineName);
int count=0;
for (int i = ev.Entries.Count - 1; i >= 0; i--)
{
EventLogEntry CurrentEntry = ev.Entries[i];
if (CurrentEntry.Source.ToUpper() == "USER32")
{
count = count + 1;
}
}
ev.Close();
</code>```

and i have tried like

```<code>DateTime dt = DateTime.Now;
TimeSpan ts = dt.Subtract(CurrentEntry.TimeGenerated);
int hours = (ts.Days * 24) + ts.Hours;
</code>```

Any suggestion?

答:
```<code>var ev = new EventLog("system", System.Environment.MachineName);
var count = ev.Entries.Cast<EventLogEntry>()
    .Where (e => e.TimeGenerated >= DateTime.Now.AddDays(-1)
        && e.Source.Equals("USER32", StringComparison.CurrentCultureIgnoreCase)).Count();
</code>```

Edit:

Considering jCoder's comment about the enteries being sorted on TimeGenerated. Using this code will gain performance:

```<code>var ev = new EventLog("system", System.Environment.MachineName);
int count = 0;
var y = DateTime.Now.AddDays(-1);
for (int i = ev.Entries.Count - 1; i >= 0 ; i--)
{
    if(ev.Entries[i].TimeGenerated < y)
        break;
    if(ev.Entries[i].Source.Equals("USER32", StringComparison.CurrentCultureIgnoreCase))
        count++;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Filter data for last 24 hours using c#?

Body:
Here i am calculating the server restart count.

i need the server restart count for last 24 hours.

string logType = "System";
EventLog ev = new EventLog(logType, System.Environment.MachineName);
int count=0;
for (int i = ev.Entries.Count - 1; i >= 0; i--)
{
EventLogEntry CurrentEntry = ev.Entries[i];
if (CurrentEntry.Source.ToUpper() == "USER32")
{
count = count + 1;
}
}
ev.Close();

and i have tried like

DateTime dt = DateTime.Now;
TimeSpan ts = dt.Subtract(CurrentEntry.TimeGenerated);
int hours = (ts.Days * 24) + ts.Hours;

Any suggestion?

Body:
var ev = new EventLog("system", System.Environment.MachineName);
var count = ev.Entries.Cast<EventLogEntry>()
    .Where (e => e.TimeGenerated >= DateTime.Now.AddDays(-1)
        && e.Source.Equals("USER32", StringComparison.CurrentCultureIgnoreCase)).Count();

Edit:

Considering jCoder's comment about the enteries being sorted on TimeGenerated. Using this code will gain performance:

var ev = new EventLog("system", System.Environment.MachineName);
int count = 0;
var y = DateTime.Now.AddDays(-1);
for (int i = ev.Entries.Count - 1; i >= 0 ; i--)
{
    if(ev.Entries[i].TimeGenerated < y)
        break;
    if(ev.Entries[i].Source.Equals("USER32", StringComparison.CurrentCultureIgnoreCase))
        count++;
}


问:
C# code to inject 64bit dll to process
I have a code to inject 32bit library(C++) to foreign 32bit process:

```<code>[DllImport("kernel32")]
        public static extern IntPtr CreateRemoteThread(
          IntPtr hProcess,
          IntPtr lpThreadAttributes,
          uint dwStackSize,
          UIntPtr lpStartAddress, // raw Pointer into remote process
          IntPtr lpParameter,
          uint dwCreationFlags,
          out IntPtr lpThreadId
        );

        ...

        public static bool InjectDLL(Process p, string dll)
        {
            IntPtr bytesout;
            Int32 LenWrite = dll.Length + 1;
            IntPtr AllocMem = (IntPtr)VirtualAllocEx(p.Handle, (IntPtr)null, (uint)LenWrite, 0x1000, 0x40);
            WriteProcessMemory(p.Handle, AllocMem, dll, (UIntPtr)LenWrite, out bytesout);
            UIntPtr Injector = (UIntPtr)GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA");
            IntPtr hThread = (IntPtr)CreateRemoteThread(p.Handle, (IntPtr)null, 0, Injector, AllocMem, 0, out bytesout);
            return true;
        }
</code>```

But how to fix that code to inject 64 bit libraries to 64bit processes? Code above doesn't work to 64bit processes and dlls.

Thanks!

答:
Your injector, your target process and the DLL must all be x64.

The reason is because of this line:

```<code>GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA");
</code>```

That will return the address of the x86 LoadLibrary() not the x64 address.

Title: C# code to inject 64bit dll to process

Body:
I have a code to inject 32bit library(C++) to foreign 32bit process:

[DllImport("kernel32")]
        public static extern IntPtr CreateRemoteThread(
          IntPtr hProcess,
          IntPtr lpThreadAttributes,
          uint dwStackSize,
          UIntPtr lpStartAddress, // raw Pointer into remote process
          IntPtr lpParameter,
          uint dwCreationFlags,
          out IntPtr lpThreadId
        );

        ...

        public static bool InjectDLL(Process p, string dll)
        {
            IntPtr bytesout;
            Int32 LenWrite = dll.Length + 1;
            IntPtr AllocMem = (IntPtr)VirtualAllocEx(p.Handle, (IntPtr)null, (uint)LenWrite, 0x1000, 0x40);
            WriteProcessMemory(p.Handle, AllocMem, dll, (UIntPtr)LenWrite, out bytesout);
            UIntPtr Injector = (UIntPtr)GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA");
            IntPtr hThread = (IntPtr)CreateRemoteThread(p.Handle, (IntPtr)null, 0, Injector, AllocMem, 0, out bytesout);
            return true;
        }

But how to fix that code to inject 64 bit libraries to 64bit processes? Code above doesn't work to 64bit processes and dlls.

Thanks!

Body:
Your injector, your target process and the DLL must all be x64.

The reason is because of this line:

GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA");

That will return the address of the x86 LoadLibrary() not the x64 address.


问:
Delete values in line based on column index using shell script
I want to be able to delete the values to the RIGHT(starting from given column index) from the test.txt at the given column index based on a given length, N.

Column index refers to the position when you open the file in the VIM editor in LINUX.

If my test.txt contains 1234 5678, and I call my delete_var function which takes in the column number as 2 to start deleting from and length N as 2 to delete as input, the test.txt would reflect 14 5678 as it deleted the values from column 2 to column 4 as the length to delete was 2.

I have the following code as of now but I am unable to understand what I would put in the sed command.

```<code>delete_var() {

    sed -i -r 's/not sure what goes here' test.txt
}

clmn_index= $1
_N=$2

delete_var "$clmn_index" "$_N"   # call the method with the column index and length to delete
</code>```

```<code>#sample test.txt (before call to fn)
1234 5678
</code>```

```<code>#sample test.txt (after call to fn)
14 5678
</code>```

Can someone guide me?

答:
One idea using cut, keeping in mind that storing the results back into the original file will require an intermediate file (eg, tmp.txt) ...

Assume our variables:

```<code>$ s=2          # start position
$ n=2          # length of string to remove
$ x=$((s-1))   # last column to keep before the deleted characters (1 in this case)
$ y=$((s+n))   # start of first column to keep after the deleted characters (4 in this case)
</code>```

At this point we can use cut -c to designate the columns to keep:

```<code>$ echo '1234 5678' > test.txt

$ set -x              # display the cut command with variables expanded
$ cut -c1-${x},${y}- test.txt
+ cut -c1-1,4- test.txt
14 5678
</code>```

Where:

1-${x} - keep range of characters from position 1 to position $(x) (1-1 in this case)

${y}- - keep range of characters from position ${y} to end of line (4-EOL in this case)

NOTE: You could also use cut's ability to work with the complement (ie, explicitly tell what characters to remove ... as opposed to above which says what characters to keep). See KamilCuk's answer for an example.

Obviously (?) the above does not overwrite test.txt so you'd need an extra step, eg:

```<code>$ echo '1234 5678' > test.txt
$ cut -c1-${x},${y}- test.txt > tmp.txt    # store result in intermediate file
$ cat tmp.txt > test.txt                   # copy intermediate file over original file
$ cat test.txt
14 5678
</code>```

Body:
I want to be able to delete the values to the RIGHT(starting from given column index) from the test.txt at the given column index based on a given length, N.

Column index refers to the position when you open the file in the VIM editor in LINUX.

If my test.txt contains 1234 5678, and I call my delete_var function which takes in the column number as 2 to start deleting from and length N as 2 to delete as input, the test.txt would reflect 14 5678 as it deleted the values from column 2 to column 4 as the length to delete was 2.

I have the following code as of now but I am unable to understand what I would put in the sed command.

delete_var() {

    sed -i -r 's/not sure what goes here' test.txt
}

clmn_index= $1
_N=$2

delete_var "$clmn_index" "$_N"   # call the method with the column index and length to delete

#sample test.txt (before call to fn)
1234 5678

#sample test.txt (after call to fn)
14 5678

Can someone guide me?

Body:
One idea using cut, keeping in mind that storing the results back into the original file will require an intermediate file (eg, tmp.txt) ...

Assume our variables:

$ s=2          # start position
$ n=2          # length of string to remove
$ x=$((s-1))   # last column to keep before the deleted characters (1 in this case)
$ y=$((s+n))   # start of first column to keep after the deleted characters (4 in this case)

At this point we can use cut -c to designate the columns to keep:

$ echo '1234 5678' > test.txt

$ set -x              # display the cut command with variables expanded
$ cut -c1-${x},${y}- test.txt
+ cut -c1-1,4- test.txt
14 5678

Where:

1-${x} - keep range of characters from position 1 to position $(x) (1-1 in this case)

${y}- - keep range of characters from position ${y} to end of line (4-EOL in this case)

NOTE: You could also use cut's ability to work with the complement (ie, explicitly tell what characters to remove ... as opposed to above which says what characters to keep). See KamilCuk's answer for an example.

Obviously (?) the above does not overwrite test.txt so you'd need an extra step, eg:

$ echo '1234 5678' > test.txt
$ cut -c1-${x},${y}- test.txt > tmp.txt    # store result in intermediate file
$ cat tmp.txt > test.txt                   # copy intermediate file over original file
$ cat test.txt
14 5678


问:
libucrl failed to check server certificate
I am using libcurl (in C) to login to a secure site (https). So far it was working fine. Since yesterday it is not able to login. The code looks as below.

```<code>bool login(char *user, char *password)
{
    bool result = false;
    CURL * curl = NULL;
    char errbuf[CURL_ERROR_SIZE];
    char status_text[1024];
    CURLcode res;
    long resp_code = 0;
    int index;

    /* These fields should be collected from license file */
    char *user_field = "name";
    char *password_field = "pass";

    char *form_id_field = "form_id";
    char *form_id = "user_login";

    char *link = "https://example.com/user/login";

    curl_global_init(CURL_GLOBAL_ALL);
    curl = curl_easy_init();
    if(curl == NULL) goto on_error;

    curl_easy_reset(curl);

    curl_easy_setopt(curl, CURLOPT_USERAGENT, "Mozilla/4.0");
    curl_easy_setopt(curl, CURLOPT_AUTOREFERER, 1);
    curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
    curl_easy_setopt(curl, CURLOPT_COOKIEFILE, "");
    curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errbuf);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, my_callback);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)NULL);

    curl_easy_setopt(curl, CURLOPT_URL, link);
    res = curl_easy_perform(curl);

    if(res == CURLE_OK)
    {
        curl_easy_setopt(curl, CURLOPT_AUTOREFERER, 1);
        curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
        curl_easy_setopt(curl, CURLOPT_REFERER, link);

        /* Data should be "name=user&pass=password&form_id=user-login" */
        index = sprintf(status_text, "%s=%s&%s=%s&%s=%s",
            user_field, user, password_field,
            password, form_id_field, form_id);

        *(status_text + index) = 0x0;

        resp_code = 0;
        res = CURLE_ABORTED_BY_CALLBACK;

        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, status_text);
        res = curl_easy_perform(curl);
        curl_easy_getinfo (curl, CURLINFO_RESPONSE_CODE, &resp_code);

        if((resp_code == 200) && (res != CURLE_ABORTED_BY_CALLBACK))
        {
            result = true;
        }
        else
        {
            result = false;
        }
    }

on_error:
    if(curl)
    {
        curl_easy_cleanup(curl);
        curl_global_cleanup();
        curl_global_cleanup();
    }

    return result;
}
</code>```

While curl_easy_perform is executed it fails. The errbuf shows error like "server certificate verification failed. cafile /etc/ssl/certs/ca-certificates.crt crlfile none". I understand it is somewhat problematic with /etc/ssl/certs/ca-certificates.crt file, but I did not change anything.

What may be the issue here, any hint to fix this, highly appreciated.

答:
It is more a hint than an answer but I don't have enough rep points to comment.

Since yesterday it is not able to login

This might be connected to the fact that Sectigo's legacy AddTrust External CA Root certificate expired on May 30, 2020 https://support.sectigo.com/articles/Knowledge/Sectigo-AddTrust-External-CA-Root-Expiring-May-30-2020

From the link above

Certificates for your site are issued from a “chain” of issuing or “intermediate” CA that completes a path back to these trusted root certificates.

If I understand the above statement correctly, AddTrust External CA Root certificate is probably one of the certs in chain thus validation fails - at least for some clients.

EDIT

What also worked for me is this https://www.agwa.name/blog/post/fixing_the_addtrust_root_expiration

edit /etc/ca-certificates.conf and put a bang/exclamation mark (!) before mozilla/AddTrust_External_Root.crt

Run update-ca-certificates

Body:
I am using libcurl (in C) to login to a secure site (https). So far it was working fine. Since yesterday it is not able to login. The code looks as below.

bool login(char *user, char *password)
{
    bool result = false;
    CURL * curl = NULL;
    char errbuf[CURL_ERROR_SIZE];
    char status_text[1024];
    CURLcode res;
    long resp_code = 0;
    int index;

    /* These fields should be collected from license file */
    char *user_field = "name";
    char *password_field = "pass";

    char *form_id_field = "form_id";
    char *form_id = "user_login";

    char *link = "https://example.com/user/login";

    curl_global_init(CURL_GLOBAL_ALL);
    curl = curl_easy_init();
    if(curl == NULL) goto on_error;

    curl_easy_reset(curl);

    curl_easy_setopt(curl, CURLOPT_USERAGENT, "Mozilla/4.0");
    curl_easy_setopt(curl, CURLOPT_AUTOREFERER, 1);
    curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
    curl_easy_setopt(curl, CURLOPT_COOKIEFILE, "");
    curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errbuf);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, my_callback);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)NULL);

    curl_easy_setopt(curl, CURLOPT_URL, link);
    res = curl_easy_perform(curl);

    if(res == CURLE_OK)
    {
        curl_easy_setopt(curl, CURLOPT_AUTOREFERER, 1);
        curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
        curl_easy_setopt(curl, CURLOPT_REFERER, link);

        /* Data should be "name=user&pass=password&form_id=user-login" */
        index = sprintf(status_text, "%s=%s&%s=%s&%s=%s",
            user_field, user, password_field,
            password, form_id_field, form_id);

        *(status_text + index) = 0x0;

        resp_code = 0;
        res = CURLE_ABORTED_BY_CALLBACK;

        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, status_text);
        res = curl_easy_perform(curl);
        curl_easy_getinfo (curl, CURLINFO_RESPONSE_CODE, &resp_code);

        if((resp_code == 200) && (res != CURLE_ABORTED_BY_CALLBACK))
        {
            result = true;
        }
        else
        {
            result = false;
        }
    }

on_error:
    if(curl)
    {
        curl_easy_cleanup(curl);
        curl_global_cleanup();
        curl_global_cleanup();
    }

    return result;
}

While curl_easy_perform is executed it fails. The errbuf shows error like "server certificate verification failed. cafile /etc/ssl/certs/ca-certificates.crt crlfile none". I understand it is somewhat problematic with /etc/ssl/certs/ca-certificates.crt file, but I did not change anything.

What may be the issue here, any hint to fix this, highly appreciated.


问:
Java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/firebase/FirebaseApp

This is React Native project. I have an error after successful build in Android Studio Emulator:

java.lang.NoClassDefFoundError: Failed resolution of:
  Lcom/google/firebase/FirebaseApp

My files:

package.json:

```<code>...
"react-native": "^0.55.3",
"react-native-camera": "1.1.2",
"react-native-check-box": "^2.1.0",
"react-native-extended-stylesheet": "^0.8.1",
"react-native-firebase": "^4.2.0",
"react-native-geocoder": "^0.5.0",
"react-native-git-upgrade": "^0.2.7",
"react-native-htmlview": "^0.12.1",
"react-native-image-picker": "^0.26.10",
"react-native-linear-gradient": "^2.4.0",
"react-native-local-storage": "^1.5.2",
"react-native-maps": "^0.21.0",
"react-native-modal": "^5.4.0",
"react-native-modal-dropdown": "^0.6.1",
"react-native-read-more-text": "^1.0.0",
"react-native-router-flux": "^4.0.0-beta.27",
"react-native-svg-image": "^2.0.1",
"react-native-text-input-mask": "^0.7.0",
...
</code>```

android/app/build.gradle:

```<code>...
android {
    compileSdkVersion 27
    buildToolsVersion "27.0.1"

    defaultConfig {
        applicationId "com.something.anything"
        minSdkVersion 16
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
        ndk {
            abiFilters "armeabi-v7a", "x86"
        }
        multiDexEnabled true
    }
    signingConfigs {
        release {
            if (project.hasProperty('MYAPP_RELEASE_STORE_FILE')) {
                storeFile file(MYAPP_RELEASE_STORE_FILE)
                storePassword MYAPP_RELEASE_STORE_PASSWORD
                keyAlias MYAPP_RELEASE_KEY_ALIAS
                keyPassword MYAPP_RELEASE_KEY_PASSWORD
            }
        }
    }
    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include "armeabi-v7a", "x86"
        }
    }
    buildTypes {
        release {
            signingConfig signingConfigs.release
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
        }
    }
    // applicationVariants are e.g. debug, release
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            // For each separate APK per architecture, set a unique version code as described here:
            // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits
            def versionCodes = ["armeabi-v7a":1, "x86":2]
            def abi = output.getFilter(OutputFile.ABI)
            if (abi != null) {  // null for the universal-debug, universal-release variants
                output.versionCodeOverride =
                        versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
            }
        }
    }
}

dependencies {
    compile(project(':react-native-firebase')) {
        transitive = false
    }
    compile project(':react-native-geocoder')
    compile(project(':react-native-maps')) {
      exclude group: 'com.google.android.gms', module: 'play-services-base'
      exclude group: 'com.google.android.gms', module: 'play-services-maps'
      exclude group: 'com.google.android.gms', module: 'play-services-location'
    }

    compile 'com.google.android.gms:play-services-base:15.+'
    compile 'com.google.android.gms:play-services-maps:15.+'
    compile 'com.google.android.gms:play-services-location:15.+'
    compile (project(':react-native-camera')) {
    exclude group: "com.google.android.gms"
    compile 'com.android.support:exifinterface:25.+'
    compile ('com.google.android.gms:play-services-vision:12.0.1') {
        force = true
        }
    }
    compile project(':react-native-text-input-mask')
    compile project(':react-native-linear-gradient')
    compile project(':react-native-image-picker')
    compile fileTree(dir: "libs", include: ["*.jar"])
    compile "com.android.support:appcompat-v7:23.0.1"
    compile "com.facebook.react:react-native:+"  // From node_modules
}

allprojects {
    repositories {
        maven { url "https://jitpack.io" }
        maven { url "https://maven.google.com" }
    }
}

// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
    from configurations.compile
    into 'libs'
}
</code>```

android/build.gradle

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
        google()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        mavenLocal()
        jcenter()
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url "$rootDir/../node_modules/react-native/android"
        }
    }
}

subprojects {
  project.configurations.all {
     resolutionStrategy.eachDependency { details ->
        if (details.requested.group == 'com.android.support'
              && !details.requested.name.contains('multidex')
        ) {
           details.useVersion "27.1.0"
        }
     }
  }
}
</code>```

I've tried a lot of solutions but nothing helped.

答:
UPDATE YOUR FIREBASE LIBRARIES!!!!

Eg. if your app uses firebase auth, Google for it, in its documentation they provide with the latest version, paste it to your build.gradle

The libraries added by your Firebase Assistant in Android Studio are usually old.

Body:
This is React Native project. I have an error after successful build in Android Studio Emulator:

java.lang.NoClassDefFoundError: Failed resolution of:
  Lcom/google/firebase/FirebaseApp

My files:

package.json:

...
"react-native": "^0.55.3",
"react-native-camera": "1.1.2",
"react-native-check-box": "^2.1.0",
"react-native-extended-stylesheet": "^0.8.1",
"react-native-firebase": "^4.2.0",
"react-native-geocoder": "^0.5.0",
"react-native-git-upgrade": "^0.2.7",
"react-native-htmlview": "^0.12.1",
"react-native-image-picker": "^0.26.10",
"react-native-linear-gradient": "^2.4.0",
"react-native-local-storage": "^1.5.2",
"react-native-maps": "^0.21.0",
"react-native-modal": "^5.4.0",
"react-native-modal-dropdown": "^0.6.1",
"react-native-read-more-text": "^1.0.0",
"react-native-router-flux": "^4.0.0-beta.27",
"react-native-svg-image": "^2.0.1",
"react-native-text-input-mask": "^0.7.0",
...

android/app/build.gradle:

...
android {
    compileSdkVersion 27
    buildToolsVersion "27.0.1"

    defaultConfig {
        applicationId "com.something.anything"
        minSdkVersion 16
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
        ndk {
            abiFilters "armeabi-v7a", "x86"
        }
        multiDexEnabled true
    }
    signingConfigs {
        release {
            if (project.hasProperty('MYAPP_RELEASE_STORE_FILE')) {
                storeFile file(MYAPP_RELEASE_STORE_FILE)
                storePassword MYAPP_RELEASE_STORE_PASSWORD
                keyAlias MYAPP_RELEASE_KEY_ALIAS
                keyPassword MYAPP_RELEASE_KEY_PASSWORD
            }
        }
    }
    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include "armeabi-v7a", "x86"
        }
    }
    buildTypes {
        release {
            signingConfig signingConfigs.release
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
        }
    }
    // applicationVariants are e.g. debug, release
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            // For each separate APK per architecture, set a unique version code as described here:
            // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits
            def versionCodes = ["armeabi-v7a":1, "x86":2]
            def abi = output.getFilter(OutputFile.ABI)
            if (abi != null) {  // null for the universal-debug, universal-release variants
                output.versionCodeOverride =
                        versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
            }
        }
    }
}

dependencies {
    compile(project(':react-native-firebase')) {
        transitive = false
    }
    compile project(':react-native-geocoder')
    compile(project(':react-native-maps')) {
      exclude group: 'com.google.android.gms', module: 'play-services-base'
      exclude group: 'com.google.android.gms', module: 'play-services-maps'
      exclude group: 'com.google.android.gms', module: 'play-services-location'
    }

    compile 'com.google.android.gms:play-services-base:15.+'
    compile 'com.google.android.gms:play-services-maps:15.+'
    compile 'com.google.android.gms:play-services-location:15.+'
    compile (project(':react-native-camera')) {
    exclude group: "com.google.android.gms"
    compile 'com.android.support:exifinterface:25.+'
    compile ('com.google.android.gms:play-services-vision:12.0.1') {
        force = true
        }
    }
    compile project(':react-native-text-input-mask')
    compile project(':react-native-linear-gradient')
    compile project(':react-native-image-picker')
    compile fileTree(dir: "libs", include: ["*.jar"])
    compile "com.android.support:appcompat-v7:23.0.1"
    compile "com.facebook.react:react-native:+"  // From node_modules
}

allprojects {
    repositories {
        maven { url "https://jitpack.io" }
        maven { url "https://maven.google.com" }
    }
}

// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
    from configurations.compile
    into 'libs'
}

android/build.gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
        google()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        mavenLocal()
        jcenter()
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url "$rootDir/../node_modules/react-native/android"
        }
    }
}

subprojects {
  project.configurations.all {
     resolutionStrategy.eachDependency { details ->
        if (details.requested.group == 'com.android.support'
              && !details.requested.name.contains('multidex')
        ) {
           details.useVersion "27.1.0"
        }
     }
  }
}

I've tried a lot of solutions but nothing helped.


问:
How do I set colors for three js instanced objects?
I have an a-frame component that leverages three js instancing to render a large number of spheres efficiently. Based on examples from the three js library such as https://github.com/mrdoob/three.js/blob/master/examples/webgl_instancing_scatter.html, I should be able to set the colors for each of the instanced renderings individually. I thought I had followed the example but my per instance colors are not taking effect.

```<code>AFRAME.registerComponent('spheres', {
    schema: {
        count: {type: 'number'},
        radius: {type: 'number'},
        scale: {type: 'number'},
        colors: {type: 'array'},
        positions: {type: 'array'}
    },
    init: function() {
        const {count, radius, scale, colors, positions} = this.data;

        const material = new THREE.MeshNormalMaterial();

        const geometry = new THREE.SphereBufferGeometry( radius, 3, 2 );
        const instancedGeometry = new THREE.InstancedBufferGeometry().copy(geometry);
        var instanceColors = [];

        for ( var i = 0; i < count; i ++ ) {

            instanceColors.push( Math.random() );
            instanceColors.push( Math.random() );
            instanceColors.push( Math.random() );

        }
        instancedGeometry.setAttribute("instanceColor", new THREE.InstancedBufferAttribute( new Float32Array( instanceColors ), 3 ))

        instancedGeometry.computeVertexNormals();

        material.vertexColors = true;

        const matrix = new THREE.Matrix4();
        const mesh = new THREE.InstancedMesh( instancedGeometry, material, count );

        for ( var i = 0; i < count; i ++ ) {

            this.setMatrix(positions[i], scale)( matrix );
            mesh.setMatrixAt( i, matrix );

        }

        this.el.object3D.add( mesh );
    },
</code>```

What am I doing wrong?

答:
Got it to work with the following based on @prisoner849 example. I had to use MeshPhongMaterial rather than MeshNormalMaterial. Not quite sure why. Also not sure why I need to use an InstancedBufferAttribute and a BufferAttribute for the colors. maybe @prisoner849 can follow up with details. This solution is a bit ugly, hopefully three will provide a cleaner way to tweak instanced colors soon, or maybe there is a better way already and I just dont know about it</p>

```<code>AFRAME.registerComponent('spheres', {
    schema: {
        count: {type: 'number'},
        radius: {type: 'number'},
        scale: {type: 'number'},
        colors: {type: 'array'},
        positions: {type: 'array'}
    },
    init: function() {
        const {count, radius, scale, colors, positions} = this.data;

        var geometry = new THREE.SphereBufferGeometry(radius);
        var material = new THREE.MeshPhongMaterial({ flatShading: true });
        var colorParsChunk = [
            'attribute vec3 instanceColor;',
            'varying vec3 vInstanceColor;',
            '#include <common>'
        ].join( '\n' );

        var instanceColorChunk = [
            '#include <begin_vertex>',
            '\tvInstanceColor = instanceColor;'
        ].join( '\n' );

        var fragmentParsChunk = [
            'varying vec3 vInstanceColor;',
            '#include <common>'
        ].join( '\n' );

        var colorChunk = [
            'vec4 diffuseColor = vec4( diffuse * vInstanceColor, opacity );'
        ].join( '\n' );

        material.onBeforeCompile = function ( shader ) {

            shader.vertexShader = shader.vertexShader
                .replace( '#include <common>', colorParsChunk )
                .replace( '#include <begin_vertex>', instanceColorChunk );

            shader.fragmentShader = shader.fragmentShader
                .replace( '#include <common>', fragmentParsChunk )
                .replace( 'vec4 diffuseColor = vec4( diffuse, opacity );', colorChunk );

        };

        var instanceColors = [];

        for ( var i = 0; i < count; i ++ ) {

            instanceColors.push( Math.random() );
            instanceColors.push( Math.random() );
            instanceColors.push( Math.random() );

        }

        const matrix = new THREE.Matrix4();
        const mesh = new THREE.InstancedMesh( geometry, material, count );

        var instanceColorsBase = new Float32Array(instanceColors.length);
        instanceColorsBase.set(instanceColors);
        geometry.setAttribute( 'instanceColor', new THREE.InstancedBufferAttribute( new Float32Array( instanceColors ), 3 ) );
        geometry.setAttribute( 'instanceColorBase', new THREE.BufferAttribute(new Float32Array( instanceColorsBase ), 3 ) );

        for ( var i = 0; i < count; i ++ ) {

            this.setMatrix(positions[i], scale)( matrix );
            mesh.setMatrixAt( i, matrix );

        }

        this.el.object3D.add( mesh );
    },
    setMatrix: function( pos, scaler ) {

        var position = new THREE.Vector3();
        var rotation = new THREE.Euler();
        var quaternion = new THREE.Quaternion();
        var scale = new THREE.Vector3();

        return function ( matrix ) {

            position.x = pos[0];
            position.y = pos[1];
            position.z = pos[2];

            rotation.x = 0;
            rotation.y = 0;
            rotation.z = 0;

            quaternion.setFromEuler( rotation );

            scale.x = scale.y = scale.z = scaler;

            matrix.compose( position, quaternion, scale );

        };

    }
});
</code>```

Body:
I have an a-frame component that leverages three js instancing to render a large number of spheres efficiently. Based on examples from the three js library such as https://github.com/mrdoob/three.js/blob/master/examples/webgl_instancing_scatter.html, I should be able to set the colors for each of the instanced renderings individually. I thought I had followed the example but my per instance colors are not taking effect.

AFRAME.registerComponent('spheres', {
    schema: {
        count: {type: 'number'},
        radius: {type: 'number'},
        scale: {type: 'number'},
        colors: {type: 'array'},
        positions: {type: 'array'}
    },
    init: function() {
        const {count, radius, scale, colors, positions} = this.data;

        const material = new THREE.MeshNormalMaterial();

        const geometry = new THREE.SphereBufferGeometry( radius, 3, 2 );
        const instancedGeometry = new THREE.InstancedBufferGeometry().copy(geometry);
        var instanceColors = [];

        for ( var i = 0; i < count; i ++ ) {

            instanceColors.push( Math.random() );
            instanceColors.push( Math.random() );
            instanceColors.push( Math.random() );

        }
        instancedGeometry.setAttribute("instanceColor", new THREE.InstancedBufferAttribute( new Float32Array( instanceColors ), 3 ))

        instancedGeometry.computeVertexNormals();

        material.vertexColors = true;

        const matrix = new THREE.Matrix4();
        const mesh = new THREE.InstancedMesh( instancedGeometry, material, count );

        for ( var i = 0; i < count; i ++ ) {

            this.setMatrix(positions[i], scale)( matrix );
            mesh.setMatrixAt( i, matrix );

        }

        this.el.object3D.add( mesh );
    },

What am I doing wrong?

Body:
Got it to work with the following based on @prisoner849 example. I had to use MeshPhongMaterial rather than MeshNormalMaterial. Not quite sure why. Also not sure why I need to use an InstancedBufferAttribute and a BufferAttribute for the colors. maybe @prisoner849 can follow up with details. This solution is a bit ugly, hopefully three will provide a cleaner way to tweak instanced colors soon, or maybe there is a better way already and I just dont know about it

AFRAME.registerComponent('spheres', {
    schema: {
        count: {type: 'number'},
        radius: {type: 'number'},
        scale: {type: 'number'},
        colors: {type: 'array'},
        positions: {type: 'array'}
    },
    init: function() {
        const {count, radius, scale, colors, positions} = this.data;

        var geometry = new THREE.SphereBufferGeometry(radius);
        var material = new THREE.MeshPhongMaterial({ flatShading: true });
        var colorParsChunk = [
            'attribute vec3 instanceColor;',
            'varying vec3 vInstanceColor;',
            '#include <common>'
        ].join( '\n' );

        var instanceColorChunk = [
            '#include <begin_vertex>',
            '\tvInstanceColor = instanceColor;'
        ].join( '\n' );

        var fragmentParsChunk = [
            'varying vec3 vInstanceColor;',
            '#include <common>'
        ].join( '\n' );

        var colorChunk = [
            'vec4 diffuseColor = vec4( diffuse * vInstanceColor, opacity );'
        ].join( '\n' );

        material.onBeforeCompile = function ( shader ) {

            shader.vertexShader = shader.vertexShader
                .replace( '#include <common>', colorParsChunk )
                .replace( '#include <begin_vertex>', instanceColorChunk );

            shader.fragmentShader = shader.fragmentShader
                .replace( '#include <common>', fragmentParsChunk )
                .replace( 'vec4 diffuseColor = vec4( diffuse, opacity );', colorChunk );

        };

        var instanceColors = [];

        for ( var i = 0; i < count; i ++ ) {

            instanceColors.push( Math.random() );
            instanceColors.push( Math.random() );
            instanceColors.push( Math.random() );

        }

        const matrix = new THREE.Matrix4();
        const mesh = new THREE.InstancedMesh( geometry, material, count );

        var instanceColorsBase = new Float32Array(instanceColors.length);
        instanceColorsBase.set(instanceColors);
        geometry.setAttribute( 'instanceColor', new THREE.InstancedBufferAttribute( new Float32Array( instanceColors ), 3 ) );
        geometry.setAttribute( 'instanceColorBase', new THREE.BufferAttribute(new Float32Array( instanceColorsBase ), 3 ) );

        for ( var i = 0; i < count; i ++ ) {

            this.setMatrix(positions[i], scale)( matrix );
            mesh.setMatrixAt( i, matrix );

        }

        this.el.object3D.add( mesh );
    },
    setMatrix: function( pos, scaler ) {

        var position = new THREE.Vector3();
        var rotation = new THREE.Euler();
        var quaternion = new THREE.Quaternion();
        var scale = new THREE.Vector3();

        return function ( matrix ) {

            position.x = pos[0];
            position.y = pos[1];
            position.z = pos[2];

            rotation.x = 0;
            rotation.y = 0;
            rotation.z = 0;

            quaternion.setFromEuler( rotation );

            scale.x = scale.y = scale.z = scaler;

            matrix.compose( position, quaternion, scale );

        };

    }
});


问:
Finding the calculation that generates a NaN
I have a moderately large piece (a few thousand lines) of Python/Numpy/Scipy code that is throwing up NaNs with certain inputs. I've looked for, and found, some of the usual suspects (log(0) and the like), but none of the obvious ones seem to be the culprits in this case.

Is there a relatively painless way (i.e., apart from putting exception handling code around each potential culprit), to find out where these NaNs are coming from?

答:
I would start with numpy.seterr.

There, an invalid operation is defined as "result is not an expressible number, typically indicates that a NaN was produced". By default, this seems to be set to "ignore".


问:
Paypal Smart Buttons - Expires Field (yy vs yyyy)
I just installed Paypal Smart Buttons on my website and to my surprise the Expires field does not get auto filled since it's MM/YY rather than MM/YYYY. I looked through the documentation and found nothing in regards how to change this. Has anyone managed to get around this issue?

Before:

After:

答:
I did some research on this and found that if the attribute autocomplete="cc-exp-year" were set on the form field per Chrome's spec, it might make this field auto-complete automatically. I sent this tip PayPal's way for them to investigate as a potential bug/improvement since it'll be best to make this work for everyone.

(There might be a way to make just your browser recognize the field, but that won't help customers)


问:
Purpose of overloading member function returning iterator and const_iterator
In my class assignment I am suppose to implement member functions of a predefined class. I am confused on the purpose of these the overload on findStudent. Can this class not be designed to only contain one definition, which returns a regular iterator that can be casted as const? Or rather, use std::find since it is already overloaded to return a const_iterator?</p>

```<code>class Class{
public:
   Class(std::string name, std::string teacher, std::string capacity);
   std::string getTeacher();
   std::string getName();
   int getCapacity();
   void addStudent(std::string);
   void removeStudent(std::string);
   std::vector<std::string>::iterator findStudent();
   std::vector<std::string>::const_iterator findStudent() const;
private:
   std::string name;
   std::string teacher;
   int capacity;
   std::vector<std::string> students;
};
</code>```

答:
The purpose of overloading those functions is that they differ by their const-ness.

Consider:

you pass Class foo; to a function

void bar(Class& foo).

If inside this function you were to call findStudent(), the non-const version of the member function would be invoked. As a result, you would get a mutating iterator of std::vector<std::string>. The iterator would allow to assign new values, clear strings and do whatever else you want with the values.

Now consider another case:

void bar(const Class& foo).

Inside this function, the const version of findStudents() will be called, and you won't be able to modify the values. You will be able to inspect them, to print them, to sum the lengths, i.e., you will be able to do only non-mutating operations on your students.

The purpose of this is to enable both the compiler and -- especially important! -- the programmer to reason about the code. Const functions do not change the state of the object, they conserve invariants of the code. For instance, it generally holds that if you call a const function twice in succession, both calls should return the same answer. (This holds "generally", but not always, especially if we are dealing with hardware).

Body:
In my class assignment I am suppose to implement member functions of a predefined class. I am confused on the purpose of these the overload on findStudent. Can this class not be designed to only contain one definition, which returns a regular iterator that can be casted as const? Or rather, use std::find since it is already overloaded to return a const_iterator?

class Class{
public:
   Class(std::string name, std::string teacher, std::string capacity);
   std::string getTeacher();
   std::string getName();
   int getCapacity();
   void addStudent(std::string);
   void removeStudent(std::string);
   std::vector<std::string>::iterator findStudent();
   std::vector<std::string>::const_iterator findStudent() const;
private:
   std::string name;
   std::string teacher;
   int capacity;
   std::vector<std::string> students;
};


问:
Is it possible to fire a .then() block without a return value from a promise?
Curious issue I'm having dealing with some callback functions. I need to make a series of API calls that all return promises  then  I'm trying to take that data and map it to an array that exists on the global scope followed by a function to export the new data as a pdf - my issue is that the then() block is firing before the other function finishes and far before the first API call finshes.  `

```<code> let fireWatson = async () => {
        let watsonClassifed = []
        let watsonCallIndex = 0;
        let returnedArr = []
        for (let i = 0; i < watsonData.length; i++) {
            let params = {
                classifierId: '***********',
                collection: watsonData[i]
            }
            naturalLanguageClassifier.classifyCollection(params,
                 function (err, response) {
                    if (err)
                        console.log('error:', err);
                    else
                        console.log("data returned")
                        console.log(response.result.collection)
                    watsonClassifed.push(response.result.collection);
                    console.log(watsonClassifed)
                })

    }
}

fireWatson(watsonData).then(res =>
        console.log("firing stupid callbback after data")
    )
</code>```

I realize this function isnt actually returning anything but is it possible to still make use of a promise without a return value or is this the main issue im hitting?  Ideally - i want the then function to wait until the data is back - mapped to the global array and then outputted but this of course depends on proper synchronicity.

output:

```<code>[Done] exited with code=0 in 1.526 seconds

[Running] node "index.js"
firing stupid callbback
data returned
all my sweet sweet data
</code>```

答:
turns out console.log was firing because every .then() block expects a function.

wrong:

```<code> fireWatson(watsonData).then(res =>
            console.log("firing stupid callbback after data")
        )
</code>```

right:

```<code>fireWatson(watsonData).then(()res =>
            console.log("firing stupid callbback after data")
        )
</code>```

Body:
Curious issue I'm having dealing with some callback functions. I need to make a series of API calls that all return promises  then  I'm trying to take that data and map it to an array that exists on the global scope followed by a function to export the new data as a pdf - my issue is that the then() block is firing before the other function finishes and far before the first API call finshes.  `

 let fireWatson = async () => {
        let watsonClassifed = []
        let watsonCallIndex = 0;
        let returnedArr = []
        for (let i = 0; i < watsonData.length; i++) {
            let params = {
                classifierId: '***********',
                collection: watsonData[i]
            }
            naturalLanguageClassifier.classifyCollection(params,
                 function (err, response) {
                    if (err)
                        console.log('error:', err);
                    else
                        console.log("data returned")
                        console.log(response.result.collection)
                    watsonClassifed.push(response.result.collection);
                    console.log(watsonClassifed)
                })

    }
}

fireWatson(watsonData).then(res =>
        console.log("firing stupid callbback after data")
    )

I realize this function isnt actually returning anything but is it possible to still make use of a promise without a return value or is this the main issue im hitting?  Ideally - i want the then function to wait until the data is back - mapped to the global array and then outputted but this of course depends on proper synchronicity.

output:

[Done] exited with code=0 in 1.526 seconds

[Running] node "index.js"
firing stupid callbback
data returned
all my sweet sweet data

Body:
turns out console.log was firing because every .then() block expects a function.

wrong:

 fireWatson(watsonData).then(res =>
            console.log("firing stupid callbback after data")
        )

right:

fireWatson(watsonData).then(()res =>
            console.log("firing stupid callbback after data")
        )


问:
How to make Strapi recognize custom domain pointing to an S3 bucket?
I'm using an S3 bucket to store static assets through the strapi-provider-upload-aws-s3 plugin. Also, I have a custom domain pointing to that bucket via SSL. Basically, https://my.domain.com/photo.jpg points to https://s3.amazonaws.com/my.domain.com/photo.jpg. Is there any way to let the plugin know this so it automatically changes the URLs from s3.amazonaws.com/my.domain.com to just my.domain.com before updating the field containing such a URL?

If this isn't possible via a straightforward configuration or the dashboard, is there any way to tweak the code itself to incorporate this functionality? And if so (am strongly hoping there is), what file holds this logic should one were to go this route?

答:
I ran into the same problem, but after a lot of hours of research, you can do the next:

First configure an S3 bucket with the name of your custom domain for example: static.yourdomain.com and make it as Static Hosting on S3 Settings, after in your configuration of strapi S3 provider put the next:

```<code>providerOptions: {
      accessKeyId: process.env.AWS_ACCESS_KEY_ID || '',
      secretAccessKey: process.env.AWS_ACCESS_SECRET || '',
      region: 'us-east-1',
      endpoint: 'static.yourdomain.com',
      s3BucketEndpoint: true,
      params: {
        Bucket: 'static.yourdomain.com'
      },
    }
</code>```

In your DNS create an CNAME static.yourdomain.com which points to the s3 public domain, but the trick is the following:

Instead of this:

```<code>static.yourdomain.com.s3-website-us-east-1.amazonaws.com
</code>```

Put this:

```<code>static.yourdomain.com.s3.amazonaws.com
</code>```

Body:
I ran into the same problem, but after a lot of hours of research, you can do the next:

First configure an S3 bucket with the name of your custom domain for example: static.yourdomain.com and make it as Static Hosting on S3 Settings, after in your configuration of strapi S3 provider put the next:

providerOptions: {
      accessKeyId: process.env.AWS_ACCESS_KEY_ID || '',
      secretAccessKey: process.env.AWS_ACCESS_SECRET || '',
      region: 'us-east-1',
      endpoint: 'static.yourdomain.com',
      s3BucketEndpoint: true,
      params: {
        Bucket: 'static.yourdomain.com'
      },
    }

In your DNS create an CNAME static.yourdomain.com which points to the s3 public domain, but the trick is the following:

Instead of this:

static.yourdomain.com.s3-website-us-east-1.amazonaws.com

Put this:

static.yourdomain.com.s3.amazonaws.com


问:
Reveal input to the left not the right
I have code that shows and reveals an input box to the right of the search icon. I'm looking to have it slide open so the input is on the left side. However, my attempts just make matters worse.

Your assistance is appreciated.

Below is the working example that shows the input box revealing to the right side.

var search_btn = document.querySelector(".search-btn");
search_btn.addEventListener("click",function(){
    document.querySelector('.search-slide').classList.toggle("active");
   document.querySelector('.search-slide input[type=search]').focus();
})

var close_btn = document.querySelector(".search-close");
close_btn.addEventListener("click",function(){
   document.querySelector('.search-slide').classList.toggle("active");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>input {
  max-width: 100%;
  padding: 0;
  margin: 0;
  font-size: 1em;
  color: inherit;
}

input[type=submit],
input[type=button] {
  cursor: pointer;
}

.ib-m {
  display: inline-block;
  vertical-align: middle;
}
.search {
  min-width: 18.9375em;
}
.search input[type=submit] {
  vertical-align: middle;
  width: 1.375em;
  height: 1.375em;
  border: none;
  outline: none;
  background: none;
  -webkit-transition: opacity 100ms ease-in-out;
  transition: opacity 100ms ease-in-out;
}
.search input[type=submit]:hover {
  opacity: .5;
}
.search input[type=search] {
  width: 14em;
  height: 2.5em;
  padding: 0 .375em;
  border: none;
  border-bottom: 1px solid #000;
  margin-left: .1875em;
  background: inherit;
  -webkit-transition: border-color 100ms ease-in-out;
  transition: border-color 100ms ease-in-out;
}
.search input[type=search]:focus {
  border-bottom-color: inherit;
  outline: none;
}

.search-slide {
  width: 0;
  height: 2.5em;
  overflow: hidden;
  transition:width 0.3s ease;
}

.search-slide.active{width:15.5625em}

.search-close {
  width: 1.375em;
  height: 1.375em;
  text-align: center;
  cursor: pointer;
  -webkit-transition: opacity 100ms ease-in-out;
  transition: opacity 100ms ease-in-out;
}
.search-close:hover {
  opacity: .5;
}</code>```

<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css" rel="stylesheet"/>

<input type="submit" value="" class="search-btn fa ib-m">

<input type="search" placeholder="Enter your search" class="ib-m">

```
</div>
</div>
</p>

<p>Below is my broken attempt to do what my ultimate goal is:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var search_btn = document.querySelector(".search-btn");
search_btn.addEventListener("click",function(){
    document.querySelector('.search-slide').classList.toggle("active");
   document.querySelector('.search-slide input[type=search]').focus();
})

var close_btn = document.querySelector(".search-close");
close_btn.addEventListener("click",function(){
   document.querySelector('.search-slide').classList.toggle("active");
});</code>```

input {
  max-width: 100%;
  padding: 0;
  margin: 0;
  font-size: 1em;
  color: inherit;
}

input[type=submit],
input[type=button] {
  cursor: pointer;
}

.ib-m {
  display: inline-block;
  vertical-align: middle;
}
.search {
  min-width: 18.9375em;
}
.search input[type=submit] {
  vertical-align: middle;
  width: 1.375em;
  height: 1.375em;
  border: none;
  outline: none;
  background: none;
  -webkit-transition: opacity 100ms ease-in-out;
  transition: opacity 100ms ease-in-out;
}
.search input[type=submit]:hover {
  opacity: .5;
}
.search input[type=search] {
  width: 14em;
  height: 2.5em;
  padding: 0 .375em;
  border: none;
  border-bottom: 1px solid #000;
  margin-left: .1875em;
  background: inherit;
  -webkit-transition: border-color 100ms ease-in-out;
  transition: border-color 100ms ease-in-out;
}
.search input[type=search]:focus {
  border-bottom-color: inherit;
  outline: none;
}

.search-slide {
  width: 0;
  height: 2.5em;
  overflow: hidden;
  transition:width 0.3s ease;
}

.search-slide.active{width:15.5625em}

.search-close {
  width: 1.375em;
  height: 1.375em;
  text-align: center;
  cursor: pointer;
  -webkit-transition: opacity 100ms ease-in-out;
  transition: opacity 100ms ease-in-out;
}
.search-close:hover {
  opacity: .5;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css" rel="stylesheet"/>
<div class="search">
<input type="search" placeholder="Enter your search" class="ib-m"><div class="search-slide ib-m">
<input type="submit" value="" class="search-btn fa ib-m"><div class="search-close ib-m"><i class="fa fa-times"></i></div>
</div></div></code>```

答:
There are several ways to achieve what you want, one of the easiest one could be reordering the HTML elements. Also since you are using fonts for your icons, width and height attributes will not affect them. So you just have to specify their size by font-size.

So your code should be something like this:

var search_btn = document.querySelector(".search-btn");
search_btn.addEventListener("click", function() {
  document.querySelector('.search-slide').classList.toggle("active");
  document.querySelector('.search-slide input[type=search]').focus();
})

var close_btn = document.querySelector(".search-close");
close_btn.addEventListener("click", function() {
  document.querySelector('.search-slide').classList.toggle("active");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>input {
  max-width: 100%;
  padding: 0;
  margin: 0;
  font-size: 1em;
  color: inherit;
}

input[type=submit],
input[type=button] {
  cursor: pointer;
}

.ib-m {
  display: inline-block;
  vertical-align: middle;
}

.search {
  min-width: 18.9375em;
}

.search input[type=submit] {
  vertical-align: middle;
  border: none;
  outline: none;
  background: none;
  -webkit-transition: opacity 100ms ease-in-out;
  transition: opacity 100ms ease-in-out;
}

.search input[type=submit]:hover {
  opacity: .5;
}

.search input[type=search] {
  width: 14em;
  height: 2.5em;
  padding: 0 .375em;
  border: none;
  border-bottom: 1px solid #000;
  margin-left: .1875em;
  background: inherit;
  -webkit-transition: border-color 100ms ease-in-out;
  transition: border-color 100ms ease-in-out;
}

.search input[type=search]:focus {
  border-bottom-color: inherit;
  outline: none;
}

.search-slide {
  width: 0;
  height: 2.5em;
  overflow: hidden;
  transition: width 0.3s ease;
}

.search-slide.active {
  width: 15.5625em
}

.search-close {
  text-align: center;
  cursor: pointer;
  -webkit-transition: opacity 100ms ease-in-out;
  transition: opacity 100ms ease-in-out;
}

.search-close:hover {
  opacity: .5;
}</code>```

<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css" rel="stylesheet" />

    <input type="search" placeholder="Enter your search" class="ib-m">

  <input type="submit" value="" class="search-btn fa ib-m">

```

Title: Reveal input to the left not the right

Body:
I have code that shows and reveals an input box to the right of the search icon. I'm looking to have it slide open so the input is on the left side. However, my attempts just make matters worse.

Your assistance is appreciated.

Below is the working example that shows the input box revealing to the right side.

var search_btn = document.querySelector(".search-btn");
search_btn.addEventListener("click",function(){
    document.querySelector('.search-slide').classList.toggle("active");
   document.querySelector('.search-slide input[type=search]').focus();
})

var close_btn = document.querySelector(".search-close");
close_btn.addEventListener("click",function(){
   document.querySelector('.search-slide').classList.toggle("active");
});

input {
  max-width: 100%;
  padding: 0;
  margin: 0;
  font-size: 1em;
  color: inherit;
}

input[type=submit],
input[type=button] {
  cursor: pointer;
}

.ib-m {
  display: inline-block;
  vertical-align: middle;
}
.search {
  min-width: 18.9375em;
}
.search input[type=submit] {
  vertical-align: middle;
  width: 1.375em;
  height: 1.375em;
  border: none;
  outline: none;
  background: none;
  -webkit-transition: opacity 100ms ease-in-out;
  transition: opacity 100ms ease-in-out;
}
.search input[type=submit]:hover {
  opacity: .5;
}
.search input[type=search] {
  width: 14em;
  height: 2.5em;
  padding: 0 .375em;
  border: none;
  border-bottom: 1px solid #000;
  margin-left: .1875em;
  background: inherit;
  -webkit-transition: border-color 100ms ease-in-out;
  transition: border-color 100ms ease-in-out;
}
.search input[type=search]:focus {
  border-bottom-color: inherit;
  outline: none;
}

.search-slide {
  width: 0;
  height: 2.5em;
  overflow: hidden;
  transition:width 0.3s ease;
}

.search-slide.active{width:15.5625em}

.search-close {
  width: 1.375em;
  height: 1.375em;
  text-align: center;
  cursor: pointer;
  -webkit-transition: opacity 100ms ease-in-out;
  transition: opacity 100ms ease-in-out;
}
.search-close:hover {
  opacity: .5;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css" rel="stylesheet"/>

<input type="submit" value="" class="search-btn fa ib-m">

<input type="search" placeholder="Enter your search" class="ib-m">

Below is my broken attempt to do what my ultimate goal is:

var search_btn = document.querySelector(".search-btn");
search_btn.addEventListener("click",function(){
    document.querySelector('.search-slide').classList.toggle("active");
   document.querySelector('.search-slide input[type=search]').focus();
})

var close_btn = document.querySelector(".search-close");
close_btn.addEventListener("click",function(){
   document.querySelector('.search-slide').classList.toggle("active");
});

input {
  max-width: 100%;
  padding: 0;
  margin: 0;
  font-size: 1em;
  color: inherit;
}

input[type=submit],
input[type=button] {
  cursor: pointer;
}

.ib-m {
  display: inline-block;
  vertical-align: middle;
}
.search {
  min-width: 18.9375em;
}
.search input[type=submit] {
  vertical-align: middle;
  width: 1.375em;
  height: 1.375em;
  border: none;
  outline: none;
  background: none;
  -webkit-transition: opacity 100ms ease-in-out;
  transition: opacity 100ms ease-in-out;
}
.search input[type=submit]:hover {
  opacity: .5;
}
.search input[type=search] {
  width: 14em;
  height: 2.5em;
  padding: 0 .375em;
  border: none;
  border-bottom: 1px solid #000;
  margin-left: .1875em;
  background: inherit;
  -webkit-transition: border-color 100ms ease-in-out;
  transition: border-color 100ms ease-in-out;
}
.search input[type=search]:focus {
  border-bottom-color: inherit;
  outline: none;
}

.search-slide {
  width: 0;
  height: 2.5em;
  overflow: hidden;
  transition:width 0.3s ease;
}

.search-slide.active{width:15.5625em}

.search-close {
  width: 1.375em;
  height: 1.375em;
  text-align: center;
  cursor: pointer;
  -webkit-transition: opacity 100ms ease-in-out;
  transition: opacity 100ms ease-in-out;
}
.search-close:hover {
  opacity: .5;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css" rel="stylesheet"/>

<input type="search" placeholder="Enter your search" class="ib-m">

<input type="submit" value="" class="search-btn fa ib-m">

Body:
There are several ways to achieve what you want, one of the easiest one could be reordering the HTML elements. Also since you are using fonts for your icons, width and height attributes will not affect them. So you just have to specify their size by font-size.

So your code should be something like this:

var search_btn = document.querySelector(".search-btn");
search_btn.addEventListener("click", function() {
  document.querySelector('.search-slide').classList.toggle("active");
  document.querySelector('.search-slide input[type=search]').focus();
})

var close_btn = document.querySelector(".search-close");
close_btn.addEventListener("click", function() {
  document.querySelector('.search-slide').classList.toggle("active");
});

input {
  max-width: 100%;
  padding: 0;
  margin: 0;
  font-size: 1em;
  color: inherit;
}

input[type=submit],
input[type=button] {
  cursor: pointer;
}

.ib-m {
  display: inline-block;
  vertical-align: middle;
}

.search {
  min-width: 18.9375em;
}

.search input[type=submit] {
  vertical-align: middle;
  border: none;
  outline: none;
  background: none;
  -webkit-transition: opacity 100ms ease-in-out;
  transition: opacity 100ms ease-in-out;
}

.search input[type=submit]:hover {
  opacity: .5;
}

.search input[type=search] {
  width: 14em;
  height: 2.5em;
  padding: 0 .375em;
  border: none;
  border-bottom: 1px solid #000;
  margin-left: .1875em;
  background: inherit;
  -webkit-transition: border-color 100ms ease-in-out;
  transition: border-color 100ms ease-in-out;
}

.search input[type=search]:focus {
  border-bottom-color: inherit;
  outline: none;
}

.search-slide {
  width: 0;
  height: 2.5em;
  overflow: hidden;
  transition: width 0.3s ease;
}

.search-slide.active {
  width: 15.5625em
}

.search-close {
  text-align: center;
  cursor: pointer;
  -webkit-transition: opacity 100ms ease-in-out;
  transition: opacity 100ms ease-in-out;
}

.search-close:hover {
  opacity: .5;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css" rel="stylesheet" />
<div class="search">
  <div class="search-slide ib-m">
    <input type="search" placeholder="Enter your search" class="ib-m">
    <div class="search-close ib-m"><i class="fa fa-times"></i></div>
  </div>
  <input type="submit" value="&#xf002;" class="search-btn fa ib-m">
</div>


问:
"npm ERR! unexpected end of JSON input near" while creating a new react app
[enter image description here][1]npm

I am trying for so many times to create a app in react but every time the CMD showing an ERR!

here is code :
Microsoft Windows [Version 10.0.18363.476]
(c) 2019 Microsoft Corporation. All rights reserved.

C:\Users\Sumit>E:
The system cannot find the drive specified.

C:\Users\Sumit>D:

D:>React js
'React' is not recognized as an internal or external command,
operable program or batch file.

D:>react js
'react' is not recognized as an internal or external command,
operable program or batch file.

D:>React js
'React' is not recognized as an internal or external command,
operable program or batch file.

D:>create-react-app my_react

Creating a new React app in D:\my_react.

Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts...

npm ERR! Response timeout while trying to fetch https://registry.npmjs.org/react (over 30000ms)

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Sumit\AppData\Roaming\npm-cache_logs\2020-06-01T14_33_43_496Z-debug.log

Aborting installation.
  npm install --save --save-exact --loglevel error react react-dom react-scripts has failed.

Deleting generated file... package.json
Deleting my_react / from D:\
Done.

D:>create-react-app my-react-app

Creating a new React app in D:\my-react-app.

Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts...

npm ERR! Unexpected end of JSON input while parsing near '...Y3hEcJW8se9P4K6+GYGu9'

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Sumit\AppData\Roaming\npm-cache_logs\2020-06-01T14_34_57_334Z-debug.log

Aborting installation.
  npm install --save --save-exact --loglevel error react react-dom react-scripts has failed.

Deleting generated file... package.json
Deleting my-react-app / from D:\
Done.

D:>create-react-app new-react

Creating a new React app in D:\new-react.

Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts...

npm ERR! Unexpected end of JSON input while parsing near '...gAAwSQP/RpJCkm/rgw8jt'

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Sumit\AppData\Roaming\npm-cache_logs\2020-06-01T14_38_28_735Z-debug.log

Aborting installation.
  npm install --save --save-exact --loglevel error react react-dom react-scripts has failed.

Deleting generated file... package.json
Deleting new-react / from D:\
Done.

D:>npm create-react-app my-react-aplication

Usage: npm

where  is one of:
    access, adduser, audit, bin, bugs, c, cache, ci, cit,
    clean-install, clean-install-test, completion, config,
    create, ddp, dedupe, deprecate, dist-tag, docs, doctor,
    edit, explore, fund, get, help, help-search, hook, i, init,
    install, install-ci-test, install-test, it, link, list, ln,
    login, logout, ls, org, outdated, owner, pack, ping, prefix,
    profile, prune, publish, rb, rebuild, repo, restart, root,
    run, run-script, s, se, search, set, shrinkwrap, star,
    stars, start, stop, t, team, test, token, tst, un,
    uninstall, unpublish, unstar, up, update, v, version, view,
    whoami

npm  -h  quick help on
npm -l            display full usage info
npm help    search for help on
npm help npm      involved overview

Specify configs in the ini-formatted file:
    C:\Users\Sumit.npmrc
or on the command line via: npm  --key value
Config info can be viewed via: npm help config

npm@6.14.4 C:\Program Files\nodejs\node_modules\npm

D:>npx create-react-app my-react

Creating a new React app in D:\my-react.

Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts...

npm ERR! Unexpected end of JSON input while parsing near '...gAAwSQP/RpJCkm/rgw8jt'

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Sumit\AppData\Roaming\npm-cache_logs\2020-06-01T14_54_02_126Z-debug.log

Aborting installation.
  npm install --save --save-exact --loglevel error react react-dom react-scripts has failed.

Deleting generated file... package.json
Deleting my-react / from D:\
Done.

D:>

答:
if you didn't install npm in general mode, it should better you do it with this comment in the root with the command

npm install -g
, or if you did it before you need to update it with the command
npm update [-g]


问:
Can you use C# to orchestrate (durable function) a Python Azure Function?
We are using a Python Azure Function for ETL based on several files that are dropped off in blob storage every day at the same time. Our current workflow is using several Python functions to pick up those files (using the azure-storage-blob Python library), transform them, load them to our Azure SQL database, and then archive all the files to cold storage. Right now we are relying on timer triggers because some of the functions depend on other functions to be complete before manipulating and archiving the source files.

It seems like using Azure Durable Functions would be a better workflow for this, since we could orchestrate the functions better and decide when either the next ETL process should run or when the files should be archived. The problem is that Azure Durable Functions is not yet supported in Python. Is it possible to use a C# Durable Function to orchestrate a Python Azure Function? Or does Microsoft recommend using the preview Python Durable Functions (https://github.com/Azure/azure-functions-durable-python)? The documentation says that Python Durable Functions should have consumption plan support by May 2020.

答: Also, have you considered using Logic Apps as the orchestrator for your functions?   Seems like that would be a more rapid way to implement orchestration.</p>