问:
refreshing page after submitting form to display result of the action made
i think i have a problem in my code , i have page that displays a list of jobs available with two buttons one to show the job profile 'profile' and the second to apply for the job 'apply', the expected result when hitting apply is to have the applied job disappeared from the list of all available jobs. The code works just fine on localhost, but after uploading it to server, I have to refresh the page after clicking apply to see the result of the action made. This is the code of AvailableJobs.php:

```<code> <?php $sql1= "SELECT * FROM Job"; // select all the Job
$result1= mysqli_query($conn,$sql1);
while($row1=mysqli_fetch_array($result1))
{ $JobName= $row1['JobName'];
    $JID= $row1['JobID'];
    $OrgID= $row1['OrgID']; // get the Org ID for the available Job

$sql10=" SELECT * FROM JobStudent WHERE JobID='$JID' AND StudentID='$SID'";
$resultss = mysqli_query($conn,$sql10);
$numResults = mysqli_fetch_array($resultss);
if ($numResults == 0) {

 $sql2="SELECT * FROM RequestedOrganization WHERE OrgID='$OrgID'";
$result2= mysqli_query($conn,$sql2);
  while($row2=mysqli_fetch_array($result2))
{ $OrgGPA= $row2['GPA'];
    $OrgTrack= $row2['Track'];
    $Priority= $row2['priorityGT'];
}
 ?>
<li><input disabled style="border:none; margin-bottom: 10px; width:100%;" name="JobName" value="<?php echo $row1['JobName'];?>"> </li> <?php
 echo "<form action='AvailableJobAction_page.php' method='POST'>
<input type='hidden' name='tempId' value='$JID'/>
<input style='border-radius: 12px; margin-bottom: 10px; background-color: #ccc;' type='submit' class='right' name='submit-btn' value='Apply' onclick='return func1()'/>
</form>";
echo "<form action='OrgProfileSS.php' method='POST'>
<input type='hidden' name='temppId' value='$JID'/>
<input type='hidden' name='tempppId' value='$OrgID'/>
<input style='border-radius: 12px; background-color: #ccc;' type='submit' name='submit-btnn' class='right' value='Profile'/>
</form><br/>"; ?>
</code>```

this is the execute page AvailableJobAction_page.php:

```<code>$USER=$_SESSION['login_user'];

if (isset($_POST['submit-btn'])){
$Jobid=$_POST['tempId'];  // J ID

$Sql="SELECT * FROM Job WHERE JobID='$Jobid'";
$Result2= mysqli_query($conn,$Sql);
while ( $Row1 =mysqli_fetch_array($Result2)){
$JN= $Row1['JobName'];
$orgid= $Row1['OrgID'];

$Sql10="SELECT * FROM Employer WHERE EmployerID='$orgid'";
$Result10= mysqli_query($conn,$Sql10);
while ( $Row10 =mysqli_fetch_array($Result10)){
$EmpEmail= $Row10['EmailAccount'];
}

}

$sql="SELECT * FROM Student WHERE KsuEmailStuent='$USER'"; // Get S ID
$result2= mysqli_query($conn,$sql);
while ( $row1 =mysqli_fetch_array($result2)){
$StID= $row1['StudentID'];
}

$sql4="SELECT * FROM JobStudent WHERE StudentID='$StID' AND JobID='$Jobid'";
$result4= mysqli_query($conn,$sql4);
$rows= mysqli_num_rows($result4);
if ($rows>0){
echo "<script type='text/javascript'>alert('You Already Applied before!')</script>";
echo "<script>window.location.href='AvailableJobs.php';</script>";
}else{
$sql4="INSERT INTO JobStudent (JobID,StudentID,Status) VALUES ('$Jobid','$StID','Pending')";
$result4= mysqli_query($conn,$sql4);

$sql1="SELECT * FROM Job WHERE JobID='$Jobid'";
$result1= mysqli_query($conn,$sql1);
while ( $row2 =mysqli_fetch_array($result1)){
$Nos= $row2['NoOfAppliedstudnets'];
}
$Nos++;
$sql3= "UPDATE Job SET NoOfstudnets='$Nos' WHERE JobID='$Jobid'";
$result3= mysqli_query($conn,$sql3);

$to =  $USER; // Send Email with the new Pass
$subject = "Applied done sucsessfully!";
$message = "Your request have been sent, Please wait for response from employer and note that you can view your request status in your account home";
$message = wordwrap($message,70);
//$headers = "From : Admin@PTN.com";
if(mail($to, $subject, $message)){
echo "<script type='text/javascript'>alert('Applied done sucsessfully!')</script>";
echo "<script>window.location.href='AvailableJobs.php';</script>";
}else{
echo "<script type='text/javascript'>alert('Erorr in send Email ')</script>";
echo "<script>window.location.href='AvailableJobs.php';</script>";
}

$to =  $EmpEmail; // Send Email with the new Pass
$subject = "New student have Applied!";
$message = "New student have Applied to this Job ".$JN ;
$message = wordwrap($message,70);
//$headers = "From : Admin@PTN.com";
mail($to, $subject, $message);
}
}
else echo "<script type='text/javascript'>alert('ERROR!')</script>";
</code>```

答:
change the code in the part :

```<code>$sql10=" SELECT * FROM JobStudent WHERE JobID='$JID' AND StudentID='$SID'";
$resultss = mysqli_query($conn,$sql10);
</code>```

change the check to first mysqli_num_rows  instead of mysqli_fetch_array

```<code>$numResults = mysqli_num_rows($resultss);
if ($numResults == 0) {
</code>```

Body:
i think i have a problem in my code , i have page that displays a list of jobs available with two buttons one to show the job profile 'profile' and the second to apply for the job 'apply', the expected result when hitting apply is to have the applied job disappeared from the list of all available jobs. The code works just fine on localhost, but after uploading it to server, I have to refresh the page after clicking apply to see the result of the action made. This is the code of AvailableJobs.php:

 <?php $sql1= "SELECT * FROM Job"; // select all the Job
$result1= mysqli_query($conn,$sql1);
while($row1=mysqli_fetch_array($result1))
{ $JobName= $row1['JobName'];
    $JID= $row1['JobID'];
    $OrgID= $row1['OrgID']; // get the Org ID for the available Job

$sql10=" SELECT * FROM JobStudent WHERE JobID='$JID' AND StudentID='$SID'";
$resultss = mysqli_query($conn,$sql10);
$numResults = mysqli_fetch_array($resultss);
if ($numResults == 0) {

 $sql2="SELECT * FROM RequestedOrganization WHERE OrgID='$OrgID'";
$result2= mysqli_query($conn,$sql2);
  while($row2=mysqli_fetch_array($result2))
{ $OrgGPA= $row2['GPA'];
    $OrgTrack= $row2['Track'];
    $Priority= $row2['priorityGT'];
}
 ?>

<input disabled style="border:none; margin-bottom: 10px; width:100%;" name="JobName" value="<?php echo $row1['JobName'];?>">
 <?php
 echo "<form action='AvailableJobAction_page.php' method='POST'>
<input type='hidden' name='tempId' value='$JID'/>
<input style='border-radius: 12px; margin-bottom: 10px; background-color: #ccc;' type='submit' class='right' name='submit-btn' value='Apply' onclick='return func1()'/>
</form>";
echo "<form action='OrgProfileSS.php' method='POST'>
<input type='hidden' name='temppId' value='$JID'/>
<input type='hidden' name='tempppId' value='$OrgID'/>
<input style='border-radius: 12px; background-color: #ccc;' type='submit' name='submit-btnn' class='right' value='Profile'/>
</form>
"; ?>

this is the execute page AvailableJobAction_page.php:

$USER=$_SESSION['login_user'];

if (isset($_POST['submit-btn'])){
$Jobid=$_POST['tempId'];  // J ID

$Sql="SELECT * FROM Job WHERE JobID='$Jobid'";
$Result2= mysqli_query($conn,$Sql);
while ( $Row1 =mysqli_fetch_array($Result2)){
$JN= $Row1['JobName'];
$orgid= $Row1['OrgID'];

$Sql10="SELECT * FROM Employer WHERE EmployerID='$orgid'";
$Result10= mysqli_query($conn,$Sql10);
while ( $Row10 =mysqli_fetch_array($Result10)){
$EmpEmail= $Row10['EmailAccount'];
}

}

$sql="SELECT * FROM Student WHERE KsuEmailStuent='$USER'"; // Get S ID
$result2= mysqli_query($conn,$sql);
while ( $row1 =mysqli_fetch_array($result2)){
$StID= $row1['StudentID'];
}

$sql4="SELECT * FROM JobStudent WHERE StudentID='$StID' AND JobID='$Jobid'";
$result4= mysqli_query($conn,$sql4);
$rows= mysqli_num_rows($result4);
if ($rows>0){
echo "";
echo "";
}else{
$sql4="INSERT INTO JobStudent (JobID,StudentID,Status) VALUES ('$Jobid','$StID','Pending')";
$result4= mysqli_query($conn,$sql4);

$sql1="SELECT * FROM Job WHERE JobID='$Jobid'";
$result1= mysqli_query($conn,$sql1);
while ( $row2 =mysqli_fetch_array($result1)){
$Nos= $row2['NoOfAppliedstudnets'];
}
$Nos++;
$sql3= "UPDATE Job SET NoOfstudnets='$Nos' WHERE JobID='$Jobid'";
$result3= mysqli_query($conn,$sql3);

$to =  $USER; // Send Email with the new Pass
$subject = "Applied done sucsessfully!";
$message = "Your request have been sent, Please wait for response from employer and note that you can view your request status in your account home";
$message = wordwrap($message,70);
//$headers = "From : Admin@PTN.com";
if(mail($to, $subject, $message)){
echo "";
echo "";
}else{
echo "";
echo "";
}

$to =  $EmpEmail; // Send Email with the new Pass
$subject = "New student have Applied!";
$message = "New student have Applied to this Job ".$JN ;
$message = wordwrap($message,70);
//$headers = "From : Admin@PTN.com";
mail($to, $subject, $message);
}
}
else echo "";

Body:
change the code in the part :

$sql10=" SELECT * FROM JobStudent WHERE JobID='$JID' AND StudentID='$SID'";
$resultss = mysqli_query($conn,$sql10);

change the check to first mysqli_num_rows  instead of mysqli_fetch_array

$numResults = mysqli_num_rows($resultss);
if ($numResults == 0) {


来源: stackexchange

问:
What is the best way to return duplicate values from a list on the same ListView row in the GetView() Method?
I have some data in a list that shows for example the Item Number, Line Number, Quantity, and Pack Size of an order. The problem is that some lines on the order will have the same item number but different quantities, pack sizes or both. For example :

```<code>Order#  Line#   Item#   Qty    Pack Size
100      1      12345   640     (10@64)
100      1      12345   128     (1@128)
100      2      23124    48     (1@48)
100      3      53425    80     (1@80)
</code>```

Shown above for item 12345 they have ordered a total of 768 pieces but for 640 of those pieces they would like to receive 10 packs containing 64 pieces each and they would like 128 of the pieces in just one pack. When the ListView is created naturally it will create 4 rows, one row for each of the rows in the list. I would like it to only show 3 rows one for each Item# and if there are duplicate items it should add the quantities and combine the pack sizes into one row. I have tried doing something like this trying to force it to do what i wanted but it obviously does not work that well. I am fairly new to Android and ListViews so I am hoping that there is a better way to accomplish this. Can anyone point me in the right direction?

```<code>    public class LoadInfoViewAdapter : BaseAdapter<Items>
{
    private List<Items> lItems;
    private Context gContext;
    private string gLoadnStop;
    private string gPacks;
    private decimal gtotal;
    int total;

    public LoadInfoViewAdapter(Context context, List<Items> loadinfo,  string LoadnStop)
    {
        lItems = loadinfo;
        gContext = context;
        gLoadnStop = LoadnStop;

    }

    public override int Count
    {
        get { return lItems.Count; }
    }
    public override long GetItemId(int position)
    {
        return position;
    }
    public override Items this[int position]
    {
        get { return lItems[position]; }
    }
    public override View GetView(int position, View convertView, ViewGroup parent)
    {
        View row = convertView;
        if (row == null)
        {
            row = LayoutInflater.From(gContext).Inflate(Resource.Layout.LoadInfoItems_Row, null);
        }
        //If the item at the current position is the same as the item in the next position add the qty and combine the packs
        if (lItems[position].ItemNo == lItems[position + 1].ItemNo)
        {
            string itemno = lItems[position].ItemNo;
            int count = 0;
            row.FindViewById<TextView>(Resource.Id.txtItemNo).Text = lItems[position].ItemNo.Trim();
            row.FindViewById<TextView>(Resource.Id.txtLineNo).Text = lItems[position].LineNum.Trim();
            foreach (var item in lItems.Where(r => r.ItemNo == itemno))
            {
                if (count == 0)
                {
                    gPacks = lItems[position].Pack.ToString().Trim();
                    gtotal = lItems[position].Qty;
                }
                else
                {
                    gPacks = lItems[position + 1].Pack.ToString().Trim() + ", " + gPacks;
                    gtotal = lItems[position + 1].Qty + gtotal;
                }
                count = +1;
            }
            row.FindViewById<TextView>(Resource.Id.txtQuantity).Text = gtotal + " (" + gPacks + ") ";
            gtotal = 0;
        }
        //check to see if the current item is was the same as the previous item added.  If so I dont want to create a row for that item.
        else if (lItems[position].ItemNo == lItems[position - 1].ItemNo)
        {
            //Not too sure what would be the best code to go here
        }
        //if it has no duplicate create the row like normal
        else
        {
            row.FindViewById<TextView>(Resource.Id.txtItemNo).Text = lItems[position].ItemNo.Trim();
            row.FindViewById<TextView>(Resource.Id.txtLineNo).Text = lItems[position].LineNum.Trim();
            row.FindViewById<TextView>(Resource.Id.txtQuantity).Text = lItems[position].Qty.ToString().Trim() + lItems[position].Pack.ToString().Trim();
        }
        return row;
    }
</code>```

I would like it to return something like this :

```<code>12345  1   768((10@64),(1@128))
23124  2   48(1@48)
53425  3   80(1@80)
</code>```

For whatever reason it will do what i was hoping for the duplicate item numbers but it sometimes duplicates a different item in the list like:

```<code>12345  1   768((10@64),(1@128))
23124  2   48(1@48)
53425  3   80(1@80)
23124  2   48(1@48)
</code>```

Anyone got any suggestions?

答:
Your fundamental issue is that the Items indexer is stating that you have 4 items available, but your desired result is 3 items.

This isn't really a task that you should be solving in your BaseAdapter.  You should be processing the list in advance and reducing to your target 3 items BEFORE passing it into your base adapter.

Also, you should try and avoid using FindViewFromId in GetView, unless the convertView is null.  In order to do this, you can pack the previously identified Views into the Tag property: that's what it's for, see https://blog.xamarin.com/creating-highly-performant-smooth-scrolling-android-listviews/

If you really want to do it all in your base adapter, then convert the items in the constructor, something like this:

```<code>public class LoadInfoViewAdapter : BaseAdapter<Items>
{
    private List<CondensedItems> cItems;
    private Context gContext;

    public LoadInfoViewAdapter(Context context, List<Items> loadinfo,  string LoadnStop)
    {
        gContext = context;
        gLoadnStop = LoadnStop;

        // Get all of the unique item numbers.
        var uniqueItemNos = loadInfo.Select(x => x.ItemNo).Distinct();

        cItems = new List<CondensedItem>();

        foreach(string uniqueItem in uniqueItemNos)
        {
            // Gets all of the items with the target itemNo.  If you want to avoid merging them all, you need to do some work checking for sequential indexes or something similar.
            var matchingItems = loadInfo.Select(x => x.ItemNo == uniqueItem).ToList();
            var lineNo = matchingItems[0].LineNo;
            var qty = matchingItems.Sum(x => x.Qty).ToString();

            StringBuilder packsSB = new StringBuilder();

            foreach(var item in matchingItems)
            {
                packs.Append(item.Pack + ",");
            }

            string packs = packsSB.ToString().Trim(',');

            cItems.Add(
                new CondensedItem
                {
                    ItemNo = uniqueItem,
                    LineNo = lineNo,
                    Packs = $"{qty}({packs})"
                });
        }
    }

    public override int Count
    {
        get { return cItems.Count; }
    }
    public override long GetItemId(int position)
    {
        return position;
    }
    public override Items this[int position]
    {
        get { return cItems[position]; }
    }
    public override View GetView(int position, View convertView, ViewGroup parent)
    {
        View row = convertView;
        CondensedViewHolder viewHolder;

        if (row == null)
        {
            row = LayoutInflater.From(gContext).Inflate(Resource.Layout.LoadInfoItems_Row, null);

            viewHolder = new CondensedViewHolder
            {
                ItemView = row.FindViewById<TextView>(Resource.Id.txtItemNo),
                LineView = row.FindViewById<TextView>(Resource.Id.txtLineNo),
                PacksView = row.FindViewById<TextView>(Resource.Id.txtQuantity)
            }

            row.Tag = viewHolder;
        }
        else
        {
            viewHolder = row.Tag as CondensedViewHolder;
        }

        viewHolder.ItemView.Text = cItems[position].ItemNo;
        viewHolder.LineView.Text = cItems[position].LineNo;
        viewHolder.PacksView.Text = cItems[position].Packs;

        return row;
    }

    private class CondensedItem
    {
        string ItemNo { get; set; }
        string LineNo { get; set; }
        string Packs { get; set; }
    }

    private class CondensedViewHolder : Java.Lang.Object
    {
        public TextView ItemView { get; set; }
        public TextView LineView { get; set; }
        public TextView PacksView { get; set; }
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have some data in a list that shows for example the Item Number, Line Number, Quantity, and Pack Size of an order. The problem is that some lines on the order will have the same item number but different quantities, pack sizes or both. For example :

Order#  Line#   Item#   Qty    Pack Size
100      1      12345   640     (10@64)
100      1      12345   128     (1@128)
100      2      23124    48     (1@48)
100      3      53425    80     (1@80)

Shown above for item 12345 they have ordered a total of 768 pieces but for 640 of those pieces they would like to receive 10 packs containing 64 pieces each and they would like 128 of the pieces in just one pack. When the ListView is created naturally it will create 4 rows, one row for each of the rows in the list. I would like it to only show 3 rows one for each Item# and if there are duplicate items it should add the quantities and combine the pack sizes into one row. I have tried doing something like this trying to force it to do what i wanted but it obviously does not work that well. I am fairly new to Android and ListViews so I am hoping that there is a better way to accomplish this. Can anyone point me in the right direction?

    public class LoadInfoViewAdapter : BaseAdapter<Items>
{
    private List<Items> lItems;
    private Context gContext;
    private string gLoadnStop;
    private string gPacks;
    private decimal gtotal;
    int total;

    public LoadInfoViewAdapter(Context context, List<Items> loadinfo,  string LoadnStop)
    {
        lItems = loadinfo;
        gContext = context;
        gLoadnStop = LoadnStop;

    }

    public override int Count
    {
        get { return lItems.Count; }
    }
    public override long GetItemId(int position)
    {
        return position;
    }
    public override Items this[int position]
    {
        get { return lItems[position]; }
    }
    public override View GetView(int position, View convertView, ViewGroup parent)
    {
        View row = convertView;
        if (row == null)
        {
            row = LayoutInflater.From(gContext).Inflate(Resource.Layout.LoadInfoItems_Row, null);
        }
        //If the item at the current position is the same as the item in the next position add the qty and combine the packs
        if (lItems[position].ItemNo == lItems[position + 1].ItemNo)
        {
            string itemno = lItems[position].ItemNo;
            int count = 0;
            row.FindViewById<TextView>(Resource.Id.txtItemNo).Text = lItems[position].ItemNo.Trim();
            row.FindViewById<TextView>(Resource.Id.txtLineNo).Text = lItems[position].LineNum.Trim();
            foreach (var item in lItems.Where(r => r.ItemNo == itemno))
            {
                if (count == 0)
                {
                    gPacks = lItems[position].Pack.ToString().Trim();
                    gtotal = lItems[position].Qty;
                }
                else
                {
                    gPacks = lItems[position + 1].Pack.ToString().Trim() + ", " + gPacks;
                    gtotal = lItems[position + 1].Qty + gtotal;
                }
                count = +1;
            }
            row.FindViewById<TextView>(Resource.Id.txtQuantity).Text = gtotal + " (" + gPacks + ") ";
            gtotal = 0;
        }
        //check to see if the current item is was the same as the previous item added.  If so I dont want to create a row for that item.
        else if (lItems[position].ItemNo == lItems[position - 1].ItemNo)
        {
            //Not too sure what would be the best code to go here
        }
        //if it has no duplicate create the row like normal
        else
        {
            row.FindViewById<TextView>(Resource.Id.txtItemNo).Text = lItems[position].ItemNo.Trim();
            row.FindViewById<TextView>(Resource.Id.txtLineNo).Text = lItems[position].LineNum.Trim();
            row.FindViewById<TextView>(Resource.Id.txtQuantity).Text = lItems[position].Qty.ToString().Trim() + lItems[position].Pack.ToString().Trim();
        }
        return row;
    }

I would like it to return something like this :

12345  1   768((10@64),(1@128))
23124  2   48(1@48)
53425  3   80(1@80)

For whatever reason it will do what i was hoping for the duplicate item numbers but it sometimes duplicates a different item in the list like:

12345  1   768((10@64),(1@128))
23124  2   48(1@48)
53425  3   80(1@80)
23124  2   48(1@48)

Anyone got any suggestions?

Body:
Your fundamental issue is that the Items indexer is stating that you have 4 items available, but your desired result is 3 items.

This isn't really a task that you should be solving in your BaseAdapter.  You should be processing the list in advance and reducing to your target 3 items BEFORE passing it into your base adapter.

Also, you should try and avoid using FindViewFromId in GetView, unless the convertView is null.  In order to do this, you can pack the previously identified Views into the Tag property: that's what it's for, see https://blog.xamarin.com/creating-highly-performant-smooth-scrolling-android-listviews/

If you really want to do it all in your base adapter, then convert the items in the constructor, something like this:

public class LoadInfoViewAdapter : BaseAdapter<Items>
{
    private List<CondensedItems> cItems;
    private Context gContext;

    public LoadInfoViewAdapter(Context context, List<Items> loadinfo,  string LoadnStop)
    {
        gContext = context;
        gLoadnStop = LoadnStop;

        // Get all of the unique item numbers.
        var uniqueItemNos = loadInfo.Select(x => x.ItemNo).Distinct();

        cItems = new List<CondensedItem>();

        foreach(string uniqueItem in uniqueItemNos)
        {
            // Gets all of the items with the target itemNo.  If you want to avoid merging them all, you need to do some work checking for sequential indexes or something similar.
            var matchingItems = loadInfo.Select(x => x.ItemNo == uniqueItem).ToList();
            var lineNo = matchingItems[0].LineNo;
            var qty = matchingItems.Sum(x => x.Qty).ToString();

            StringBuilder packsSB = new StringBuilder();

            foreach(var item in matchingItems)
            {
                packs.Append(item.Pack + ",");
            }

            string packs = packsSB.ToString().Trim(',');

            cItems.Add(
                new CondensedItem
                {
                    ItemNo = uniqueItem,
                    LineNo = lineNo,
                    Packs = $"{qty}({packs})"
                });
        }
    }

    public override int Count
    {
        get { return cItems.Count; }
    }
    public override long GetItemId(int position)
    {
        return position;
    }
    public override Items this[int position]
    {
        get { return cItems[position]; }
    }
    public override View GetView(int position, View convertView, ViewGroup parent)
    {
        View row = convertView;
        CondensedViewHolder viewHolder;

        if (row == null)
        {
            row = LayoutInflater.From(gContext).Inflate(Resource.Layout.LoadInfoItems_Row, null);

            viewHolder = new CondensedViewHolder
            {
                ItemView = row.FindViewById<TextView>(Resource.Id.txtItemNo),
                LineView = row.FindViewById<TextView>(Resource.Id.txtLineNo),
                PacksView = row.FindViewById<TextView>(Resource.Id.txtQuantity)
            }

            row.Tag = viewHolder;
        }
        else
        {
            viewHolder = row.Tag as CondensedViewHolder;
        }

        viewHolder.ItemView.Text = cItems[position].ItemNo;
        viewHolder.LineView.Text = cItems[position].LineNo;
        viewHolder.PacksView.Text = cItems[position].Packs;

        return row;
    }

    private class CondensedItem
    {
        string ItemNo { get; set; }
        string LineNo { get; set; }
        string Packs { get; set; }
    }

    private class CondensedViewHolder : Java.Lang.Object
    {
        public TextView ItemView { get; set; }
        public TextView LineView { get; set; }
        public TextView PacksView { get; set; }
    }
}


问:
Inject ILoggingFactory into Service library
I have a console application that I am using Serilog in.  I am trying to inject logging into my services library but I never see the log messages.  It seems when I step through the code that even though I am creating a Singleton LoggerFactory, the library is creating a new instance of the factory.

Console Application

```<code>ILoggerFactory loggerFactory = new LoggerFactory();
loggerFactory.AddSerilog(GetLoggerConfiguration());
_loggerIdentity = loggerFactory.CreateLogger<WorkerBroker>();

IServiceCollection services = new ServiceCollection();
services.TryAddSingleton<ILoggerFactory, LoggerFactory>();
_provider = services.BuildServiceProvider();

// Inject my service
var service = ActivatorUtilities.CreateInstance<MyService>(_provider);
</code>```

Constructor for Service where injection is occurring (in library)

```<code>public MyService(ILoggerFactory loggerFactory)
{
    _logger = loggerFactory.CreateLogger<WebCreditService>();
}
</code>```

Later in the Service I will try to log something and nothing shows in the log but I do see messages from the Console application.

答:
Try this:

// Add console logging
            serviceCollection.AddSingleton(new LoggerFactory()
                .AddConsole(configuration.GetSection("Logging"))
                .AddSerilog()
                .AddDebug());
            serviceCollection.AddLogging();

```<code>        // Add Serilog logging
        Log.Logger = new LoggerConfiguration()
            .WriteTo.RollingFile(configuration["Serilog:LogFile"])
            .ReadFrom.Configuration(configuration)
            .CreateLogger();
</code>```

But you have to consider configuration in appsettings file also.

Seen here:
https://www.codeproject.com/Articles/1218350/Elasticsearch-Kibana-and-Docker-using-NET-Standard

Body:
I have a console application that I am using Serilog in.  I am trying to inject logging into my services library but I never see the log messages.  It seems when I step through the code that even though I am creating a Singleton LoggerFactory, the library is creating a new instance of the factory.

Console Application

ILoggerFactory loggerFactory = new LoggerFactory();
loggerFactory.AddSerilog(GetLoggerConfiguration());
_loggerIdentity = loggerFactory.CreateLogger<WorkerBroker>();

IServiceCollection services = new ServiceCollection();
services.TryAddSingleton<ILoggerFactory, LoggerFactory>();
_provider = services.BuildServiceProvider();

// Inject my service
var service = ActivatorUtilities.CreateInstance<MyService>(_provider);

Constructor for Service where injection is occurring (in library)

public MyService(ILoggerFactory loggerFactory)
{
    _logger = loggerFactory.CreateLogger<WebCreditService>();
}

Later in the Service I will try to log something and nothing shows in the log but I do see messages from the Console application.

Body:
Try this:

// Add console logging
            serviceCollection.AddSingleton(new LoggerFactory()
                .AddConsole(configuration.GetSection("Logging"))
                .AddSerilog()
                .AddDebug());
            serviceCollection.AddLogging();

        // Add Serilog logging
        Log.Logger = new LoggerConfiguration()
            .WriteTo.RollingFile(configuration["Serilog:LogFile"])
            .ReadFrom.Configuration(configuration)
            .CreateLogger();

But you have to consider configuration in appsettings file also.

Seen here:
https://www.codeproject.com/Articles/1218350/Elasticsearch-Kibana-and-Docker-using-NET-Standard


问:
connecting to quickbooks database via odbc with php?
[edit]

We're collecting credit application data from users on a web form.

I have not tied my web form directly into QB.

I have no idea what the QB table structure is for this collection of data - nor of how it displays it to the user because I've never actually worked directly with QB.  Others in my office do however.

I would still appreciate any information about open source / free options.

I'll simplify the problem by removing the first desired option.

Let's just talk about importing a flat file into quickbooks.

I don't have a copy of quickbooks that I can play with, so I have no idea what options exist that are native to quickbooks but I see some chatter on the web about QB expecting an .ini file for imports.  (don't know the format that it expects yet, but I'll get that worked out later)

Please share your story if you have managed to import a flat file from mySQL into quickbooks or know of links that offer insight (I'm not finding much right now).

[end edit]

I realize that this scenario is probably uncommon, but I need to connect to an existing quickbooks database in one of two ways.

1) either directly from a php script running on our web site -- insert user supplied data directly from web to quickbooks.

or

2) put user's data directly into mySQL database and later export data from mySQL to quickbooks.

If the first option is viable, I would appreciate your thoughts on establishing an odbc connection to the quickbooks database.

can I go about it with something like:

```<code>try {
  $conn = @odbc_connect("DSNName", "", "", "SQL_CUR_USE_ODBC");
  // un and pw parameters are passed as empty strings since the DSN
  // has knowledge of the password already.
  // 4th parameter is optional

  $exec = @odbc_exec($conn, $insert) or die ("exec error");
  echo "success!";
}
catch (Exception $e) {
  echo $e->getMessage();
} // end try catch
</code>```

答: With QuickBooks Enterprise 2011 this changed, and you can have real ODBC access (although with limited rights and to a limited amount of tables) and then use an SQL tool to map via the ODBC access.</p>

ContentLicense: CC BY-SA 2.5

Body:
[edit]

We're collecting credit application data from users on a web form.

I have not tied my web form directly into QB.

I have no idea what the QB table structure is for this collection of data - nor of how it displays it to the user because I've never actually worked directly with QB.  Others in my office do however.

I would still appreciate any information about open source / free options.

I'll simplify the problem by removing the first desired option.

Let's just talk about importing a flat file into quickbooks.

I don't have a copy of quickbooks that I can play with, so I have no idea what options exist that are native to quickbooks but I see some chatter on the web about QB expecting an .ini file for imports.  (don't know the format that it expects yet, but I'll get that worked out later)

Please share your story if you have managed to import a flat file from mySQL into quickbooks or know of links that offer insight (I'm not finding much right now).

[end edit]

I realize that this scenario is probably uncommon, but I need to connect to an existing quickbooks database in one of two ways.

1) either directly from a php script running on our web site -- insert user supplied data directly from web to quickbooks.

or

2) put user's data directly into mySQL database and later export data from mySQL to quickbooks.

If the first option is viable, I would appreciate your thoughts on establishing an odbc connection to the quickbooks database.

can I go about it with something like:

try {
  $conn = @odbc_connect("DSNName", "", "", "SQL_CUR_USE_ODBC");
  // un and pw parameters are passed as empty strings since the DSN
  // has knowledge of the password already.
  // 4th parameter is optional

  $exec = @odbc_exec($conn, $insert) or die ("exec error");
  echo "success!";
}
catch (Exception $e) {
  echo $e->getMessage();
} // end try catch


问:
Java's FilterOutputStream adds a performance penalty

I have a piece of code that's splitting an output stream to two destinations.  They're both going to a file, but the second destination will go through a filter.  I'm trying to figure out why simply wrapping a FilterOutputStream without overriding any methods adds a huge performance penalty.

I created a file that's 358 megabytes:

```<code>dd if=/dev/zero of=dummyfile.txt count=700000 bs=512
</code>```

Ran this code against it:

```<code>private OutputStream getFilteredStream(OutputStream out1, OutputStream out2) {
    return new TeeOutputStream(out1, new FilterOutputStream(out2));
}
private OutputStream getDestination(String name) {
    return new BufferedOutputStream(new FileOutputStream(new File(name)));
}
...
InputStream in = new FileInputStream(new File("dummyfile.txt"));
OutputStream out = getFilteredStream(getDestination("dest1"), getDestination("dest2"));
long start = System.currentTimeMillis();
IOUtils.copy(in, out);
out.flush();
long end = System.currentTimeMillis();
System.err.println(((end - start) / 1000.0) + " seconds");
// close the files
</code>```

The result:

```<code>1.672 seconds
</code>```

If I remove the FilterOutputStream...

```<code>private OutputStream getFilteredStream(OutputStream out1, OutputStream out2) {
    return new TeeOutputStream(out1, out2);
}
</code>```

... and run it again, the result is:

```<code>0.797 seconds
</code>```

I am expecting a performance penalty when using a FilterOutputStream, but I am NOT expecting the penalty to be double, especially when not overriding any methods.  I looked at the source code for FilterOutputStream, but did not see anything that would cause such a huge penalty.

Can someone explain what might be causing this issue?

答:
It is slower because the default implementation in FilterOutputStream disables block processing and sends all bytes through the write(int b) method, one at a time.

This is documented:

Note that this method does not call the write method of its underlying input stream with the same arguments. Subclasses of FilterOutputStream should provide a more efficient implementation of this method.

Body:
I have a piece of code that's splitting an output stream to two destinations.  They're both going to a file, but the second destination will go through a filter.  I'm trying to figure out why simply wrapping a FilterOutputStream without overriding any methods adds a huge performance penalty.

I created a file that's 358 megabytes:

dd if=/dev/zero of=dummyfile.txt count=700000 bs=512

Ran this code against it:

private OutputStream getFilteredStream(OutputStream out1, OutputStream out2) {
    return new TeeOutputStream(out1, new FilterOutputStream(out2));
}
private OutputStream getDestination(String name) {
    return new BufferedOutputStream(new FileOutputStream(new File(name)));
}
...
InputStream in = new FileInputStream(new File("dummyfile.txt"));
OutputStream out = getFilteredStream(getDestination("dest1"), getDestination("dest2"));
long start = System.currentTimeMillis();
IOUtils.copy(in, out);
out.flush();
long end = System.currentTimeMillis();
System.err.println(((end - start) / 1000.0) + " seconds");
// close the files

The result:

1.672 seconds

If I remove the FilterOutputStream...

private OutputStream getFilteredStream(OutputStream out1, OutputStream out2) {
    return new TeeOutputStream(out1, out2);
}

... and run it again, the result is:

0.797 seconds

I am expecting a performance penalty when using a FilterOutputStream, but I am NOT expecting the penalty to be double, especially when not overriding any methods.  I looked at the source code for FilterOutputStream, but did not see anything that would cause such a huge penalty.

Can someone explain what might be causing this issue?


问:
Creating and installing Conda packages into Virtual Envs
I'm working on packaging up a suite of tools that can be installed in different environments, and I've run into many problems with dependencies, which are an issue since this package will be installed in air-gapped environments.

The package will be installed via Anaconda, and I have provided the installation script. In order to create the package, I ran the following command:

```<code>conda metapackage toolkit_bundle 0.0.1 --dependencies r-essentials tensorflow gensim spacy r-ggplot2 r-plotly r-dplyr r-rjson r-tm r-reshape2 r-shiny r-sparklyr r-slam r-nlp r-cluster r-ggvis r-plyr r-tidyr r-zoo r-magrittr r-xtable r-htmlwidgets r-formattable r-highcharter --summary "Toolkit Bundle"
</code>```

This produced a tar.bzip2 file that I held on to and tried to install via the conda command

```<code>conda install toolkit_bundle.tar.bz2
</code>```

The command seemed to run successfully, but I was unsuccessful in importing the modules in Python. I also tried creating a virtual conda environment and importing the package.

```<code>conda create -n myenv toolkit_bundle-0.0.1.tar.bz2
</code>```

There was no error, but none of the modules were able to be imported either.

Am I missing a step in this process, or is my thought process flawed?

Update:
It looks like my thinking was pretty flawed. A quick skim of the conda metapackage command documentation revealed the following:

```<code>Tool for building conda metapackages.  A metapackage is a package  with no  files,  only  metadata.  They are typically used to collect several packages together into a single package via dependencies.
</code>```

So my initial understanding was incorrect, and the package only contains metadata. Are there any other ideas for creating packages with dependencies resolved that can be installed in an air gapped environment?

答: I was able to download the packages I needed via the pypi website, and after determining the dependencies, I manually downloaded them and wrote a script to install them in the required order.</p>

Body:
I'm working on packaging up a suite of tools that can be installed in different environments, and I've run into many problems with dependencies, which are an issue since this package will be installed in air-gapped environments.

The package will be installed via Anaconda, and I have provided the installation script. In order to create the package, I ran the following command:

conda metapackage toolkit_bundle 0.0.1 --dependencies r-essentials tensorflow gensim spacy r-ggplot2 r-plotly r-dplyr r-rjson r-tm r-reshape2 r-shiny r-sparklyr r-slam r-nlp r-cluster r-ggvis r-plyr r-tidyr r-zoo r-magrittr r-xtable r-htmlwidgets r-formattable r-highcharter --summary "Toolkit Bundle"

This produced a tar.bzip2 file that I held on to and tried to install via the conda command

conda install toolkit_bundle.tar.bz2

The command seemed to run successfully, but I was unsuccessful in importing the modules in Python. I also tried creating a virtual conda environment and importing the package.

conda create -n myenv toolkit_bundle-0.0.1.tar.bz2

There was no error, but none of the modules were able to be imported either.

Am I missing a step in this process, or is my thought process flawed?

Update:
It looks like my thinking was pretty flawed. A quick skim of the conda metapackage command documentation revealed the following:

Tool for building conda metapackages.  A metapackage is a package  with no  files,  only  metadata.  They are typically used to collect several packages together into a single package via dependencies.

So my initial understanding was incorrect, and the package only contains metadata. Are there any other ideas for creating packages with dependencies resolved that can be installed in an air gapped environment?


问:
How to install npgsql for c++ in Visual Studio 2017
sorry if this is too simple to be of help to most people.

This is the first time I have done anything remotely like this and it appears that my problem is too unadvanced to be covered in any documentation.
I am trying to connect a c++ project in Visual Studio 2017 to a PostgreSQL database.
Just to be clear, I know how to run pgAdmin/host databases, code in C++, and I think I could handle the npgsql syntax if I got it working.
However, I've never used .NET (although 4.5 is on my computer).

Here's what I am doing:

I start an empty project for C++ in Visual Studio 2017.

I open nuget manager and search npgsql, but my project is pointing to native,v0.0 instead of a .NET framework.

So I target v4.5 in the .NET framework property, but that doesn't change anything.

Could someone please tell if what I am trying to do is possible?

Should I be using a different project other than empty project?

Does this need to be some kind of web application?

If it is possible I'd love any advice on how to do it.

答: If you are writing a native c++ program it is very unlikely you want to bring in a .net assembly. If you want to connect to a pg database I would suggest instead that you use the odbc driver (https://odbc.postgresql.org/) or perhaps there is some library available as part of PG, but using a .net assembly will require a great deal of unnecessary interop work.</p>


问:
How to find out the task dependency in apache spark
I understand that from Apache Spark you can find out dependency of among RDD inside stages by using spark history UI, like this:

From that DAG of RDD I know that: RDD number 36 can not start before finishing RDD number 33,34 and 35.

My question is: How can I find dependency among all tasks inside specific stage?

From the spark event logs and Spark history server UI I can get the start and end time of task, But I cant find how to get dependency between tasks.

答:
How can I find dependency among all tasks inside specific stage?

It is simple - tasks in a single stage are always independent. They can only depend on the results of another stage.


问:
Split Words in the comment text
I am trying to write a macro which will split the comment. My supervisor wants to prioritize the comments, e.g.:

Low : Comment 1

Medium : Comment 2

High: Comment 3

The output should be displayed in Excel with the following headings.
I was able to write a macro to export comments from Word to an Excel file, however I am struggling to add this code snippet to split the comment text.

```<code>Comment ID  |Page|  Section/Paragraph Name  |Comment Scope  |Comment text   |Priority   |Reviewer   |Comment Date|
1   |1| 1.1heading1|    example| heading|   Comment 1   |Low    |BlueDolphin    |1/1/1|
2|  2|  1.2heading  |example2   |Comment 2  |Medium|    BlueDolphin|    1/1/1|
3|  3   |1.3heading|    3example3|Comment 3 |High   |BlueDolphin    |1/1/1|
</code>```

Any help is much appreciated.

答: This looks pretty straightforward.  Just turn on the Macro Recorder, select the cells of interest, click Data > Text to Columns, and follow the prompts.  Turn off the Macro Recorder when done.  That's it.</p>

Title: Split Words in the comment text

Body:
I am trying to write a macro which will split the comment. My supervisor wants to prioritize the comments, e.g.:

Low : Comment 1

Medium : Comment 2

High: Comment 3

The output should be displayed in Excel with the following headings.
I was able to write a macro to export comments from Word to an Excel file, however I am struggling to add this code snippet to split the comment text.

Comment ID  |Page|  Section/Paragraph Name  |Comment Scope  |Comment text   |Priority   |Reviewer   |Comment Date|
1   |1| 1.1heading1|    example| heading|   Comment 1   |Low    |BlueDolphin    |1/1/1|
2|  2|  1.2heading  |example2   |Comment 2  |Medium|    BlueDolphin|    1/1/1|
3|  3   |1.3heading|    3example3|Comment 3 |High   |BlueDolphin    |1/1/1|

Any help is much appreciated.


问:
exception ToString(): debug versus release mode
regarding th stack trace depth in debug and release mode. I have come to the following conclusion (calling exception.ToString()):

at debug mode you get the complete stack trace with line numbers (several frames) at release mode instead complete stack trace you get only the throwing method in try block (single frame) with line numbers

-is that true ?
-is there any way to get the complete stack tracve on release mode ?

答:
When you run in Debug mode there is a Debugger attached with your application which gets the stack trace with the help of the .pdb (Programme Debug Database) file. Where as in release mode we dont have a pdb or a debugger so couldnt get the Stack trace with line numbers.

The Debug configuration of your program is compiled with full symbolic debug information and no optimization. Optimization complicates debugging, because the relationship between source code and generated instructions is more complex.

The Release configuration of your program contains no symbolic debug information and is fully optimized. Debug information can be generated in Program Database Files (C++), depending on the compiler options that are used. Creating PDB files can be very useful if you later have to debug your release version.


问:
How do I do a reverse to_i?
I'm using Ruby 2.4.  If there are numbers at the beginning of my string, I can get the value as an integer by doing

```<code>2.4.0 :003 >   s = "13s"
 => "13s"
2.4.0 :004 > s.to_i
 => 13
</code>```

However, how do I get the numbers as an integer if they are at the end of my string?  For instance, in

```<code>s13
</code>```

I have "13" at the end of the string, but obviously, .to_i won't extract that ...

```<code>2.4.0 :005 > s = "s13"
 => "s13"
2.4.0 :006 > s.to_i
 => 0
</code>```

What's a generic way of extracting the numerical portion of the end of a string?  IF the string is

```<code>abcd
</code>```

I'd expect the numerical portion to just be zero.

答:
One solution would be this one

```<code>"s13".reverse.to_i.to_s.reverse
</code>```

Or extract the digits from the end of the string

```<code>"s13"[/\d+\z/]
</code>```

Title: How do I do a reverse to_i?

Body:
I'm using Ruby 2.4.  If there are numbers at the beginning of my string, I can get the value as an integer by doing

2.4.0 :003 >   s = "13s"
 => "13s"
2.4.0 :004 > s.to_i
 => 13

However, how do I get the numbers as an integer if they are at the end of my string?  For instance, in

s13

I have "13" at the end of the string, but obviously, .to_i won't extract that ...

2.4.0 :005 > s = "s13"
 => "s13"
2.4.0 :006 > s.to_i
 => 0

What's a generic way of extracting the numerical portion of the end of a string?  IF the string is

abcd

I'd expect the numerical portion to just be zero.

Body:
One solution would be this one

"s13".reverse.to_i.to_s.reverse

Or extract the digits from the end of the string

"s13"[/\d+\z/]


问:
How can I add changing content to an automated mail (smtplib) in python 3.6.2?
I want to send a mail to myself. How can I change the content to a varying text rather than a static text?

```<code>import smtplib
import random
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

#food dictionary

food = random.choice([spaghetti, pizza])

def mail():

    email_user = 'me'
    email_send = ['no1','no2']

    msg = MIMEMultipart()
    msg['From'] = email_user
    msg['To'] = ','.join(email_send)
    msg['Subject'] = 'food for the week!'

    body = 'why can't I get my new content in here?!'
</code>```

this is the part (body=...) that I have troubles with I think. How can I put 'food' in there from the random.choice() part and not get an error message? Or is there a better way altogether?

```<code>msg.attach(MIMEText(body,'plain'))
text = msg.as_string()
mail =smtplib.SMTP("smtp.gmail.com", 587)
mail.ehlo()
mail.starttls()
mail.login(email_user,"pwd")
mail.sendmail(email_user,email_send, text)
mail.close()
mail()
</code>```

答:
By passing the function a value to be used. Also note, function definition should be before they are used.</p>

```<code>import smtplib
import random
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

def mail(food):

    email_user = 'me'
    email_send = ['no1','no2']

    msg = MIMEMultipart()
    msg['From'] = email_user
    msg['To'] = ','.join(email_send)
    msg['Subject'] = 'food for the week!'

    body = food
    msg.attach(MIMEText(body,'plain'))

    text = msg.as_string()

    mail =smtplib.SMTP("smtp.gmail.com", 587)

    mail.ehlo()

    mail.starttls()

    mail.login(email_user,"pwd")

    mail.sendmail(email_user,email_send, text)

    mail.close()

    mail()
#food dictionary

food = random.choice([spaghetti, pizza])
mail(food)
</code>```

Body:
I want to send a mail to myself. How can I change the content to a varying text rather than a static text?

import smtplib
import random
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

#food dictionary

food = random.choice([spaghetti, pizza])

def mail():

    email_user = 'me'
    email_send = ['no1','no2']

    msg = MIMEMultipart()
    msg['From'] = email_user
    msg['To'] = ','.join(email_send)
    msg['Subject'] = 'food for the week!'

    body = 'why can't I get my new content in here?!'

this is the part (body=...) that I have troubles with I think. How can I put 'food' in there from the random.choice() part and not get an error message? Or is there a better way altogether?

msg.attach(MIMEText(body,'plain'))
text = msg.as_string()
mail =smtplib.SMTP("smtp.gmail.com", 587)
mail.ehlo()
mail.starttls()
mail.login(email_user,"pwd")
mail.sendmail(email_user,email_send, text)
mail.close()
mail()

Body:
By passing the function a value to be used. Also note, function definition should be before they are used.

import smtplib
import random
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

def mail(food):

    email_user = 'me'
    email_send = ['no1','no2']

    msg = MIMEMultipart()
    msg['From'] = email_user
    msg['To'] = ','.join(email_send)
    msg['Subject'] = 'food for the week!'

    body = food
    msg.attach(MIMEText(body,'plain'))

    text = msg.as_string()

    mail =smtplib.SMTP("smtp.gmail.com", 587)

    mail.ehlo()

    mail.starttls()

    mail.login(email_user,"pwd")

    mail.sendmail(email_user,email_send, text)

    mail.close()

    mail()
#food dictionary

food = random.choice([spaghetti, pizza])
mail(food)


问:
Long Press InkResponse not working when using Container with Decoration
Long Press InkResponse not working when using Container with Decoration

https://github.com/flutter/flutter/issues/13421

```<code>return new Container(
      color: Colors.white,
      padding: new EdgeInsets.all(16.0),
      child: new Column(
</code>```

or

```<code>return new Container(
      decoration: new BoxDecoration(
        color: Colors.white,
      ),
      padding: new EdgeInsets.all(16.0),
      child: new Column(
</code>```

(both are identical)

If I comment color, everything goes back to normal.

It is the same for image property.

But not for the border property.

I placed a GestureDetector over Container to see if the gestures are detected,
there was no problem with the detection, its just the long press animations that are not working.

I could also confirm this without using the GestureDetector, I can Hear the Tapping Sound from the Emulator when doing a long press or a tap.

Temporary Workaround is to use Scaffold

```<code>return new Scaffold(
      backgroundColor: Colors.white,
      body: new Container(
        padding: new EdgeInsets.all(16.0),
        child: new Column(
</code>```

答:
This is what the docs say:

The InkResponse widget must have a Material widget as an ancestor. The
  Material widget is where the ink reactions are actually painted. This
  matches the material design premise wherein the Material is what is
  actually reacting to touches by spreading ink.

So I added a Material ancestor to the Container.

```<code>new Material(
      color: Colors.white,
      child: new Container(
        padding: new EdgeInsets.all(16.0),
        child: new Column(
</code>```

Body:
Long Press InkResponse not working when using Container with Decoration

https://github.com/flutter/flutter/issues/13421

return new Container(
      color: Colors.white,
      padding: new EdgeInsets.all(16.0),
      child: new Column(

or

return new Container(
      decoration: new BoxDecoration(
        color: Colors.white,
      ),
      padding: new EdgeInsets.all(16.0),
      child: new Column(

(both are identical)

If I comment color, everything goes back to normal.

It is the same for image property.

But not for the border property.

I placed a GestureDetector over Container to see if the gestures are detected,
there was no problem with the detection, its just the long press animations that are not working.

I could also confirm this without using the GestureDetector, I can Hear the Tapping Sound from the Emulator when doing a long press or a tap.

Temporary Workaround is to use Scaffold

return new Scaffold(
      backgroundColor: Colors.white,
      body: new Container(
        padding: new EdgeInsets.all(16.0),
        child: new Column(

Body:
This is what the docs say:

The InkResponse widget must have a Material widget as an ancestor. The
  Material widget is where the ink reactions are actually painted. This
  matches the material design premise wherein the Material is what is
  actually reacting to touches by spreading ink.

So I added a Material ancestor to the Container.

new Material(
      color: Colors.white,
      child: new Container(
        padding: new EdgeInsets.all(16.0),
        child: new Column(


问:
Maven pom.xml plugin not found. Screenshot attached
screenshot

All the dependencies and plugins in my project were resolved when I was using my old computer. Today I had to switch to the new one, reinstall all the programs and clone the project from git again. Right now I'm kinda baffled on how to solve this issue.
I've tried reimporting the project, invalidating caches and restarting IntelliJ Idea, performing mvn clean install -U, mvn clean install.
Still.

答:
There are a couple of possibilities for this to happen:

Do you by chance have a custom settings.xml (mostly found in ~/.m2 folder) file pointing to another maven repository than maven central?

Versions of the plugins are unavailable or wrong?

Internet connectivity :-)

My guess is that your "old" computer had a custom settings.xml file which is not present on your new computer (yet)...


问:
linear search on array of object c++
i have a problem with a function ..
I want the function to have two arguments ..
one will be a array of objects and the second one will be the code given by the user
and into the function to run a linear search and check if the user's code exists and if the code exists will return his position in the array else returns -1...

this is what i have try already:

```<code>int passwdSearch(Eidos pinPro[], int pass)
{
int i=0;
bool found;
found=false;
while(i<N && found==false)
{
    if(pinPro[i].getPasswd()==pass)
    {
        found=true;
        return i;
    }
    else
        return -1;
    i++;

}
</code>```

}

i want the function return the position if password exist else return symbolic number -1

The problem is that the code return position only for the first element of array and for the 4 others element function return -1

答:
Try this:</p>

```<code>int passwdSearch(Eidos pinPro[], int pass)
{
    for(int i=0; i<N; i++)
    {
        if(pinPro[i].getPasswd()==pass)
            return i;
    }
    return -1;
}
</code>```

Title: linear search on array of object c++

Body:
i have a problem with a function ..
I want the function to have two arguments ..
one will be a array of objects and the second one will be the code given by the user
and into the function to run a linear search and check if the user's code exists and if the code exists will return his position in the array else returns -1...

this is what i have try already:

int passwdSearch(Eidos pinPro[], int pass)
{
int i=0;
bool found;
found=false;
while(i<N && found==false)
{
    if(pinPro[i].getPasswd()==pass)
    {
        found=true;
        return i;
    }
    else
        return -1;
    i++;

}

}

i want the function return the position if password exist else return symbolic number -1

The problem is that the code return position only for the first element of array and for the 4 others element function return -1

Body:
Try this:

int passwdSearch(Eidos pinPro[], int pass)
{
    for(int i=0; i<N; i++)
    {
        if(pinPro[i].getPasswd()==pass)
            return i;
    }
    return -1;
}


问:
Running a Dockerized Selenium Grid on Jenkins
I'm trying to get my tests running in Jenkins. I have Dockerized my test runner code, and am using the Dockerized Selenium hub/grid. I can run everything fine locally on my machine and would like to do the same on a Jenkins server. All the containers are started using the docker shell commands, and they are all put on the same Docker network so they can communicate. Again, everything works fine locally, but when I try this on the Jenkins machine I get an error message saying:

Error forwarding the new session cannot find : Capabilities [{rotatable=false, ...

Since the exact same commands work locally the only reason I can think of why this fails is because the containers must be unable to communicate on the Jenkins machine. Perhaps they are started on another node or slave, I'm not sure. Does anyone have experience running multiple containers on a Jenkins machine? Or does anyone have any other ideas of why this is failing?

答: if you are using Jenkins Container Have Jenkins connect to the Selenium-Hub container's internal IP directly,Not through local host or FQDN, </p>


问:
UISplitViewController in Mac apps?
Is it possible to use UISplitViewController in a Mac app?</p>

答:
No, it's part of UIKit and thus not available on Mac. You can use NSSplitView if you need a view with multiple panes, but it has a very different API.

Besides, the most significant feature of UISplitViewController (handling auto-rotation and hiding the master view in portrait mode) doesn't make much sense in a Mac app, as the screen never rotates.

Title: UISplitViewController in Mac apps?


问:
Prefetch related starting from a single object - geting first in second prefetch and count and order
I have 3 Models Product,Company Categories.

```<code>class Product(Meta):
    categories = models.ManyToManyField(Category)
    company = models.ForeignKey(Company, related_name='products', on_delete=models.CASCADE)
updated_at = models.DateTimeField(auto_now_add=False, auto_now=True)
</code>```

I need:

to get all the products of a company

show  the product first category

count the number products per company and show

order products by reverse updated_at

I start from:

```<code>1. Company.objects.get(pk=company_pk).prefetch_related('products')
</code>```

will give me an error, because get returns an object:

```<code>class CompanyProductListView(ListView):
 model = Company
 template_name_suffix = '_company_list'

def get_queryset(self):
    company_pk = self.kwargs.get('pk')
    return Company.objects.get(pk=company_pk).prefetch_related('products')
</code>```

get without prefetch works.

return Company.objects.filter(pk=company_pk).prefetch_related('products')

there is no error, but in template:

```<code> {% for company in company_list %}
        {{ company.name}}
    {% endfor %}
</code>```

I loop even is one, but doesn't show me anything.

Besides that I need to attach first category to each product, and count the number of products

I'm thinking on access something like this:

```<code>{{company.name}}

{% for product in company.products %}
   {{ product.name }}
   {{ product.category }}
</code>```

答:
This query will get a little complicated, but should help you solve your issue.

PS: I haven't tested this but should mostly work. Will take a deeper look once I get some more time.

First we get the company we want:

```<code>company = Company.objects.get(pk=company_pk)
</code>```

Then we fetch all the first categories for all products, it can be done by using this question as a guide:

```<code>first_categories = Category.objects.order_by('product__id', '-id').distinct('product__id')
</code>```

Now we use the first_categories to use to limit the amount of data we prefetch (giving this a different perspective, we will query the Product model instead of the Company model)

```<code>product_list = Products.objects.filter(company=company).prefetch_related(
    Prefetch('categories', queryset=first_categories)
)
</code>```

```<code>def get_queryset():
    company_pk = ...
    company = ...
    first_categories = ...
    product_list = ...
    return product_list
</code>```

Body:
I have 3 Models Product,Company Categories.

class Product(Meta):
    categories = models.ManyToManyField(Category)
    company = models.ForeignKey(Company, related_name='products', on_delete=models.CASCADE)
updated_at = models.DateTimeField(auto_now_add=False, auto_now=True)

I need:

to get all the products of a company

show  the product first category

count the number products per company and show

order products by reverse updated_at

I start from:

1. Company.objects.get(pk=company_pk).prefetch_related('products')

will give me an error, because get returns an object:

class CompanyProductListView(ListView):
 model = Company
 template_name_suffix = '_company_list'

def get_queryset(self):
    company_pk = self.kwargs.get('pk')
    return Company.objects.get(pk=company_pk).prefetch_related('products')

get without prefetch works.

return Company.objects.filter(pk=company_pk).prefetch_related('products')

there is no error, but in template:

 {% for company in company_list %}
        {{ company.name}}
    {% endfor %}

I loop even is one, but doesn't show me anything.

Besides that I need to attach first category to each product, and count the number of products

I'm thinking on access something like this:

{{company.name}}

{% for product in company.products %}
   {{ product.name }}
   {{ product.category }}

Body:
This query will get a little complicated, but should help you solve your issue.

PS: I haven't tested this but should mostly work. Will take a deeper look once I get some more time.

First we get the company we want:

company = Company.objects.get(pk=company_pk)

Then we fetch all the first categories for all products, it can be done by using this question as a guide:

first_categories = Category.objects.order_by('product__id', '-id').distinct('product__id')

Now we use the first_categories to use to limit the amount of data we prefetch (giving this a different perspective, we will query the Product model instead of the Company model)

product_list = Products.objects.filter(company=company).prefetch_related(
    Prefetch('categories', queryset=first_categories)
)

def get_queryset():
    company_pk = ...
    company = ...
    first_categories = ...
    product_list = ...
    return product_list


问:
For ALB - is there an equivalent of fail2ban?
ALB (Application Load Balancing) is a layer 7 load balancer on AWS ELB.

For ALB - is there an equivalent of fail2ban which can prevent DDoS attacks?

答: Have you checked out AWS WAF? Not part of ALB per se, but may meet the goal.</p>


问:
SWIFT 4 nested JSON Struct - Codable
I'm having issues creating a struct to parse JSON in Swift 4. I'm able to parse small JSONs and JSONDecoder seems to work fine. Just need help to create a struct to parse JSON like that:

```<code>{
    "main": {
        "solutions": [
                    {
                    "exersises": [
                                     {
                                     "book_title": "test",
                                     "release_date": "2015-01-12T11:00",
                                     "price": 100,
                                     "additional": [
                                                   {
                                                   "item1": "test",
                                                   "item2": "test",
                                                   "number": 1
                                                   },
                                                   {
                                                    "item1": "test2",
                                                    "item2": "test2",
                                                    "number": 2
                                                   }
                                                   ],
                                     "availability": "Yes",
                                     "item_id": 43534
                                     }
                                     ]

                    }

                    ]
    }
}
</code>```

What kind of struct do I need to get to value of book_title for example?

答:
Its really easy. Your main probem is most likely root element. Let me get first layer or two for you.

```<code>let decoded = try JSONDecoder().decode(MainJSON.self, from: data)

class MainJSON: Codable {
    var main:SolutionJSON?
}

class SolutionJSON: Codable {
    var exercises:[ExercisesJSON]?
}

class ExercisesJSON: Codable {
    var bookTitle: String?
    var releaseDate: String?
    var price: Double?
    ... etc

    enum CodingKeys: String, CodingKey {
        case bookTitle = "book_title"
        case releaseDate = "release_date"
        case price = "price"
    }
}
</code>```

ExerciseJSON also uses Codable interface which lets remap json properties into swift properties if they don't match. Hope this helps.

Title: SWIFT 4 nested JSON Struct - Codable

Body:
I'm having issues creating a struct to parse JSON in Swift 4. I'm able to parse small JSONs and JSONDecoder seems to work fine. Just need help to create a struct to parse JSON like that:

{
    "main": {
        "solutions": [
                    {
                    "exersises": [
                                     {
                                     "book_title": "test",
                                     "release_date": "2015-01-12T11:00",
                                     "price": 100,
                                     "additional": [
                                                   {
                                                   "item1": "test",
                                                   "item2": "test",
                                                   "number": 1
                                                   },
                                                   {
                                                    "item1": "test2",
                                                    "item2": "test2",
                                                    "number": 2
                                                   }
                                                   ],
                                     "availability": "Yes",
                                     "item_id": 43534
                                     }
                                     ]

                    }

                    ]
    }
}

What kind of struct do I need to get to value of book_title for example?

Body:
Its really easy. Your main probem is most likely root element. Let me get first layer or two for you.

let decoded = try JSONDecoder().decode(MainJSON.self, from: data)

class MainJSON: Codable {
    var main:SolutionJSON?
}

class SolutionJSON: Codable {
    var exercises:[ExercisesJSON]?
}

class ExercisesJSON: Codable {
    var bookTitle: String?
    var releaseDate: String?
    var price: Double?
    ... etc

    enum CodingKeys: String, CodingKey {
        case bookTitle = "book_title"
        case releaseDate = "release_date"
        case price = "price"
    }
}

ExerciseJSON also uses Codable interface which lets remap json properties into swift properties if they don't match. Hope this helps.

ContentLicense: CC BY-SA 4.0


问:
AJAX Permission Denied On IE?
I'm trying to make an ajax call to an external domain that is already allowing external requests by sending Access-Control-Allow-Origin:* header, but i get Permission Denied on the xmlhttp.post() line.

Here is my code:

```<code>var xmlhttp;
try {
    xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
    try {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (E) {
        xmlhttp = false;
    }
}

if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
    try {
        xmlhttp = new XMLHttpRequest();
    } catch (e) {
        xmlhttp = false;
    }
}

xmlhttp.onreadystatechange = function () {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        alert(xmlhttp.responseText);
    }
}

xmlhttp.open("GET", "http://www.domain.com", true);
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlhttp.send();
</code>```

答: I believe that in IE, you still can't use XMLHttpRequest for cross domain requests. For that, you need to use XDomainRequest object. Full documentation is here. I believe the reason for introducing the separate object was to allow developers to do a compatibility test before making a request that certainly would fail with older browsers.

Title: AJAX Permission Denied On IE?

Body:
I'm trying to make an ajax call to an external domain that is already allowing external requests by sending Access-Control-Allow-Origin:* header, but i get Permission Denied on the xmlhttp.post() line.

Here is my code:

var xmlhttp;
try {
    xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
    try {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (E) {
        xmlhttp = false;
    }
}

if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
    try {
        xmlhttp = new XMLHttpRequest();
    } catch (e) {
        xmlhttp = false;
    }
}

xmlhttp.onreadystatechange = function () {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        alert(xmlhttp.responseText);
    }
}

xmlhttp.open("GET", "http://www.domain.com", true);
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlhttp.send();


问:
Match ids and on ng-mouseenter change border colour of elements with same id
I have dart image being generated in one controller which has a unique id

```<code>event.img = angular.element(`
      <div class= "your-container">
        <img src="${getDartImage(event)}"
              ng-mouseenter="$ctrl.clicker(${event.id})" class="dart">
      </div>`);
event.img = $compile(event.img)($scope);
</code>```

I also have a div being generated in another controller which also has a unique id.

```<code><scheduled-event
    event="event"
    ng-repeat="event in $ctrl.adherence.events"
    ng-mouseenter="$ctrl.clicker1($ctrl.adherence.events[$index].id)">
</scheduled-event>
</code>```

I want to match these ids and when I do a ng-mouseeenter on one element, lets say a dart, the div border - colour with the matching id changes.

答:
You can do this with the help of ng-class. When you enter the element, just trigger the mouseenter function and set the flag to the selected Id and check if the id entered is the same as the id set in the flag.

HTML:

```<code> <scheduled-event

    event="event"
    ng-repeat="event in $ctrl.adherence.events"
    ng-mouseenter="$ctrl.clicker1($ctrl.adherence.events[$index].id)"
    ng-class="{'bd-col':$ctrl.selectedId==$ctrl.adherence.events[$index].id}">

</scheduled-event>
</code>```

JS:

```<code>this.clicker1=function(id){
  this.selectedId=id;
}
</code>```

CSS:

```<code>.bd-col{
 border-color: #444;
}
</code>```

Body:
I have dart image being generated in one controller which has a unique id

event.img = angular.element(`

`);
event.img = $compile(event.img)($scope);

I also have a div being generated in another controller which also has a unique id.

<scheduled-event
    event="event"
    ng-repeat="event in $ctrl.adherence.events"
    ng-mouseenter="$ctrl.clicker1($ctrl.adherence.events[$index].id)">
</scheduled-event>

I want to match these ids and when I do a ng-mouseeenter on one element, lets say a dart, the div border - colour with the matching id changes.

Body:
You can do this with the help of ng-class. When you enter the element, just trigger the mouseenter function and set the flag to the selected Id and check if the id entered is the same as the id set in the flag.

HTML:

 <scheduled-event

    event="event"
    ng-repeat="event in $ctrl.adherence.events"
    ng-mouseenter="$ctrl.clicker1($ctrl.adherence.events[$index].id)"
    ng-class="{'bd-col':$ctrl.selectedId==$ctrl.adherence.events[$index].id}">

</scheduled-event>

JS:

this.clicker1=function(id){
  this.selectedId=id;
}

CSS:

.bd-col{
 border-color: #444;
}


问:
How to paginate once number of pages has been scraped? (Scrapy)
I'm trying to paginate through a review site that doesn't have hyperlinked pagination buttons. I've written logic to paginate and hardcoded the number of pages for each link. However, I'm wondering if it's possible to use information that I scrape as the number of pages for a given link in start_requests.

Spider code here (with 2 links to paginate through):

```<code>class TareviewsSpider(scrapy.Spider):
    name = 'tareviews'
    allowed_domains = ['tripadvisor.com']
    # start_urls = []

    def start_requests(self):
        for page in range(0,395,5):
            yield self.make_requests_from_url('https://www.tripadvisor.com/Hotel_Review-g60795-d102542-Reviews-or{}-Courtyard_Philadelphia_Airport-Philadelphia_Pennsylvania.html'.format(page))
        for page in range(0,1645,5):
            yield self.make_requests_from_url('https://www.tripadvisor.com/Hotel_Review-g60795-d122332-Reviews-or{}-The_Ritz_Carlton_Philadelphia-Philadelphia_Pennsylvania.html'.format(page))

    def parse(self, response):
        for idx,review in enumerate(response.css('div.review-container')):
            item = {
                'num_reviews': response.css('span.reviews_header_count::text')[0].re(r'\d{0,3}\,?\d{1,3}'),
                'hotel_name': response.css('h1.heading_title::text').extract_first(),
                'review_title': review.css('span.noQuotes::text').extract_first(),
                'review_body': review.css('p.partial_entry::text').extract_first(),
                'review_date': review.xpath('//*[@class="ratingDate relativeDate"]/@title')[idx].extract(),
                'num_reviews_reviewer': review.css('span.badgetext::text').extract_first(),
                'reviewer_name': review.css('span.scrname::text').extract(),
                'bubble_rating': review.xpath("//div[contains(@class, 'reviewItemInline')]//span[contains(@class, 'ui_bubble_rating')]/@class")[idx].re(r'(?<=ui_bubble_rating bubble_).+?(?=0)')
            }
            yield item
</code>```

'num_reviews' is the value for the number of the last page for each link. In the for loop in start_requests it is 395 and 1645.

Is this possible? I'd like to avoid a headless browser if possible. Thanks!

答:
I made this code

I use normal url - without -or{} - to get page and find number of reviews.

Next I add -or{} to url - it can be in any place - to generate urls to pages with reviews.

And then I use for loop and Request() to get pages with reviews.

Reviews are parsed by different method - parse_reviews()

In code I use scrapy.crawler.CrawlerProcess() to run it without full project,

so everyone can easily run and test it.

It saves data in output.csv

```<code>import scrapy

class TareviewsSpider(scrapy.Spider):

    name = 'tareviews'
    allowed_domains = ['tripadvisor.com']

    start_urls = [ # without `-or{}`
        'https://www.tripadvisor.com/Hotel_Review-g60795-d102542-Reviews-Courtyard_Philadelphia_Airport-Philadelphia_Pennsylvania.html',
        'https://www.tripadvisor.com/Hotel_Review-g60795-d122332-Reviews-The_Ritz_Carlton_Philadelphia-Philadelphia_Pennsylvania.html',
    ]

    def parse(self, response):
        # get number of reviews
        num_reviews = response.css('span.reviews_header_count::text').extract_first()
        num_reviews = num_reviews[1:-1] # remove `( )`
        num_reviews = num_reviews.replace(',', '') # remove `,`
        num_reviews = int(num_reviews) # convert to integer
        print('num_reviews:', num_reviews, type(num_reviews))

        # create template to generate urls to pages with reviews
        url = response.url.replace('.html', '-or{}.html')
        print('template:', url)

        # add requests to list
        for offset in range(0, num_reviews, 5):
            print('url:', url.format(offset))
            yield scrapy.Request(url=url.format(offset), callback=self.parse_reviews)

    def parse_reviews(self, response):
        print('reviews')
        for idx,review in enumerate(response.css('div.review-container')):
            item = {
                'num_reviews': response.css('span.reviews_header_count::text')[0].re(r'\d{0,3}\,?\d{1,3}'),
                'hotel_name': response.css('h1.heading_title::text').extract_first(),
                'review_title': review.css('span.noQuotes::text').extract_first(),
                'review_body': review.css('p.partial_entry::text').extract_first(),
                'review_date': review.xpath('//*[@class="ratingDate relativeDate"]/@title')[idx].extract(),
                'num_reviews_reviewer': review.css('span.badgetext::text').extract_first(),
                'reviewer_name': review.css('span.scrname::text').extract(),
                'bubble_rating': review.xpath("//div[contains(@class, 'reviewItemInline')]//span[contains(@class, 'ui_bubble_rating')]/@class")[idx].re(r'(?<=ui_bubble_rating bubble_).+?(?=0)')
            }
            yield item

# --- run without project ---

import scrapy.crawler

c = scrapy.crawler.CrawlerProcess({
    "FEED_FORMAT": 'csv',
    "FEED_URI": 'output.csv',
})
c.crawl(TareviewsSpider)
c.start())
</code>```

BTW: to get page you need url

```<code> https://www.tripadvisor.com/g60795-d102542
 https://www.tripadvisor.com/g60795-d102542-or0
 https://www.tripadvisor.com/g60795-d102542-or5
</code>```

Other words in url are only for SEO - to get better position in Google search results.

Body:
I'm trying to paginate through a review site that doesn't have hyperlinked pagination buttons. I've written logic to paginate and hardcoded the number of pages for each link. However, I'm wondering if it's possible to use information that I scrape as the number of pages for a given link in start_requests.

Spider code here (with 2 links to paginate through):

class TareviewsSpider(scrapy.Spider):
    name = 'tareviews'
    allowed_domains = ['tripadvisor.com']
    # start_urls = []

    def start_requests(self):
        for page in range(0,395,5):
            yield self.make_requests_from_url('https://www.tripadvisor.com/Hotel_Review-g60795-d102542-Reviews-or{}-Courtyard_Philadelphia_Airport-Philadelphia_Pennsylvania.html'.format(page))
        for page in range(0,1645,5):
            yield self.make_requests_from_url('https://www.tripadvisor.com/Hotel_Review-g60795-d122332-Reviews-or{}-The_Ritz_Carlton_Philadelphia-Philadelphia_Pennsylvania.html'.format(page))

    def parse(self, response):
        for idx,review in enumerate(response.css('div.review-container')):
            item = {
                'num_reviews': response.css('span.reviews_header_count::text')[0].re(r'\d{0,3}\,?\d{1,3}'),
                'hotel_name': response.css('h1.heading_title::text').extract_first(),
                'review_title': review.css('span.noQuotes::text').extract_first(),
                'review_body': review.css('p.partial_entry::text').extract_first(),
                'review_date': review.xpath('//*[@class="ratingDate relativeDate"]/@title')[idx].extract(),
                'num_reviews_reviewer': review.css('span.badgetext::text').extract_first(),
                'reviewer_name': review.css('span.scrname::text').extract(),
                'bubble_rating': review.xpath("//div[contains(@class, 'reviewItemInline')]//span[contains(@class, 'ui_bubble_rating')]/@class")[idx].re(r'(?<=ui_bubble_rating bubble_).+?(?=0)')
            }
            yield item

'num_reviews' is the value for the number of the last page for each link. In the for loop in start_requests it is 395 and 1645.

Is this possible? I'd like to avoid a headless browser if possible. Thanks!

Body:
I made this code

I use normal url - without -or{} - to get page and find number of reviews.

Next I add -or{} to url - it can be in any place - to generate urls to pages with reviews.

And then I use for loop and Request() to get pages with reviews.

Reviews are parsed by different method - parse_reviews()

In code I use scrapy.crawler.CrawlerProcess() to run it without full project,

so everyone can easily run and test it.

It saves data in output.csv

import scrapy

class TareviewsSpider(scrapy.Spider):

    name = 'tareviews'
    allowed_domains = ['tripadvisor.com']

    start_urls = [ # without `-or{}`
        'https://www.tripadvisor.com/Hotel_Review-g60795-d102542-Reviews-Courtyard_Philadelphia_Airport-Philadelphia_Pennsylvania.html',
        'https://www.tripadvisor.com/Hotel_Review-g60795-d122332-Reviews-The_Ritz_Carlton_Philadelphia-Philadelphia_Pennsylvania.html',
    ]

    def parse(self, response):
        # get number of reviews
        num_reviews = response.css('span.reviews_header_count::text').extract_first()
        num_reviews = num_reviews[1:-1] # remove `( )`
        num_reviews = num_reviews.replace(',', '') # remove `,`
        num_reviews = int(num_reviews) # convert to integer
        print('num_reviews:', num_reviews, type(num_reviews))

        # create template to generate urls to pages with reviews
        url = response.url.replace('.html', '-or{}.html')
        print('template:', url)

        # add requests to list
        for offset in range(0, num_reviews, 5):
            print('url:', url.format(offset))
            yield scrapy.Request(url=url.format(offset), callback=self.parse_reviews)

    def parse_reviews(self, response):
        print('reviews')
        for idx,review in enumerate(response.css('div.review-container')):
            item = {
                'num_reviews': response.css('span.reviews_header_count::text')[0].re(r'\d{0,3}\,?\d{1,3}'),
                'hotel_name': response.css('h1.heading_title::text').extract_first(),
                'review_title': review.css('span.noQuotes::text').extract_first(),
                'review_body': review.css('p.partial_entry::text').extract_first(),
                'review_date': review.xpath('//*[@class="ratingDate relativeDate"]/@title')[idx].extract(),
                'num_reviews_reviewer': review.css('span.badgetext::text').extract_first(),
                'reviewer_name': review.css('span.scrname::text').extract(),
                'bubble_rating': review.xpath("//div[contains(@class, 'reviewItemInline')]//span[contains(@class, 'ui_bubble_rating')]/@class")[idx].re(r'(?<=ui_bubble_rating bubble_).+?(?=0)')
            }
            yield item

# --- run without project ---

import scrapy.crawler

c = scrapy.crawler.CrawlerProcess({
    "FEED_FORMAT": 'csv',
    "FEED_URI": 'output.csv',
})
c.crawl(TareviewsSpider)
c.start())

BTW: to get page you need url

 https://www.tripadvisor.com/g60795-d102542
 https://www.tripadvisor.com/g60795-d102542-or0
 https://www.tripadvisor.com/g60795-d102542-or5

Other words in url are only for SEO - to get better position in Google search results.


问:
C++ Beginner Algorithm Assignment
I've got an assignment, which sounds like this : "An archer has black and white arrows, and he can only shoot white ducks with white arrows and black ducks only with black arrows. The ducks come in groups, which grow in size like this : one, then two, then three, then five, eight, etc., so basically Fibonacci numbers. The ducks in those groups are ordered so that you won't find two ducks of the same colour near each other, and each group starts with a white duck(for example, for the group which has 5 ducks in it: white black white black white). The archer can only kill the ducks if he can kill the entire group."

Being given the number of white arrows(ka) and black arrows(kb) I must say how many groups has the archer killed and how many arrows of each type has he got left.

```<code>int ka, kb;
cin >> ka >> kb;

int total_rows{0};
for(int current_group{1}, previous_group{1}; ka+kb >= current_group; ++total_rows)
{
    //see which of the arrows he shoots
    for(int i=1; i <= current_group; ++i)
    {
        if(i%2 == 1)
            --ka;
        else
            --kb;
    }

    // swap the 2 fib numbers so we can get the next one
    swap(current_group, previous_group);

    current_group += previous_group;
}

cout << total_rows << ' ' << ka << ' ' << kb;
</code>```

If I typed, for example, 9 and 10, I should get 4,2,6. I'm getting something which has nothing to do with that...

答:
Maybe a slightly different approach on calculating how many arrows will be used, that the one you are using. As we know the ducks are alternating, this means that for the odd group you will need extra white arrow, otherwise the number used will be N/2 for each color

```<code>#include <iostream>

int next_group()
{
    static int prev = 0;
    static int next = 1;

    int res = prev + next;
    prev = next;
    next = res;

    return next;
}

int main()
{
    int white, black;
    std::cin >> white >> black;

    int groups = 0;
    while (true)
    {
        int n = next_group();
        int arrows = n % 2 == 0 ? n / 2 : (n - 1) / 2;

        if (n % 2 == 0)
        {
            if (arrows > white || arrows > black)
                break;
        }
        else
        {
            if (arrows + 1 > white || arrows > black)
                break;

            white--;
        }

        white -= arrows;
        black -= arrows;
        groups++;

    }

    std::cout
        << "Complete groups eliminated: " << groups
        << "\nWhite arrows left: " << white
        << "\nBlack arrows left: " << black
        << std::endl;

    system("pause");
    return 0;
}
</code>```

Title: C++ Beginner Algorithm Assignment

Body:
I've got an assignment, which sounds like this : "An archer has black and white arrows, and he can only shoot white ducks with white arrows and black ducks only with black arrows. The ducks come in groups, which grow in size like this : one, then two, then three, then five, eight, etc., so basically Fibonacci numbers. The ducks in those groups are ordered so that you won't find two ducks of the same colour near each other, and each group starts with a white duck(for example, for the group which has 5 ducks in it: white black white black white). The archer can only kill the ducks if he can kill the entire group."

Being given the number of white arrows(ka) and black arrows(kb) I must say how many groups has the archer killed and how many arrows of each type has he got left.

int ka, kb;
cin >> ka >> kb;

int total_rows{0};
for(int current_group{1}, previous_group{1}; ka+kb >= current_group; ++total_rows)
{
    //see which of the arrows he shoots
    for(int i=1; i <= current_group; ++i)
    {
        if(i%2 == 1)
            --ka;
        else
            --kb;
    }

    // swap the 2 fib numbers so we can get the next one
    swap(current_group, previous_group);

    current_group += previous_group;
}

cout << total_rows << ' ' << ka << ' ' << kb;

If I typed, for example, 9 and 10, I should get 4,2,6. I'm getting something which has nothing to do with that...

Body:
Maybe a slightly different approach on calculating how many arrows will be used, that the one you are using. As we know the ducks are alternating, this means that for the odd group you will need extra white arrow, otherwise the number used will be N/2 for each color

#include <iostream>

int next_group()
{
    static int prev = 0;
    static int next = 1;

    int res = prev + next;
    prev = next;
    next = res;

    return next;
}

int main()
{
    int white, black;
    std::cin >> white >> black;

    int groups = 0;
    while (true)
    {
        int n = next_group();
        int arrows = n % 2 == 0 ? n / 2 : (n - 1) / 2;

        if (n % 2 == 0)
        {
            if (arrows > white || arrows > black)
                break;
        }
        else
        {
            if (arrows + 1 > white || arrows > black)
                break;

            white--;
        }

        white -= arrows;
        black -= arrows;
        groups++;

    }

    std::cout
        << "Complete groups eliminated: " << groups
        << "\nWhite arrows left: " << white
        << "\nBlack arrows left: " << black
        << std::endl;

    system("pause");
    return 0;
}


问:
Spring Data JPA - How can I fetch data from a Date column using only month and day?
I have a simple Spring Data JPA project working with mysql and I need to fetch all registers that match the day and month. The column I need to filter is type Datetime.

```<code>1935-12-08 00:00:00
</code>```

If I want to do this in a db level it works fine:

```<code>SELECT * FROM my_database.event where event_date LIKE '%-12-08%';
</code>```

It treats the date as a string. Now I need to do this in my repository yet nothing seems to work. I tried the basic one:

```<code>List<Event> findByEventDateLike(
        @Param("eventDate") Date eventDate);
</code>```

but it says it returns an illegal argument exception since it is a Date object. I tried other combinations but apparently spring data jpa can't compare dates with partial information.

NOTE: To keep it clean I'm trying to avoid @Query sentences but if it is the only way to go, it is a valid answer.

How can I do it?

答:
The code below works for ZonedDateTime (startDate), don't have an opportunity to test against DateTime right now:

```<code>@Query("SELECT b FROM Box b " +
        "WHERE EXTRACT (day FROM b.startDate) = :dayOfMonth AND EXTRACT (month FROM b.startDate) = :month")
List<Box> findBoxWithParticularDayAndMonth(@Param("dayOfMonth") Integer dayOfMonth, @Param("month") Integer month);
</code>```

Usage:

```<code>List<Box> boxes = boxRepo.findBoxWithParticularDayAndMonth(22, 5);
</code>```

Body:
I have a simple Spring Data JPA project working with mysql and I need to fetch all registers that match the day and month. The column I need to filter is type Datetime.

1935-12-08 00:00:00

If I want to do this in a db level it works fine:

SELECT * FROM my_database.event where event_date LIKE '%-12-08%';

It treats the date as a string. Now I need to do this in my repository yet nothing seems to work. I tried the basic one:

List<Event> findByEventDateLike(
        @Param("eventDate") Date eventDate);

but it says it returns an illegal argument exception since it is a Date object. I tried other combinations but apparently spring data jpa can't compare dates with partial information.

NOTE: To keep it clean I'm trying to avoid @Query sentences but if it is the only way to go, it is a valid answer.

How can I do it?

Body:
The code below works for ZonedDateTime (startDate), don't have an opportunity to test against DateTime right now:

@Query("SELECT b FROM Box b " +
        "WHERE EXTRACT (day FROM b.startDate) = :dayOfMonth AND EXTRACT (month FROM b.startDate) = :month")
List<Box> findBoxWithParticularDayAndMonth(@Param("dayOfMonth") Integer dayOfMonth, @Param("month") Integer month);

Usage:

List<Box> boxes = boxRepo.findBoxWithParticularDayAndMonth(22, 5);


问:
How to read multiple Excel files and concatenate them into one Apache Spark DataFrame?
Recently I wanted to do Spark Machine Learning Lab from Spark Summit 2016.  Training video is here and exported  notebook is available here.

The dataset used in the lab can be downloaded from UCI Machine Learning Repository. It contains a set of readings from various sensors in a gas-fired power generation plant. The format is xlsx file with five sheets.

To use the data in the lab I needed to read all the sheets form the Excel file and to concatenate them into one Spark DataFrame. During the training they are using Databricks Notebook but I was using IntelliJ IDEA with Scala and evaluating the code in the console.

The first step was to save all the  Excel sheets into separate xlsx files named sheet1.xlxs, sheet2.xlsx etc. and put them into sheets directory.

How to read all the Excel files and concatenate them into one Apache Spark DataFrame?

答:
We need spark-excel library for this, can be obtained from

https://github.com/crealytics/spark-excel#scala-api

clone the git project from above github link and build using "sbt package"

Using Spark 2 to run the spark-shell

spark-shell --driver-class-path ./spark-excel_2.11-0.8.3.jar
  --master=yarn-client

Import the necessary

import org.apache.spark.sql._

  import org.apache.spark.sql.functions._

  val sqlContext = new SQLContext(sc)

Set excel doc path

val document = "path to excel doc"

Execute the below function for creating dataframe out of it

```<code>val dataDF = sqlContext.read
                          .format("com.crealytics.spark.excel")
                          .option("sheetName", "Sheet Name")
                          .option("useHeader", "true")
                          .option("treatEmptyValuesAsNulls", "false")
                          .option("inferSchema", "false")
                          .option("location", document)
                          .option("addColorColumns", "false")
                          .load(document)
</code>```

That's all! now you can perform the Dataframe operation on the dataDF object.

Body:
We need spark-excel library for this, can be obtained from

https://github.com/crealytics/spark-excel#scala-api

clone the git project from above github link and build using "sbt package"

Using Spark 2 to run the spark-shell

spark-shell --driver-class-path ./spark-excel_2.11-0.8.3.jar
  --master=yarn-client

Import the necessary

import org.apache.spark.sql._

  import org.apache.spark.sql.functions._

  val sqlContext = new SQLContext(sc)

Set excel doc path

val document = "path to excel doc"

Execute the below function for creating dataframe out of it

val dataDF = sqlContext.read
                          .format("com.crealytics.spark.excel")
                          .option("sheetName", "Sheet Name")
                          .option("useHeader", "true")
                          .option("treatEmptyValuesAsNulls", "false")
                          .option("inferSchema", "false")
                          .option("location", document)
                          .option("addColorColumns", "false")
                          .load(document)

That's all! now you can perform the Dataframe operation on the dataDF object.


问:
Write some "if-statement"
I want to write one script in "if-statement"

There are a lot of .html files in the ./simulations/ folder, and write end balance in the html files like this:

'end balance: 1000.00000000 (0.00%)'

'end balance: 19.21977440 (-98.08%)'

'end balance: 1135.80974233 (13.58%)'

I just want to find 'end balance: ....... (...%)'

if the end balance is 1000 or lower echo 'end balance 100 0r lwss', if it is higher, 'echo end balance bigger than 1000'.

like this:

if [ "$(egrep -n 'end balance: [0-9.]' ./simulations/*.html)" -gt 1000 ]; then
echo ' end balance bigger than 1000 '
else
echo ' end balance less than 1000 '
fi

答:
If you do:

```<code>egrep -n 'end balance: [0-9.]' <<< 'end balance: 1135.80974233 (13.58%)'
</code>```

You will get:

```<code>1:end balance: 1135.80974233 (13.58%)
</code>```

To compare number you must to have numbers on left and right, so I suggest below if-statement:

```<code>if (( $(grep -o 'end balance: [0-9]\{1,\}' ./simulations/*.html | awk '{print $3}') > 1000 ))
</code>```

If you want do this for every file in ./simulations/ you use a loop:

```<code>IFS=$'\n'
for i in "$( ls -1 ./simulations/ | grep html$ )"
do
    if (( $(grep -o 'end balance: [0-9]\{1,\}' "$i" | awk '{print $3}') > 1000 ))
    then
        echo "end balance bigger than 1000"
    else
        echo "end balance less than 1000"
    fi
done
</code>```

Below command:

```<code>grep -o 'end balance: [0-9]\{1,\}' <<< 'end balance: 1135.80974233 (13.58%)' | awk '{print $3}
</code>```

Will print now:
1135

Title: Write some "if-statement"

Body:
If you do:

egrep -n 'end balance: [0-9.]' <<< 'end balance: 1135.80974233 (13.58%)'

You will get:

1:end balance: 1135.80974233 (13.58%)

To compare number you must to have numbers on left and right, so I suggest below if-statement:

if (( $(grep -o 'end balance: [0-9]\{1,\}' ./simulations/*.html | awk '{print $3}') > 1000 ))

If you want do this for every file in ./simulations/ you use a loop:

IFS=$'\n'
for i in "$( ls -1 ./simulations/ | grep html$ )"
do
    if (( $(grep -o 'end balance: [0-9]\{1,\}' "$i" | awk '{print $3}') > 1000 ))
    then
        echo "end balance bigger than 1000"
    else
        echo "end balance less than 1000"
    fi
done

Below command:

grep -o 'end balance: [0-9]\{1,\}' <<< 'end balance: 1135.80974233 (13.58%)' | awk '{print $3}

Will print now:
1135