问:
Show total sales per author in woocommerce
I'm using wordpress and woocommerce on a site where I have users create accounts so that they can upload their own clothing designs, I then sell these products and for each sale of their design the specific user gets a cut of the sale. I am trying to show the number of sales for each user on my site but can't figure out how to. I just need to be able to call the products created by each user specifically and then get the total sales from each of those products, then combine them into a total sales number for each individual user... can anyone point me in the right direction??

I am able to get the total sales for a single product using the

<?php echo get_post_meta($post->ID, 'total_sales', true); ?>

but I have no idea how to get it for a specific for a user.

答: <?php echo wc_get_customer_total_spent($user_id); ?>


来源: stackexchange

问:
How to handle and manipulate large IDs with pandas?
I'm currently working with a database table that has an ID as primary key which can have up to 28 digits.
For my use case I need to manipulate some data points in this table (including the ID) and write it back to the db table.

Now, for the ID I need to increment it by one and I'm struggling to achieve this with pandas and windows.
Unfortunately and obviously, I cannot read and save the ID as plain integers in the dataframe.
Converting it to np.float64 beforehand seems to be completely messing up the values.

For example:
I'm manipulating the data point with ID 2021051800100770010113340000
If I convert the ID column to np.float64 by explicitly providing the dtype of this column,
the ID becomes 2021051800100769903675441152.0 which seems to be a completely different number to  be.
Also I don't know if incrementing the ID column by 1 is working since the result will be same as the number above.

Is there a way to this in a proper way? The last option to me would be to convert it to a string and then change the last substring of that string. But I don't feel this would be good and clean solution. Not mentioning that I'm not sure if I can write this back to the db in that form.

edit//

Based on this suggestion (https://stackoverflow.com/a/21591439/3856569)
I edited the ID column the following way:
df["ID"] = df["ID"].apply(int)

and then incrementing the number.

I get the following result:

2021051800100769903675441152

2021051800100769903675441153

So the increment seems to work now but I still see completely different numbers opposed which I was getting originally.

答:
Please bare with me to look at this problem from another angle. If we can understand how the ID is formed, we may be able to handle it differently, for example, the first 8 digits looks like a date, and if that is true, then any of your manipulation shouldn't modify those 8 digits unless your intention is to change the date. In this case, you can separate your ID (in str) into 2 parts.

20210518 / 00100770010113340000

Then now we only need to handle the second part which is still too large for np.int64. However, if you find out how it is formed, then perhaps you can further separate it and finally handle a number that can be handled by np.int64.

For example, would the ID be formed in this way?
20210518 / 001 / 007 / 7001011334 / 0000

If we can split it into segments of meaning, then we know which part we need to keep when manipulating (adding 1 in your case)

ContentLicense: CC BY-SA 4.0


问:
C# why LINQ string array Contains show false
my question is ABC006 is in testA, why Contains show false?
and testB  show true?</p>
```<code>public class Program
{
    public static void Main()
    {
        string[] testA = " ABC666,777".Split(',');
    Console.WriteLine(testA.Contains("ABC666"));
    string testB =" ABC666";
    Console.WriteLine( testB.Contains("ABC666"));

    }
}
</code>```

答: Because testA will contain the strings " ABC666" and "777", and not the string "ABC666" (note the extra space at the beginning of the first one).

Body:
my question is ABC006 is in testA, why Contains show false?
and testB  show true?

public class Program
{
    public static void Main()
    {
        string[] testA = " ABC666,777".Split(',');
    Console.WriteLine(testA.Contains("ABC666"));
    string testB =" ABC666";
    Console.WriteLine( testB.Contains("ABC666"));

    }
}


问:
Members removed from team still have custom model driven view visible
Working on powerapps.  Created multiple teams and views specific for each team.  I am able to share/assign a view to a team and only the members in that team can see that view. The issue is that when removing a member from a team, they can still see that view, but lack the access to actually see any records in that view.

Is there a way to prevent the removed user from even seeing that the view exists?

答: Is it shared to the business unit and the team perhaps? That could explain why a user still can see after being removed from a team but not from the business unit.</p>


问:
Azure Unzip automation
I am looking to do the following in Azure however I should point out that on my local machine I have no visual studio, no admin rights, no IT support and no tools (except SSMS) but I have a VERY strong drive to complete this work if its possible.

I have created an Azure blob which receives a file each day (zipped) from a 3rd party. I am looking to do the following:

1)Unzip the data in an automated fashion

2)Get the data into an Azure SQL database (already created) in an automated fashion

What I want to know is if this is possible to do using Azure alone or am I going to need admin rights / Visual Studio? If it is possible any directions that you could point me in would be greatly received!

Thanks

Dave

答:
Based on your description, one approach would be to create a Blob Triggered Azure Function through the Azure Portal (Visual Studio is not required), unzip/process the file and save desired data into Azure SQL. Moreover, considering the there is only one new file per day, prefer the Consumption Plan to optimize cost.

Find more details about Azure Function Blob Binding at https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-storage-blob.

Title: Azure Unzip automation


问:
Unity: Application keeps running in background although Application.runInBackground is false
I'm currently developing some Unity project(this is my first one, I'm not familiar with Unity) and what bothers me is that breakpoints are still hitting when I minimize Unity editor window although I have Application.runInBackground == false so the app should be suspended while in background, but it is not ! Only the UI gets frozen and music stops while the actual code is continue executing. So, I'm basically wondering if this is general behaviour or this only happens when you're running in editor to allow debugging and in release builds code execution stops ?

答: I had similar issues. I found that it is because I have an IDE attached to Unity and only then did this happen. When you switch to release mode, everything go as it's supposed to - debug mode in Unity.</p>


问:
System service or disable uninstalling?
Is it possible to write an Android Service that cannot be erased/disabled/uninstalled?

答: No. You can modify the firmware to include your application, and such applications can only be removed by replacing the whole firmware.</p>

ContentLicense: CC BY-SA 3.0

Title: System service or disable uninstalling?


问:
Laravel One to One relation error don't know why?
Error Showing

Symfony\Component\HttpFoundation\Response::setContent(): Argument #1 ($content) must be of type ?string, Illuminate\Database\Eloquent\Relations\HasOne given, called in G:\Laravel\practice-1\vendor\laravel\framework\src\Illuminate\Http\Response.php on line 72

User Model

```<code><?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function book()
    {
        # code...
        return $this->hasOne(Book::class);
    }
}

</code>```

Book Migration

```<code><?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateBooksTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('books', function (Blueprint $table) {
            $table->id();
            $table->integer('user_id')->unsigned();
            $table->string('title');
            $table->string('abut');
            $table->float('amount', 8, 2);
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('books');
    }
}

</code>```
```<code>Route::get('/user/{id}/book', function ($id) {
    return User::find($id)->book();
});
</code>```

I have no idea why I am seeing this error. I have also looked at the documentation but no help was found.

答:
Your definitions are good. But this statement:

```<code>return User::find($id)->book();
</code>```

returns a Illuminate\Database\Eloquent\Relations\HasOne object.

That is no valid content for a response. Try to change it to:

```<code>return User::find($id)->book;
</code>```

Body:
Error Showing

Symfony\Component\HttpFoundation\Response::setContent(): Argument #1 ($content) must be of type ?string, Illuminate\Database\Eloquent\Relations\HasOne given, called in G:\Laravel\practice-1\vendor\laravel\framework\src\Illuminate\Http\Response.php on line 72

User Model

<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function book()
    {
        # code...
        return $this->hasOne(Book::class);
    }
}

Book Migration

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateBooksTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('books', function (Blueprint $table) {
            $table->id();
            $table->integer('user_id')->unsigned();
            $table->string('title');
            $table->string('abut');
            $table->float('amount', 8, 2);
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('books');
    }
}

Route::get('/user/{id}/book', function ($id) {
    return User::find($id)->book();
});

I have no idea why I am seeing this error. I have also looked at the documentation but no help was found.

Body:
Your definitions are good. But this statement:

return User::find($id)->book();

returns a Illuminate\Database\Eloquent\Relations\HasOne object.

That is no valid content for a response. Try to change it to:

return User::find($id)->book;


问:
How to solve Unable to find item ID for item in application in Oracle Apex?
I have a public website made using Apex 21.1.3

When a user shares a page of my website, let's say on facebook, Facebook adds "?fbclickId=something" to the URL.

My app then crashes saying : Unable to find item ID for item fbclickId in application.

Apex thinks the user is trying to set an element that does not exist on the application.

I have url processing layer using htaccess that formats the urls before sending them to Apex in a reverse proxy. I could say let's ignore all what comes after a question mark "?" but in this case I wont be able to set any application item value neither. So that's not possible.

Does anyone have an idea how to make Apex ignore setting a parameter if it doesn't exist ?

Using google for example :

This URL https://www.google.com/?anyparameter=anyvalue will always resolve to https://www.google.com

Thanks

Cheers

答:
Here is the solution I came up with.

I couldn't find any way to ignore unavailable fields but found a trick to avoid sending them to Apex, hence escaping the error.

In the middle tier (nginx, apache, IIS) add the following logic :

Whenever there are two question marks, ignore the second one part:

```<code> For example   : someApexAppUrl?Parameter=value?fbclickid=something
 Should become : someApexAppUrl?Parameter=value
</code>```

Whenever there is a parameter added to the url for example

```<code> someApexAppUrl?Parameter=value
</code>```

Check the parameter name against

Application Items with a protection level of Unrestricted, Checksum Required - Application Level, Checksum Required - User Level, Checksum Required - Session Level

The hard coded list of the default Apex urls parameters which are : session, request, clear, debug, printerFriendly, trace, timezone, lang, territory, cs, dialogCs, x01 according to this article

Application page items with a name pattern P99_Someting

Whenever a parameter is not among these three categories, ignore it and don't send it to Apex. This way even if facebook adds something like ?fbclickid=xxx the Apex App will still work nicely.

Body:
Here is the solution I came up with.

I couldn't find any way to ignore unavailable fields but found a trick to avoid sending them to Apex, hence escaping the error.

In the middle tier (nginx, apache, IIS) add the following logic :

Whenever there are two question marks, ignore the second one part:

 For example   : someApexAppUrl?Parameter=value?fbclickid=something
 Should become : someApexAppUrl?Parameter=value

Whenever there is a parameter added to the url for example

 someApexAppUrl?Parameter=value

Check the parameter name against

Application Items with a protection level of Unrestricted, Checksum Required - Application Level, Checksum Required - User Level, Checksum Required - Session Level

The hard coded list of the default Apex urls parameters which are : session, request, clear, debug, printerFriendly, trace, timezone, lang, territory, cs, dialogCs, x01 according to this article

Application page items with a name pattern P99_Someting

Whenever a parameter is not among these three categories, ignore it and don't send it to Apex. This way even if facebook adds something like ?fbclickid=xxx the Apex App will still work nicely.


问:
foreach with SqlDataReader?
I have the following code:

```<code>SqlDataReader reader = getAddressQuery.sqlReader;
while (reader.Read())
{
    foreach (Object ob in reader)
    {
        someText.InnerText = someText.InnerText + " " + ob.ToString();
    }
}
</code>```

The code in the foreach loop does not execute. However, I can do this:

```<code>SqlDataReader reader = getAddressQuery.sqlReader;
while (reader.Read())
{
    someText.InnerText = reader[0].ToString();
}
</code>```

Which works.

Obviously I could achieve the same result using a regular for loop rather than a foreach loop, but I think the foreach syntax is clearer, so I use it when possible.

What has gone wrong here? Are foreach loops in c# not as flexible as in more high level languages?

答:
The foreach exposes an IDataRecord, which puts you in a very similar boat to the while loop:

```<code>using (SqlConnection conn = new SqlConnection(""))
using (SqlCommand comm = new SqlCommand("select * from somewhere", conn))
{
    conn.Open();

    using (var r = comm.ExecuteReader())
    {
        foreach (DbDataRecord s in r)
        {
            string val = s.GetString(0);
        }
    }
}
</code>```

If you want to see something more useful, you'll need to have some of your own code that extracts the values from the record into something more custom, as the other answer has suggested.

Either way you are going to need custom code, whether you have it inline or not or use a while loop or not depends on how often it's going to be written I suppose, any more than once and you should probably stick it in a helper method somewhere.

And to answer the somewhat question: the problem is not the foreach, it is your attempted usage of what it returns for you, as your comparable use of the while loop is not actually comparable.

Title: foreach with SqlDataReader?

Body:
I have the following code:

SqlDataReader reader = getAddressQuery.sqlReader;
while (reader.Read())
{
    foreach (Object ob in reader)
    {
        someText.InnerText = someText.InnerText + " " + ob.ToString();
    }
}

The code in the foreach loop does not execute. However, I can do this:

SqlDataReader reader = getAddressQuery.sqlReader;
while (reader.Read())
{
    someText.InnerText = reader[0].ToString();
}

Which works.

Obviously I could achieve the same result using a regular for loop rather than a foreach loop, but I think the foreach syntax is clearer, so I use it when possible.

What has gone wrong here? Are foreach loops in c# not as flexible as in more high level languages?

Body:
The foreach exposes an IDataRecord, which puts you in a very similar boat to the while loop:

using (SqlConnection conn = new SqlConnection(""))
using (SqlCommand comm = new SqlCommand("select * from somewhere", conn))
{
    conn.Open();

    using (var r = comm.ExecuteReader())
    {
        foreach (DbDataRecord s in r)
        {
            string val = s.GetString(0);
        }
    }
}

If you want to see something more useful, you'll need to have some of your own code that extracts the values from the record into something more custom, as the other answer has suggested.

Either way you are going to need custom code, whether you have it inline or not or use a while loop or not depends on how often it's going to be written I suppose, any more than once and you should probably stick it in a helper method somewhere.

And to answer the somewhat question: the problem is not the foreach, it is your attempted usage of what it returns for you, as your comparable use of the while loop is not actually comparable.


问:
Device manager does not work (open) after updating Android Studio to 2021.1.1
Android studio's device manager AVD manager works fine in old versions, but in 2021.1.1 version does not open!
Windows 10 and 11 tested
last version flutter
Intel
Sdk manager everything updated
could anyone help?</p>

答:
If you cannot seem to be able to right-click the toolbar as Yahalom mentioned, go to View > Appearance and select Toolbar.

The toolbar will move and a big space will be available on the right to right-click.


问:
Extract text in quotes after specific preceding text string for whole column
I have a column of data and need to delete the text either side of the Company Name, leaving just the company name in that column.

The company name is always preceded with "Company","value":

Example cell data:

some text to delete,:"Company","value":"Company name to remain", some text to delete

Please help me with Excel VBA to accomplish this. I wouldn't know where to start with this one.

Thank you.

答:
I managed to work this out myself.

I broke the process down into seperate stages.

Firstly, I found it easier removing all the quotes, commas and colons from the data column.

Then used InStr to find the the Companyvalue and remove everything before it, including the Companyvalue text itself and then a similar process to remove all the text after The Company Name text that I wanted to keep.

An example cell data string:

```<code>{"profile":{"45":{"B":{"profile_id":"2829","description":"Company","value":"Company Name Text To Keep","section":"B","field_id":"45"}}}}
</code>```

The VBA I used:

```<code>Sub ExtractCompanyName()
    Application.ScreenUpdating = False
    ActiveSheet.Range("B:B").Replace What:="""", Replacement:="", LookAt:=xlPart, MatchCase:=False
    ActiveSheet.Range("B:B").Replace What:=",", Replacement:="", LookAt:=xlPart, MatchCase:=False
    ActiveSheet.Range("B:B").Replace What:=":", Replacement:="", LookAt:=xlPart, MatchCase:=False
    ActiveSheet.Range("B:B").Replace What:="_", Replacement:="", LookAt:=xlPart, MatchCase:=False
    Application.ScreenUpdating = True

 For Each Cell In Sheets(1).Range("B:B")
      If InStr(Cell.Value, "Companyvalue") > 0 Then Cell.Value = Split(Cell.Value, "Companyvalue")(1)
   Next
 For Each Cell In Sheets(1).Range("B:B")
      If InStr(Cell.Value, "sectionBfieldid45") > 0 Then Cell.Value = Left(Cell.Value, InStr(Cell.Value, "sectionBfieldid45") - 1)
   Next
End Sub
</code>```

I hope this helps others.

Body:
I managed to work this out myself.

I broke the process down into seperate stages.

Firstly, I found it easier removing all the quotes, commas and colons from the data column.

Then used InStr to find the the Companyvalue and remove everything before it, including the Companyvalue text itself and then a similar process to remove all the text after The Company Name text that I wanted to keep.

An example cell data string:

{"profile":{"45":{"B":{"profile_id":"2829","description":"Company","value":"Company Name Text To Keep","section":"B","field_id":"45"}}}}

The VBA I used:

Sub ExtractCompanyName()
    Application.ScreenUpdating = False
    ActiveSheet.Range("B:B").Replace What:="""", Replacement:="", LookAt:=xlPart, MatchCase:=False
    ActiveSheet.Range("B:B").Replace What:=",", Replacement:="", LookAt:=xlPart, MatchCase:=False
    ActiveSheet.Range("B:B").Replace What:=":", Replacement:="", LookAt:=xlPart, MatchCase:=False
    ActiveSheet.Range("B:B").Replace What:="_", Replacement:="", LookAt:=xlPart, MatchCase:=False
    Application.ScreenUpdating = True

 For Each Cell In Sheets(1).Range("B:B")
      If InStr(Cell.Value, "Companyvalue") > 0 Then Cell.Value = Split(Cell.Value, "Companyvalue")(1)
   Next
 For Each Cell In Sheets(1).Range("B:B")
      If InStr(Cell.Value, "sectionBfieldid45") > 0 Then Cell.Value = Left(Cell.Value, InStr(Cell.Value, "sectionBfieldid45") - 1)
   Next
End Sub

I hope this helps others.


问:
Import an existing python project to XCode
I've got a python project I've been making in terminal with vim etc.. I've read that XCode supports Python development at that it supports SVN (which I am using) but I can't find documentation on how to start a new XCode project from an existing code repository.

Other developers are working on the project not using XCode - They won't mind if I add a project file or something, but they will mind if I have to reorganise the whole thing.

答: I don't think it's worth using Xcode for a pure python project. Although the Xcode editor does syntax-highlight Python code, Xcode does not give you any other benefit for writing a pure-python app. On OS X, I would recommend TextMate as a text editor or Eclipse with PyDev as a more full-featured IDE.</p>

OwnerDisplayName: rjmunro

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Barry Wark


问:
Adding badge to tab in android
i want to add badge to tab in my app as in iPhone.

Screen shot of badge used in iPhone is in the following link:

i have done some image like badge in android app ,its screen shot is in the following link:

this is not the exactly badge i want, i want badge on tab like in  iPhone

can anybody suggest me to add badge to tab in android? Please help me.

thanks in advance.

答:
I also looked for a solution for this in the android sdk and found none so i went and wrote a custom TabWidget for it.

The short version:

Extend the TabWidget class and override the method: drawChild (Canvas canvas, View child, long drawingTime)

In the painting you simply draw a Bitmap ontop of the canvas. You get the x location of the child with child.getRight() and subtract the width of your badge Bitmap. Also draw the text for the badge number ontop of that.

To keep a state for each tab you could use a HashMap with keys for the index of each tab.

To be able to update the tabs from anywhere i used a singleton class with the widget inside that i initialize from the main activity.

More info can be found here, including the source code for an example android project:

http://nilisoft.com/?p=622

Enjoy!

Title: Adding badge to tab in android


问:
jQuery scrollTo plugin problem. Nothing's moving?
I'm having real trouble trying to get a div to scroll on a page I'm building.

I basically have a div element, which has a much wider div inside that I want to scroll along to show different areas, and as such change the content. Basically a tab slider but a little different.

I've set it up currently to work on hover of the div in question, the event triggers but nothing happens. Please help!.

The URL is: http://ram.grtest.com/ and click 'Join'. Hover over the content in there and the event should trigger. Don't click 'Next >' - that submits a form!

Here's the initialisation (test data, i'll adjust the amount of movement later)

```<code>$('#join-content').hover(function(){
    $('#join-wrapper-scroll').scrollTo({axis: 'x',left:'+=100'}, 2000);
    return false;
});
</code>```

Thanks in advance!

答:
Does #join-wrapper-scroll have an inside layer before the content? I.e.

```<code><div id="join-wrapper-scroll">
    <ul> <!-- inner layer -->
        <li>Content that scrolls.</li>
        <li>Content that scrolls.</li>
    </ul>
</div>
</code>```

You need an "inner layer" or else the plugin won't understand what it's scrolling.

Body:
I'm having real trouble trying to get a div to scroll on a page I'm building.

I basically have a div element, which has a much wider div inside that I want to scroll along to show different areas, and as such change the content. Basically a tab slider but a little different.

I've set it up currently to work on hover of the div in question, the event triggers but nothing happens. Please help!.

The URL is: http://ram.grtest.com/ and click 'Join'. Hover over the content in there and the event should trigger. Don't click 'Next >' - that submits a form!

Here's the initialisation (test data, i'll adjust the amount of movement later)

$('#join-content').hover(function(){
    $('#join-wrapper-scroll').scrollTo({axis: 'x',left:'+=100'}, 2000);
    return false;
});

Thanks in advance!

Body:
Does #join-wrapper-scroll have an inside layer before the content? I.e.

<div id="join-wrapper-scroll">
    <ul> <!-- inner layer -->
        <li>Content that scrolls.</li>
        <li>Content that scrolls.</li>
    </ul>
</div>

You need an "inner layer" or else the plugin won't understand what it's scrolling.


问:
Minecraft | Spigot | Set Double or argument Decimal limit in command
I am currently working on my own currency system and am now looking for a solution to limit the decimal places in the argument to solve this problem.

Example

"/command username
4.555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555565555555555555555555555555555555555555555555555555555555555555555555555551"

```<code>public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {

        if (sender instanceof Player) {
            Player player = (Player) sender;

            if (args.length == 0) {
                player.sendMessage(Main.prefix + "§7/Bezahlen §8(§aSpieler§8) §8(§aBetrag§8)");
                player.sendMessage(Main.prefix + "§7Dein Kontostand: §a" + moneyapi.getMoney(player.getUniqueId()));
                return false;
            } else {
                Player target = Bukkit.getPlayer(args[0]);

                if (args.length == 1) {
                    player.sendMessage(Main.prefix + "§7/Bezahlen §8(§aSpieler§8) §8(§aBetrag§8)");
                    return false;
                } else {
                    if (args.length == 2) {
                        if (isDouble(args[1])) {
                            if (Double.parseDouble(args[1]) >= 1) {
                                if (target != null) {
                                    if (target != player) {
                                        if (moneyapi.hasEnough(player.getUniqueId(), Double.parseDouble(args[1]))) {
                                            moneyapi.removeMoney(player.getUniqueId(), Double.parseDouble(args[1]));
                                            moneyapi.addMoney(target.getUniqueId(), Double.parseDouble(args[1]));

                                            player.sendMessage(Main.prefix + "§7Bezahlt: §a" + target.getName().toString() + "§8(§c-" + args[1] + "§8)");
                                            target.sendMessage(Main.prefix + "§7Erhalten: §c" + player.getName().toString() + "§8(§a+" + args[1] + "§8)");
                                            return true;
                                        }
                                    } else {
                                        player.sendMessage(Main.prefix + "§7Du kannst dir kein Geld senden!");
                                        return false;
                                    }
                                } else {
                                    player.sendMessage(Main.prefix + "§7Dieser Spieler ist nicht online! " + "§8(§a" + args[0] + "§8)");
                                    return false;
                                }
                            } else {
                                player.sendMessage(Main.prefix + "§7Bitte gebe einen gültigen Betrag ein!");
                                return false;
                            }
                        } else {
                            player.sendMessage(Main.prefix + "§7Bitte gebe einen gültigen Betrag ein!");
                            return false;
                        }
                    }
                }
            }
        } else {
            sender.sendMessage(Main.consoleblocker);
            return false;
        }
        return false;
    }
}
</code>```

Could you guys possibly help me with this?

答: You can check the amount of decimals on a double by using BigDecimal.valueOf(value).scale() > 2 where value is the double your checking. (2 in this case is the amount of decimal places max, you can change this to whatever number)

Body:
I am currently working on my own currency system and am now looking for a solution to limit the decimal places in the argument to solve this problem.

Example

"/command username
4.555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555565555555555555555555555555555555555555555555555555555555555555555555555551"

public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {

        if (sender instanceof Player) {
            Player player = (Player) sender;

            if (args.length == 0) {
                player.sendMessage(Main.prefix + "§7/Bezahlen §8(§aSpieler§8) §8(§aBetrag§8)");
                player.sendMessage(Main.prefix + "§7Dein Kontostand: §a" + moneyapi.getMoney(player.getUniqueId()));
                return false;
            } else {
                Player target = Bukkit.getPlayer(args[0]);

                if (args.length == 1) {
                    player.sendMessage(Main.prefix + "§7/Bezahlen §8(§aSpieler§8) §8(§aBetrag§8)");
                    return false;
                } else {
                    if (args.length == 2) {
                        if (isDouble(args[1])) {
                            if (Double.parseDouble(args[1]) >= 1) {
                                if (target != null) {
                                    if (target != player) {
                                        if (moneyapi.hasEnough(player.getUniqueId(), Double.parseDouble(args[1]))) {
                                            moneyapi.removeMoney(player.getUniqueId(), Double.parseDouble(args[1]));
                                            moneyapi.addMoney(target.getUniqueId(), Double.parseDouble(args[1]));

                                            player.sendMessage(Main.prefix + "§7Bezahlt: §a" + target.getName().toString() + "§8(§c-" + args[1] + "§8)");
                                            target.sendMessage(Main.prefix + "§7Erhalten: §c" + player.getName().toString() + "§8(§a+" + args[1] + "§8)");
                                            return true;
                                        }
                                    } else {
                                        player.sendMessage(Main.prefix + "§7Du kannst dir kein Geld senden!");
                                        return false;
                                    }
                                } else {
                                    player.sendMessage(Main.prefix + "§7Dieser Spieler ist nicht online! " + "§8(§a" + args[0] + "§8)");
                                    return false;
                                }
                            } else {
                                player.sendMessage(Main.prefix + "§7Bitte gebe einen gültigen Betrag ein!");
                                return false;
                            }
                        } else {
                            player.sendMessage(Main.prefix + "§7Bitte gebe einen gültigen Betrag ein!");
                            return false;
                        }
                    }
                }
            }
        } else {
            sender.sendMessage(Main.consoleblocker);
            return false;
        }
        return false;
    }
}

Could you guys possibly help me with this?


问:
Swift UINavigationBar background image does not cover status bar when clipToBounds is true
I'm setting the background image of a large title navigation bar like this:

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    navigationController?.navigationBar.prefersLargeTitles = true

    self.title = "Nav bar"

    let largeTitleAppearance = UINavigationBarAppearance()

    largeTitleAppearance.configureWithOpaqueBackground()
    largeTitleAppearance.backgroundImage = UIImage(named: "kunal-shinde--f0YLss50Bs-unsplash")
    largeTitleAppearance.backgroundImageContentMode = .scaleAspectFill
    largeTitleAppearance.titleTextAttributes = [.foregroundColor: UIColor.white]
    largeTitleAppearance.largeTitleTextAttributes = [.foregroundColor: UIColor.white]

    navigationController?.navigationBar.standardAppearance = largeTitleAppearance
    navigationController?.navigationBar.scrollEdgeAppearance = largeTitleAppearance
}
</code>```

However, the image overflows out of the navigation bar as shown here:

I thought clipsToBounds might work so I set it to true at the end of viewDidLoad

```<code>navigationController?.navigationBar.clipsToBounds = true
</code>```

This is better, but the image does not cover the status bar! How can I get it to cover the status bar while not overflowing?

答:
We've solved this as followed:

We set the background image on ViewController. This is the same as we use in navigation bar.

let imageView = UIImageView(image: .assetImage(.background))
imageView.contentMode = .topLeft
collectionView.backgroundView = imageView
```
<p>Style the navigation bar.</p>
<pre class="lang-swift prettyprint-override"><code>// General Styling
UINavigationBar.appearance().tintColor = .assetColor(.navigationBarTintColor)

// Bar Styling
let navBarAppearance = UINavigationBarAppearance()
navBarAppearance.shadowColor = .clear
navBarAppearance.backgroundColor = UIColor(patternImage: .assetImage(.background)!)

UINavigationBar.appearance().standardAppearance = navBarAppearance
UINavigationBar.appearance().scrollEdgeAppearance = navBarAppearance
</code>```

In addition we change the translucent of the navigation bar for non-root views:

if isRootview {
    self.navigationController?.navigationBar.isTranslucent = true
} else {
    self.navigationController?.navigationBar.isTranslucent = false
}
```

Body:
I'm setting the background image of a large title navigation bar like this:

override func viewDidLoad() {
    super.viewDidLoad()

    navigationController?.navigationBar.prefersLargeTitles = true

    self.title = "Nav bar"

    let largeTitleAppearance = UINavigationBarAppearance()

    largeTitleAppearance.configureWithOpaqueBackground()
    largeTitleAppearance.backgroundImage = UIImage(named: "kunal-shinde--f0YLss50Bs-unsplash")
    largeTitleAppearance.backgroundImageContentMode = .scaleAspectFill
    largeTitleAppearance.titleTextAttributes = [.foregroundColor: UIColor.white]
    largeTitleAppearance.largeTitleTextAttributes = [.foregroundColor: UIColor.white]

    navigationController?.navigationBar.standardAppearance = largeTitleAppearance
    navigationController?.navigationBar.scrollEdgeAppearance = largeTitleAppearance
}

However, the image overflows out of the navigation bar as shown here:

I thought clipsToBounds might work so I set it to true at the end of viewDidLoad

navigationController?.navigationBar.clipsToBounds = true

This is better, but the image does not cover the status bar! How can I get it to cover the status bar while not overflowing?

Body:
We've solved this as followed:

We set the background image on ViewController. This is the same as we use in navigation bar.

let imageView = UIImageView(image: .assetImage(.background))
imageView.contentMode = .topLeft
collectionView.backgroundView = imageView

Style the navigation bar.

// General Styling
UINavigationBar.appearance().tintColor = .assetColor(.navigationBarTintColor)

// Bar Styling
let navBarAppearance = UINavigationBarAppearance()
navBarAppearance.shadowColor = .clear
navBarAppearance.backgroundColor = UIColor(patternImage: .assetImage(.background)!)

UINavigationBar.appearance().standardAppearance = navBarAppearance
UINavigationBar.appearance().scrollEdgeAppearance = navBarAppearance

In addition we change the translucent of the navigation bar for non-root views:

if isRootview {
    self.navigationController?.navigationBar.isTranslucent = true
} else {
    self.navigationController?.navigationBar.isTranslucent = false
}


问:
Subtraction of numbers double and long
In my JAVA program there is code like this:

```<code>int f_part = (int) ((f_num - num) * 100);
</code>```

f_num is double and num is long. I just want to take the fractional part out and assign it to f_part. But some times f_part value is one less than it's value. Which means if f_num = 123.55 and num = 123, But f_part equals to 54. And it happens only f_num and num is greater than 100. I don't know why this happening. Please can someone explain why this happens and way to correct it.

答:
This is due to the limited precision in doubles.

The root of your problem is that the literal 123.55 actually represents the value 123.54999....

It may seem like it holds the value 123.55 if you print it:

```<code>System.out.println(123.55);                  // prints 123.55
</code>```

but in fact, the printed value is an approximation. This can be revealed by creating a BigDecimal out of it, (which provides arbitrary precision) and print the BigDecimal:

```<code>System.out.println(new BigDecimal(123.55));  // prints 123.54999999999999715...
</code>```

You can solve it by going via Math.round but you would have to know how many decimals the source double actually entails, or you could choose to go through the string representation of the double in fact goes through a fairly intricate algorithm.

If you're working with currencies, I strongly suggest you either

Let prices etc be represented by BigDecimal which allows you to store numbers as 0.1 accurately, or

Let an int store the number of cents (as opposed to having a double store the number of dollars).

Both ways are perfectly acceptable and used in practice.

Title: Subtraction of numbers double and long

Body:
In my JAVA program there is code like this:

int f_part = (int) ((f_num - num) * 100);

f_num is double and num is long. I just want to take the fractional part out and assign it to f_part. But some times f_part value is one less than it's value. Which means if f_num = 123.55 and num = 123, But f_part equals to 54. And it happens only f_num and num is greater than 100. I don't know why this happening. Please can someone explain why this happens and way to correct it.

Body:
This is due to the limited precision in doubles.

The root of your problem is that the literal 123.55 actually represents the value 123.54999....

It may seem like it holds the value 123.55 if you print it:

System.out.println(123.55);                  // prints 123.55

but in fact, the printed value is an approximation. This can be revealed by creating a BigDecimal out of it, (which provides arbitrary precision) and print the BigDecimal:

System.out.println(new BigDecimal(123.55));  // prints 123.54999999999999715...

You can solve it by going via Math.round but you would have to know how many decimals the source double actually entails, or you could choose to go through the string representation of the double in fact goes through a fairly intricate algorithm.

If you're working with currencies, I strongly suggest you either

Let prices etc be represented by BigDecimal which allows you to store numbers as 0.1 accurately, or

Let an int store the number of cents (as opposed to having a double store the number of dollars).

Both ways are perfectly acceptable and used in practice.


问:
Return keys whose values are true from a Json Object using java
From below json object , I want to return(/or add the keys to a Set) whose values are true.

```<code>  {
    "create": true,
    "read": false,
    "update": true,
    "delete": false
  }
</code>```

I want an output like below

[ create, update ]
Could some one help me with this?

Update :

I was trying as shown below to capture all the values that are true , but I think my Java 8 filter criteria is wrong.

```<code>
Map<String, Object> mapping = new ObjectMapper().readValue(permissionStr, HashMap.class);
mySet = mapping.entrySet().stream().filter(x->x.getValue().equals(Boolean.TRUE)).map(Map.Entry::getKey)
                    .collect(Collectors.toSet());
</code>```

答:
Set each field to default to false in the Java class and annotate the class with @JsonInclude(JsonInclude.Include.NON_DEFAULT). This checks the instance of the class you created with a default instance created with a no args constructor and only sends the values that have changed, in your case any value that is true.

When parsing the JSON output, you can then check which keys are in the object.

Body:
From below json object , I want to return(/or add the keys to a Set) whose values are true.

  {
    "create": true,
    "read": false,
    "update": true,
    "delete": false
  }

I want an output like below

[ create, update ]
Could some one help me with this?

Update :

I was trying as shown below to capture all the values that are true , but I think my Java 8 filter criteria is wrong.

Map<String, Object> mapping = new ObjectMapper().readValue(permissionStr, HashMap.class);
mySet = mapping.entrySet().stream().filter(x->x.getValue().equals(Boolean.TRUE)).map(Map.Entry::getKey)
                    .collect(Collectors.toSet());


问:
Testcafe fails to connect to localhost on OSX
I'm having very strange recurring issues connecting to a locally served vuejs application (nodejs). localhost:8080 successfully loads in a local browser, but regardless of configuration testcafe returns: Failed to find a DNS-record for the resource at "http://localhost:3000/".

I emptied .testcaferc.json and created the following Minimum Working Example:
testcafe "chrome" tests/testcafe_debug.test.js --app "npm run serve" --app-init-delay 1 -S -s

tests/testcafe_debug.test.js:

```<code>
fixture `Fixture`
  .page('http://localhost:8080/login');

test('test', async t => {
  await t
    .click('body')
    .expect(Selector('div p a').text).eql('Register Here');
});
</code>```

This is actually the second time I've seen the problem. Visiting a friend an on a new network, connections failed until I added --proxyBypass localhost to the test run. This fixed the issue for the moment, but now I'm having the same errors a few weeks later.
Things I've looked into:

--hostname localhost has no effect

There's nothing strange in /etc/hosts.

No change if I turn off my wifi connection or adjust the proxy settings
I'm not running a firewall or vpn. I'm not sure where else to look. Any suggestions or advice would be profoundly appreciated.

答:
In your TestCafe launch command, you allow just one millisecond for the application to load (--app-init-delay 1). It looks like TestCafe requests the page before the server is ready. Try to increase this delay (specified in milliseconds) so that it's enough for your app server to start up and serve the tested app.

The following example specifies a ten-second delay:

testcafe "chrome" tests/testcafe_debug.test.js --app "npm run serve" --app-init-delay 10000 -S -s
```

UPD: looks similar to https://github.com/DevExpress/testcafe/issues/6844

Body:
I'm having very strange recurring issues connecting to a locally served vuejs application (nodejs). localhost:8080 successfully loads in a local browser, but regardless of configuration testcafe returns: Failed to find a DNS-record for the resource at "http://localhost:3000/".

I emptied .testcaferc.json and created the following Minimum Working Example:
testcafe "chrome" tests/testcafe_debug.test.js --app "npm run serve" --app-init-delay 1 -S -s

tests/testcafe_debug.test.js:

fixture `Fixture`
  .page('http://localhost:8080/login');

test('test', async t => {
  await t
    .click('body')
    .expect(Selector('div p a').text).eql('Register Here');
});

This is actually the second time I've seen the problem. Visiting a friend an on a new network, connections failed until I added --proxyBypass localhost to the test run. This fixed the issue for the moment, but now I'm having the same errors a few weeks later.
Things I've looked into:

--hostname localhost has no effect

There's nothing strange in /etc/hosts.

No change if I turn off my wifi connection or adjust the proxy settings
I'm not running a firewall or vpn. I'm not sure where else to look. Any suggestions or advice would be profoundly appreciated.

Body:
In your TestCafe launch command, you allow just one millisecond for the application to load (--app-init-delay 1). It looks like TestCafe requests the page before the server is ready. Try to increase this delay (specified in milliseconds) so that it's enough for your app server to start up and serve the tested app.

The following example specifies a ten-second delay:

testcafe "chrome" tests/testcafe_debug.test.js --app "npm run serve" --app-init-delay 10000 -S -s

UPD: looks similar to https://github.com/DevExpress/testcafe/issues/6844


问:
Instaloader JSON files: Convert 200 JSON files into a Single CSV (Python 3.7)
I want to automatically download pictures (or videos) along with their captions and other data from a specific Instagram Hashtag (e.g. #moodoftheday) using Instaloader. Instaloader returns JSON files including posts metadata.

The following code worked with just a single @user_profile metadata.
I want to do the same, but for a #hashtag not a specific @user.

The ultimate goal is to have all of the JSON files (e.g. 200) into a csv file.
How can I process my downloaded data in a clean excel/CSV file?

Here is my code:

```<code># Install Instaloader
import instaloader

def get_instagram_posts(username, startdate, enddate):
   # Create an instaloader object with parameters
   L = instaloader.Instaloader(download_pictures = False, download_videos = False, download_comments= False, compress_json = False)

   # Log in with the instaloader object
   L.login("username" , "password")
   # Search the instagram profile
   profile = instaloader.Profile.from_username(L.context, username)
   # Scrape the posts
   posts = profile.get_posts()
   for post in takewhile(lambda p: p.date > startdate, dropwhile(lambda p : p.date > enddate, posts)):
   print(post.date)
   L.download_post(post, target = profile.username)

'''
This function will now save all instagram posts and related data to a folder in you current working directory.
Let’s call this function on the instagram account of “moodoftheday”. let the script do its magic.
This might take a while so be patient.
'''

import os
import datetime
# instagram username
username = "realdonaldtrump"
# daterange of scraping
startdate = datetime(2020, 9, 1)
enddate = datetime(2020, 10, 1)
# get your current working directory
current_wkdir = os.get_cwd()
# Call the function. This will automatically store all the scrape data in a folder in your current working directory
get_instagram_posts(username, startdate, enddate)

'''
You notice that this data is NOT yet in the right format since each post has a separate json file.
You will need to process all these json files to a consolidated excel file in order to perform analyses on the data.
'''

def parse_instafiles(username, path):
    """
    This function loads in all the json files generated by the instaloader package and parses it into a csv file.
    """
    #print('Entering provided directory...')
    os.chdir(os.path.join(path, username))

    columns = ['filename', 'datetime', 'type', 'locations_id', 'locations_name', 'mentions', 'hashtags', 'video_duration']

    dataframe = pd.DataFrame(columns=[])

    #print('Traversing file tree...')

    glob('*UTC.json')

    for file in glob('*UTC.json'):
        with open(file, 'r') as filecontent:
            filename = filecontent.name
            #print('Found JSON file: ' + filename + '. Loading...')

            try:
                metadata = orjson.loads(filecontent.read())

            except IOError as e:
                #print("I/O Error. Couldn't load file. Trying the next one...")
                continue
            else:
                pass
            #print('Collecting relevant metadata...')
            time = datetime.fromtimestamp(int(metadata['node']['taken_at_timestamp']))
            type_ = metadata['node']['__typename']
            likes = metadata['node']['edge_media_preview_like']['count']
            comments = metadata['node']['edge_media_to_comment']['count']
            username = metadata['node']['owner']['username']
            followers = metadata['node']['owner']['edge_followed_by']['count']
            try:
                text = metadata['node']['edge_media_to_caption']['edges'][0]['node']['text']
            except:
                text = ""
            try:
                post_id = metadata['node']['id']
            except:
                post_id = ""
            minedata = {'filename': filename, 'time': time, 'text': text,
                    'likes': likes, 'comments' : comments, 'username' : username,  'followers' : followers, 'post_id' : post_id}
            #print('Writing to dataframe...')
            dataframe = dataframe.append(minedata, ignore_index=True)
            #print('Closing file...')
            del metadata
            filecontent.close()
    #print('Storing dataframe to CSV file...')
    #print('Done.')
    dataframe['source'] = 'Instagram'
    return dataframe

'''
You can then use this function to process the "moodoftheday" Instagram data.
'''

df_instagram = parse_instafiles(username, os.getcwd() )
df_instagram.to_excel("moodoftheday.csv")
</code>```

I am very new to Python and programming overall, therefore any help is very much appreciated!!
Thank you in advance! Sofia

答:
I made some changes it's not showing error but still needs some professional works:</p>
```<code>import instaloader
from datetime import datetime
import datetime
from itertools import takewhile
from itertools import dropwhile
import os
import glob as glob
import json
import pandas as pd
import csv

lusername = ''
lpassword = ''

def get_instagram_posts(username, startdate, enddate):
   # Create an instaloader object with parameters
   L = instaloader.Instaloader(download_pictures = False, download_videos = False, download_comments= False, compress_json = False)

   # Log in with the instaloader object
   L.login("lusername" , "lpassword")

   # Search the instagram profile
   profile = instaloader.Profile.from_username(L.context, username)
   # Scrape the posts
   posts = profile.get_posts()
   for post in takewhile(lambda p: p.date > startdate, dropwhile(lambda p : p.date > enddate, posts)):
    print(post.date)
   L.download_post(post, target = profile.username)

# instagram username
username = "realdonaldtrump"
# daterange of scraping
startdate = datetime.datetime(2020, 9, 1,0,0)
enddate = datetime.datetime(2022, 2, 1,0,0)
# get your current working directory
current_wkdir = os.getcwd()
# Call the function. This will automatically store all the scrape data in a folder in your current working directory
get_instagram_posts(username, startdate, enddate)

def parse_instafiles(username, path):
    #print('Entering provided directory...')
    os.chdir(os.path.join(path, username))

    columns = ['filename', 'datetime', 'type', 'locations_id', 'locations_name', 'mentions', 'hashtags', 'video_duration']

    dataframe = pd.DataFrame(columns=[])

    #print('Traversing file tree...')

#    glob('*UTC.json')

    for file in glob.glob('*UTC.json'):
        with open(file, 'r') as filecontent:
            filename = filecontent.name
            #print('Found JSON file: ' + filename + '. Loading...')

            try:
                metadata = json.load(filecontent)

            except IOError as e:
                #print("I/O Error. Couldn't load file. Trying the next one...")
                continue
            else:
                pass
            #print('Collecting relevant metadata...')
            time = datetime.datetime.fromtimestamp(int(metadata['node']['taken_at_timestamp']))
            type_ = metadata['node']['__typename']
            likes = metadata['node']['edge_media_preview_like']['count']
            comments = metadata['node']['edge_media_to_comment']['count']
            username = metadata['node']['owner']['username']
            followers = metadata['node']['owner']['edge_followed_by']['count']
            try:
                text = metadata['node']['edge_media_to_caption']['edges'][0]['node']['text']
            except:
                text = ""
            try:
                post_id = metadata['node']['id']
            except:
                post_id = ""
            minedata = {'filename': filename, 'time': time, 'text': text,
                    'likes': likes, 'comments' : comments, 'username' : username,  'followers' : followers, 'post_id' : post_id}
            #print('Writing to dataframe...')
            dataframe = dataframe.append(minedata, ignore_index=True)
            #print('Closing file...')
            del metadata
            filecontent.close()
    #print('Storing dataframe to CSV file...')
    #print('Done.')
    dataframe['source'] = 'Instagram'
    return dataframe

'''
You can then use this function to process the "moodoftheday" Instagram data.
'''

df_instagram = parse_instafiles(username, os.getcwd() )
df_instagram.to_csv("moodoftheday.csv")
</code>```

Body:
I want to automatically download pictures (or videos) along with their captions and other data from a specific Instagram Hashtag (e.g. #moodoftheday) using Instaloader. Instaloader returns JSON files including posts metadata.

The following code worked with just a single @user_profile metadata.
I want to do the same, but for a #hashtag not a specific @user.

The ultimate goal is to have all of the JSON files (e.g. 200) into a csv file.
How can I process my downloaded data in a clean excel/CSV file?

Here is my code:

# Install Instaloader
import instaloader

def get_instagram_posts(username, startdate, enddate):
   # Create an instaloader object with parameters
   L = instaloader.Instaloader(download_pictures = False, download_videos = False, download_comments= False, compress_json = False)

   # Log in with the instaloader object
   L.login("username" , "password")
   # Search the instagram profile
   profile = instaloader.Profile.from_username(L.context, username)
   # Scrape the posts
   posts = profile.get_posts()
   for post in takewhile(lambda p: p.date > startdate, dropwhile(lambda p : p.date > enddate, posts)):
   print(post.date)
   L.download_post(post, target = profile.username)

'''
This function will now save all instagram posts and related data to a folder in you current working directory.
Let’s call this function on the instagram account of “moodoftheday”. let the script do its magic.
This might take a while so be patient.
'''

import os
import datetime
# instagram username
username = "realdonaldtrump"
# daterange of scraping
startdate = datetime(2020, 9, 1)
enddate = datetime(2020, 10, 1)
# get your current working directory
current_wkdir = os.get_cwd()
# Call the function. This will automatically store all the scrape data in a folder in your current working directory
get_instagram_posts(username, startdate, enddate)

'''
You notice that this data is NOT yet in the right format since each post has a separate json file.
You will need to process all these json files to a consolidated excel file in order to perform analyses on the data.
'''

def parse_instafiles(username, path):
    """
    This function loads in all the json files generated by the instaloader package and parses it into a csv file.
    """
    #print('Entering provided directory...')
    os.chdir(os.path.join(path, username))

    columns = ['filename', 'datetime', 'type', 'locations_id', 'locations_name', 'mentions', 'hashtags', 'video_duration']

    dataframe = pd.DataFrame(columns=[])

    #print('Traversing file tree...')

    glob('*UTC.json')

    for file in glob('*UTC.json'):
        with open(file, 'r') as filecontent:
            filename = filecontent.name
            #print('Found JSON file: ' + filename + '. Loading...')

            try:
                metadata = orjson.loads(filecontent.read())

            except IOError as e:
                #print("I/O Error. Couldn't load file. Trying the next one...")
                continue
            else:
                pass
            #print('Collecting relevant metadata...')
            time = datetime.fromtimestamp(int(metadata['node']['taken_at_timestamp']))
            type_ = metadata['node']['__typename']
            likes = metadata['node']['edge_media_preview_like']['count']
            comments = metadata['node']['edge_media_to_comment']['count']
            username = metadata['node']['owner']['username']
            followers = metadata['node']['owner']['edge_followed_by']['count']
            try:
                text = metadata['node']['edge_media_to_caption']['edges'][0]['node']['text']
            except:
                text = ""
            try:
                post_id = metadata['node']['id']
            except:
                post_id = ""
            minedata = {'filename': filename, 'time': time, 'text': text,
                    'likes': likes, 'comments' : comments, 'username' : username,  'followers' : followers, 'post_id' : post_id}
            #print('Writing to dataframe...')
            dataframe = dataframe.append(minedata, ignore_index=True)
            #print('Closing file...')
            del metadata
            filecontent.close()
    #print('Storing dataframe to CSV file...')
    #print('Done.')
    dataframe['source'] = 'Instagram'
    return dataframe

'''
You can then use this function to process the "moodoftheday" Instagram data.
'''

df_instagram = parse_instafiles(username, os.getcwd() )
df_instagram.to_excel("moodoftheday.csv")

I am very new to Python and programming overall, therefore any help is very much appreciated!!
Thank you in advance! Sofia

Body:
I made some changes it's not showing error but still needs some professional works:

import instaloader
from datetime import datetime
import datetime
from itertools import takewhile
from itertools import dropwhile
import os
import glob as glob
import json
import pandas as pd
import csv

lusername = ''
lpassword = ''

def get_instagram_posts(username, startdate, enddate):
   # Create an instaloader object with parameters
   L = instaloader.Instaloader(download_pictures = False, download_videos = False, download_comments= False, compress_json = False)

   # Log in with the instaloader object
   L.login("lusername" , "lpassword")

   # Search the instagram profile
   profile = instaloader.Profile.from_username(L.context, username)
   # Scrape the posts
   posts = profile.get_posts()
   for post in takewhile(lambda p: p.date > startdate, dropwhile(lambda p : p.date > enddate, posts)):
    print(post.date)
   L.download_post(post, target = profile.username)

# instagram username
username = "realdonaldtrump"
# daterange of scraping
startdate = datetime.datetime(2020, 9, 1,0,0)
enddate = datetime.datetime(2022, 2, 1,0,0)
# get your current working directory
current_wkdir = os.getcwd()
# Call the function. This will automatically store all the scrape data in a folder in your current working directory
get_instagram_posts(username, startdate, enddate)

def parse_instafiles(username, path):
    #print('Entering provided directory...')
    os.chdir(os.path.join(path, username))

    columns = ['filename', 'datetime', 'type', 'locations_id', 'locations_name', 'mentions', 'hashtags', 'video_duration']

    dataframe = pd.DataFrame(columns=[])

    #print('Traversing file tree...')

#    glob('*UTC.json')

    for file in glob.glob('*UTC.json'):
        with open(file, 'r') as filecontent:
            filename = filecontent.name
            #print('Found JSON file: ' + filename + '. Loading...')

            try:
                metadata = json.load(filecontent)

            except IOError as e:
                #print("I/O Error. Couldn't load file. Trying the next one...")
                continue
            else:
                pass
            #print('Collecting relevant metadata...')
            time = datetime.datetime.fromtimestamp(int(metadata['node']['taken_at_timestamp']))
            type_ = metadata['node']['__typename']
            likes = metadata['node']['edge_media_preview_like']['count']
            comments = metadata['node']['edge_media_to_comment']['count']
            username = metadata['node']['owner']['username']
            followers = metadata['node']['owner']['edge_followed_by']['count']
            try:
                text = metadata['node']['edge_media_to_caption']['edges'][0]['node']['text']
            except:
                text = ""
            try:
                post_id = metadata['node']['id']
            except:
                post_id = ""
            minedata = {'filename': filename, 'time': time, 'text': text,
                    'likes': likes, 'comments' : comments, 'username' : username,  'followers' : followers, 'post_id' : post_id}
            #print('Writing to dataframe...')
            dataframe = dataframe.append(minedata, ignore_index=True)
            #print('Closing file...')
            del metadata
            filecontent.close()
    #print('Storing dataframe to CSV file...')
    #print('Done.')
    dataframe['source'] = 'Instagram'
    return dataframe

'''
You can then use this function to process the "moodoftheday" Instagram data.
'''

df_instagram = parse_instafiles(username, os.getcwd() )
df_instagram.to_csv("moodoftheday.csv")


问:
Is there a way I could control the order of the documents presented to a signer when using composite templates?
Is there a way I could control the order of the documents presented to a signer when using composite templates?
If I have, for example, 3 templates that I want to send and I want the signer to see (not necessarily sign) a specific one first how would I set that.
All templates only have one document.
As far as I understand the sequence property for server and inline templates has more to do with the order of documents and tabs in specific composites not for the overall envelope.
Here is the c# code I have for now (not perfect, kind of a first draft). I have a few template Id's stored in a list of string and I'm looping through them assigning almost random sequencing values because I only care if the inline template sequence value is higher than the server template.
What I'm asking is if I have a template document that I would like to show first is there a way to do that? It doesn't have to implement looping. I just want to know if there is a way</p>
```<code> List<CompositeTemplate> compositeTemplates = new List<CompositeTemplate>();

            Recipients recipientsServerTemplate = new Recipients();
            List<Signer> signers = new List<Signer>();
            List<CarbonCopy> carbonCopies = new List<CarbonCopy>();

        List<Text> textControlsInTemplate = SetTemplateFields();

        Tabs tabs = new Tabs
        {
            TextTabs = textControlsInTemplate
        };

        Signer signer1 = new Signer();
        signer1.Email = signerEmail;
        signer1.Name = signerName;
        signer1.RoleName = "signer";
        signer1.RecipientId = "1";
        signer1.Tabs = tabs;
        signers.Add(signer1);

        CarbonCopy cc1 = new CarbonCopy();
        cc1.Email = ccEmail;
        cc1.Name = ccName;
        cc1.RoleName = "cc";
        cc1.RecipientId = "2";
        carbonCopies.Add(cc1);

        recipientsServerTemplate.Signers = signers;
        recipientsServerTemplate.CarbonCopies = carbonCopies;

int i = 1;
            foreach (string templateId in templateIds)
            {
                List<ServerTemplate> ServerTemplates = new List<ServerTemplate>();
                List<InlineTemplate> InlineTemplates = new List<InlineTemplate>();
                CompositeTemplate CT = new CompositeTemplate
                {
                    CompositeTemplateId = i.ToString()
                };

                ServerTemplate ST = new ServerTemplate
                {
                    Sequence = i.ToString(),
                    TemplateId = templateId
                };

                InlineTemplate IT = new InlineTemplate
                {
                    Recipients = recipientsServerTemplate,
                    Sequence = (i+1).ToString()
                };

                InlineTemplates.Add(IT);
                ServerTemplates.Add(ST);
                CT.ServerTemplates = ServerTemplates;
                CT.InlineTemplates = InlineTemplates;
                compositeTemplates.Add(CT);

                i++;

               }

EnvelopeDefinition env = new EnvelopeDefinition
            {
                Status = "sent",
                CompositeTemplates = compositeTemplates
            };
</code>```

答:
Assuming each server template contains one document, the composite template with the lowest sequence number should show its template's document first.

If the sequence number doesn't work, then change the order of the composite template items within the array. Note that the envelope definition's compositeTemplates attribute takes an array of composite template objects.

I suggest that you first use the API Request Builder to try out the sequencing. The tool can then be used to generate the matching C# code.

Here's a live example with one server template used twice in an envelope. You can easily modify the diagram to use two different server templates.

Blog post about composite templates

Body:
Is there a way I could control the order of the documents presented to a signer when using composite templates?
If I have, for example, 3 templates that I want to send and I want the signer to see (not necessarily sign) a specific one first how would I set that.
All templates only have one document.
As far as I understand the sequence property for server and inline templates has more to do with the order of documents and tabs in specific composites not for the overall envelope.
Here is the c# code I have for now (not perfect, kind of a first draft). I have a few template Id's stored in a list of string and I'm looping through them assigning almost random sequencing values because I only care if the inline template sequence value is higher than the server template.
What I'm asking is if I have a template document that I would like to show first is there a way to do that? It doesn't have to implement looping. I just want to know if there is a way

 List<CompositeTemplate> compositeTemplates = new List<CompositeTemplate>();

            Recipients recipientsServerTemplate = new Recipients();
            List<Signer> signers = new List<Signer>();
            List<CarbonCopy> carbonCopies = new List<CarbonCopy>();

        List<Text> textControlsInTemplate = SetTemplateFields();

        Tabs tabs = new Tabs
        {
            TextTabs = textControlsInTemplate
        };

        Signer signer1 = new Signer();
        signer1.Email = signerEmail;
        signer1.Name = signerName;
        signer1.RoleName = "signer";
        signer1.RecipientId = "1";
        signer1.Tabs = tabs;
        signers.Add(signer1);

        CarbonCopy cc1 = new CarbonCopy();
        cc1.Email = ccEmail;
        cc1.Name = ccName;
        cc1.RoleName = "cc";
        cc1.RecipientId = "2";
        carbonCopies.Add(cc1);

        recipientsServerTemplate.Signers = signers;
        recipientsServerTemplate.CarbonCopies = carbonCopies;

int i = 1;
            foreach (string templateId in templateIds)
            {
                List<ServerTemplate> ServerTemplates = new List<ServerTemplate>();
                List<InlineTemplate> InlineTemplates = new List<InlineTemplate>();
                CompositeTemplate CT = new CompositeTemplate
                {
                    CompositeTemplateId = i.ToString()
                };

                ServerTemplate ST = new ServerTemplate
                {
                    Sequence = i.ToString(),
                    TemplateId = templateId
                };

                InlineTemplate IT = new InlineTemplate
                {
                    Recipients = recipientsServerTemplate,
                    Sequence = (i+1).ToString()
                };

                InlineTemplates.Add(IT);
                ServerTemplates.Add(ST);
                CT.ServerTemplates = ServerTemplates;
                CT.InlineTemplates = InlineTemplates;
                compositeTemplates.Add(CT);

                i++;

               }

EnvelopeDefinition env = new EnvelopeDefinition
            {
                Status = "sent",
                CompositeTemplates = compositeTemplates
            };


问:
datatype of the answer given while using itertools
Could anyone tell me what would be the data type of the answer given, while using itertools.combination(iterable, r)??</p>
```<code>from itertools import combinations
def rSubset(arr, r):

    return list(combinations(arr, r))
if __name__ == "__main__":
    arr = [1, 2, 3, 4]
    r = 2
    print (rSubset(arr, r))
</code>```

答:
itertools.combinations returns a reference to an itertools.combinations class which is iterable. To clarify this using your data:

```<code>from itertools import combinations

arr = [1, 2, 3, 4]

for comb in combinations(arr, 2):
  print(comb)
</code>```

Output:

```<code>(1, 2)
(1, 3)
(1, 4)
(2, 3)
(2, 4)
(3, 4)
</code>```

Body:
Could anyone tell me what would be the data type of the answer given, while using itertools.combination(iterable, r)??

from itertools import combinations
def rSubset(arr, r):

    return list(combinations(arr, r))
if __name__ == "__main__":
    arr = [1, 2, 3, 4]
    r = 2
    print (rSubset(arr, r))

Body:
itertools.combinations returns a reference to an itertools.combinations class which is iterable. To clarify this using your data:

from itertools import combinations

arr = [1, 2, 3, 4]

for comb in combinations(arr, 2):
  print(comb)

Output:

(1, 2)
(1, 3)
(1, 4)
(2, 3)
(2, 4)
(3, 4)


答:
I think you want to use animate:</p>

```<code>$("#join-wrapper-scroll").animate({"left": "-=600"}, 1000);
</code>```

Title: jQuery scrollTo plugin problem. Nothing's moving?

Body:
I think you want to use animate:

$("#join-wrapper-scroll").animate({"left": "-=600"}, 1000);


问:
In HTML, how can I have text that is only accessible for screen readers (i.e. for blind people)?
I have a website that has colored divs with numbers, e.g. a red block with the number 2 inside of it.  The color is important to understanding. A blind user emailed me asking if I could make it say "2 red" for his screen reader.

I tried adding this as an alt="2 red" but he said that didn't do anything. He thinks it might only read alt tags for images.

Is there a good way to do this for divs?

答:
```<code><div role="img" aria-label="red 2">
   <span aria-hidden="true">2</span>
</div>
</code>```

This will work. role="img" is necessary if you want the screen reader to read anything on mouse-hover.

Tested in ndva.

Body:
<div role="img" aria-label="red 2">
   <span aria-hidden="true">2</span>
</div>

This will work. role="img" is necessary if you want the screen reader to read anything on mouse-hover.

Tested in ndva.


问:
Pandas keep rows where column values change at least twice
Good day,

I have a large dataset with columns that keep track of the scores each person obtains. Here is a sample of the dataset:

In:

```<code>data = [[7, 10, 10, 10, 10], [17, 10, 10, 10, 10], [18, 8, 10, 10, 10], [20, 10, 10, 9, 9], [25, 9, 8, 8, 7]]
df = pd.DataFrame(data, columns = ['person_id', 'score_1', 'score_2', 'score_3', 'score_4'])
df
</code>```

Out:

```<code>    person_id   score_1 score_2 score_3 score_4
0   7           10      10      10      10
1   17          10      10      10      10
2   18          8       10      10      10
3   20          10      10      9       9
4   25          9       8       8       7
</code>```

I need to find the rows where the column values change at least twice. For example:

Row 0: All values are the same, no change

Row 1: All values are the same, no change

Row 2: 1st and 2nd values differ, 1 change

Row 3: 2nd and 3rd values differ, 1 change

Row 4: 1st, 2nd and 4th values differ, 2 changes

That means that only row 4 meets my requirements.

Thus, the desired output would be:

```<code>    person_id   score_1 score_2 score_3 score_4
4   25          9       8       8       7
</code>```

All help greatly appreciated!

答:
IIUC, you want to count the number of unique values, per rows, limited to the "score*" columns.

You can use nunique on the rows after getting the correct columns with filter. Then slice:

```<code>df[df.filter(like='score').nunique(axis=1).gt(2)]
</code>```

If you really want the changes from left to right so that A->B->A->B counts for 3 changes:

```<code>df[df.filter(like='score').diff(axis=1).ne(0).sum(axis=1).gt(2)]
</code>```

output:

```<code>   person_id  score_1  score_2  score_3  score_4
4         25        9        8        8        7
</code>```

Body:
Good day,

I have a large dataset with columns that keep track of the scores each person obtains. Here is a sample of the dataset:

In:

data = [[7, 10, 10, 10, 10], [17, 10, 10, 10, 10], [18, 8, 10, 10, 10], [20, 10, 10, 9, 9], [25, 9, 8, 8, 7]]
df = pd.DataFrame(data, columns = ['person_id', 'score_1', 'score_2', 'score_3', 'score_4'])
df

Out:

    person_id   score_1 score_2 score_3 score_4
0   7           10      10      10      10
1   17          10      10      10      10
2   18          8       10      10      10
3   20          10      10      9       9
4   25          9       8       8       7

I need to find the rows where the column values change at least twice. For example:

Row 0: All values are the same, no change

Row 1: All values are the same, no change

Row 2: 1st and 2nd values differ, 1 change

Row 3: 2nd and 3rd values differ, 1 change

Row 4: 1st, 2nd and 4th values differ, 2 changes

That means that only row 4 meets my requirements.

Thus, the desired output would be:

    person_id   score_1 score_2 score_3 score_4
4   25          9       8       8       7

All help greatly appreciated!

Body:
IIUC, you want to count the number of unique values, per rows, limited to the "score*" columns.

You can use nunique on the rows after getting the correct columns with filter. Then slice:

df[df.filter(like='score').nunique(axis=1).gt(2)]

If you really want the changes from left to right so that A->B->A->B counts for 3 changes:

df[df.filter(like='score').diff(axis=1).ne(0).sum(axis=1).gt(2)]

output:

   person_id  score_1  score_2  score_3  score_4
4         25        9        8        8        7


问:
not able to write spark dataframe to a parquet file format to C drive in PySpark,
The answer provided didn't work, link, as i am not able to comment yet, so made a post here
I am using the following command to try to write a spark (v3.2.0 using Ananaconda 3 Jupyter Notebook) dataframe to a parquet file in Pyspark and get a very strange error message that I cannot resolve. any help will be appreciated, i am not understanding this

```<code>df.write.mode("overwrite").parquet("test/")
</code>```

the error message is as follows -

```<code>    ---------------------------------------------------------------------------
Py4JJavaError                             Traceback (most recent call last)
<ipython-input-23-38311e135ec7> in <module>
----> 1 students.write.mode("overwrite").csv("students")

~\Anaconda3\lib\site-packages\pyspark\sql\readwriter.py in csv(self, path, mode, compression, sep, quote, escape, header, nullValue, escapeQuotes, quoteAll, dateFormat, timestampFormat, ignoreLeadingWhiteSpace, ignoreTrailingWhiteSpace, charToEscapeQuoteEscaping, encoding, emptyValue, lineSep)
    953                        charToEscapeQuoteEscaping=charToEscapeQuoteEscaping,
    954                        encoding=encoding, emptyValue=emptyValue, lineSep=lineSep)
--> 955         self._jwrite.csv(path)
    956
    957     def orc(self, path, mode=None, partitionBy=None, compression=None):

~\Anaconda3\lib\site-packages\py4j\java_gateway.py in __call__(self, *args)
   1307
   1308         answer = self.gateway_client.send_command(command)
-> 1309         return_value = get_return_value(
   1310             answer, self.gateway_client, self.target_id, self.name)
   1311

~\Anaconda3\lib\site-packages\pyspark\sql\utils.py in deco(*a, **kw)
    109     def deco(*a, **kw):
    110         try:
--> 111             return f(*a, **kw)
    112         except py4j.protocol.Py4JJavaError as e:
    113             converted = convert_exception(e.java_exception)

~\Anaconda3\lib\site-packages\py4j\protocol.py in get_return_value(answer, gateway_client, target_id, name)
    324             value = OUTPUT_CONVERTER[type](answer[2:], gateway_client)
    325             if answer[1] == REFERENCE_TYPE:
--> 326                 raise Py4JJavaError(
    327                     "An error occurred while calling {0}{1}{2}.\n".
    328                     format(target_id, ".", name), value)

Py4JJavaError: An error occurred while calling o111.csv.
: org.apache.spark.SparkException: Job aborted.
    at org.apache.spark.sql.errors.QueryExecutionErrors$.jobAbortedError(QueryExecutionErrors.scala:496)
    at org.apache.spark.sql.execution.datasources.FileFormatWriter$.write(FileFormatWriter.scala:251)
    at org.apache.spark.sql.execution.datasources.InsertIntoHadoopFsRelationCommand.run(InsertIntoHadoopFsRelationCommand.scala:186)
    at org.apache.spark.sql.execution.command.DataWritingCommandExec.sideEffectResult$lzycompute(commands.scala:113)
    at org.apache.spark.sql.execution.command.DataWritingCommandExec.sideEffectResult(commands.scala:111)
    at org.apache.spark.sql.execution.command.DataWritingCommandExec.executeCollect(commands.scala:125)
    at org.apache.spark.sql.execution.QueryExecution$$anonfun$eagerlyExecuteCommands$1.$anonfun$applyOrElse$1(QueryExecution.scala:110)
    at org.apache.spark.sql.execution.SQLExecution$.$anonfun$withNewExecutionId$5(SQLExecution.scala:103)
    at org.apache.spark.sql.execution.SQLExecution$.withSQLConfPropagated(SQLExecution.scala:163)
    at org.apache.spark.sql.execution.SQLExecution$.$anonfun$withNewExecutionId$1(SQLExecution.scala:90)
    at org.apache.spark.sql.SparkSession.withActive(SparkSession.scala:775)
    at org.apache.spark.sql.execution.SQLExecution$.withNewExecutionId(SQLExecution.scala:64)
    at org.apache.spark.sql.execution.QueryExecution$$anonfun$eagerlyExecuteCommands$1.applyOrElse(QueryExecution.scala:110)
    at org.apache.spark.sql.execution.QueryExecution$$anonfun$eagerlyExecuteCommands$1.applyOrElse(QueryExecution.scala:106)
    at org.apache.spark.sql.catalyst.trees.TreeNode.$anonfun$transformDownWithPruning$1(TreeNode.scala:481)
    at org.apache.spark.sql.catalyst.trees.CurrentOrigin$.withOrigin(TreeNode.scala:82)
    at org.apache.spark.sql.catalyst.trees.TreeNode.transformDownWithPruning(TreeNode.scala:481)
    at org.apache.spark.sql.catalyst.plans.logical.LogicalPlan.org$apache$spark$sql$catalyst$plans$logical$AnalysisHelper$$super$transformDownWithPruning(LogicalPlan.scala:30)
    at org.apache.spark.sql.catalyst.plans.logical.AnalysisHelper.transformDownWithPruning(AnalysisHelper.scala:267)
    at org.apache.spark.sql.catalyst.plans.logical.AnalysisHelper.transformDownWithPruning$(AnalysisHelper.scala:263)
    at org.apache.spark.sql.catalyst.plans.logical.LogicalPlan.transformDownWithPruning(LogicalPlan.scala:30)
    at org.apache.spark.sql.catalyst.plans.logical.LogicalPlan.transformDownWithPruning(LogicalPlan.scala:30)
    at org.apache.spark.sql.catalyst.trees.TreeNode.transformDown(TreeNode.scala:457)
    at org.apache.spark.sql.execution.QueryExecution.eagerlyExecuteCommands(QueryExecution.scala:106)
    at org.apache.spark.sql.execution.QueryExecution.commandExecuted$lzycompute(QueryExecution.scala:93)
    at org.apache.spark.sql.execution.QueryExecution.commandExecuted(QueryExecution.scala:91)
    at org.apache.spark.sql.execution.QueryExecution.assertCommandExecuted(QueryExecution.scala:128)
    at org.apache.spark.sql.DataFrameWriter.runCommand(DataFrameWriter.scala:848)
    at org.apache.spark.sql.DataFrameWriter.saveToV1Source(DataFrameWriter.scala:382)
    at org.apache.spark.sql.DataFrameWriter.saveInternal(DataFrameWriter.scala:355)
    at org.apache.spark.sql.DataFrameWriter.save(DataFrameWriter.scala:239)
    at org.apache.spark.sql.DataFrameWriter.csv(DataFrameWriter.scala:839)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
    at py4j.Gateway.invoke(Gateway.java:282)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.ClientServerConnection.waitForCommands(ClientServerConnection.java:182)
    at py4j.ClientServerConnection.run(ClientServerConnection.java:106)
    at java.lang.Thread.run(Thread.java:750)
Caused by: java.lang.UnsatisfiedLinkError: org.apache.hadoop.io.nativeio.NativeIO$Windows.access0(Ljava/lang/String;I)Z
    at org.apache.hadoop.io.nativeio.NativeIO$Windows.access0(Native Method)
    at org.apache.hadoop.io.nativeio.NativeIO$Windows.access(NativeIO.java:793)
    at org.apache.hadoop.fs.FileUtil.canRead(FileUtil.java:1215)
    at org.apache.hadoop.fs.FileUtil.list(FileUtil.java:1420)
    at org.apache.hadoop.fs.RawLocalFileSystem.listStatus(RawLocalFileSystem.java:601)
    at org.apache.hadoop.fs.FileSystem.listStatus(FileSystem.java:1972)
    at org.apache.hadoop.fs.FileSystem.listStatus(FileSystem.java:2014)
    at org.apache.hadoop.fs.ChecksumFileSystem.listStatus(ChecksumFileSystem.java:761)
    at org.apache.hadoop.fs.FileSystem.listStatus(FileSystem.java:1972)
    at org.apache.hadoop.fs.FileSystem.listStatus(FileSystem.java:2014)
    at org.apache.hadoop.mapreduce.lib.output.FileOutputCommitter.getAllCommittedTaskPaths(FileOutputCommitter.java:334)
    at org.apache.hadoop.mapreduce.lib.output.FileOutputCommitter.commitJobInternal(FileOutputCommitter.java:404)
    at org.apache.hadoop.mapreduce.lib.output.FileOutputCommitter.commitJob(FileOutputCommitter.java:377)
    at org.apache.spark.internal.io.HadoopMapReduceCommitProtocol.commitJob(HadoopMapReduceCommitProtocol.scala:182)
    at org.apache.spark.sql.execution.datasources.FileFormatWriter$.$anonfun$write$20(FileFormatWriter.scala:240)
    at scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.java:23)
    at org.apache.spark.util.Utils$.timeTakenMs(Utils.scala:605)
    at org.apache.spark.sql.execution.datasources.FileFormatWriter$.write(FileFormatWriter.scala:240)
    ... 42 more
</code>```

答:
Path should in below syntax.

In Windows file format always use \ and for linux file system use /

```<code>df.write.mode("overwrite").parquet(r"C:\Users\ravi\Notes\Spark")

</code>```

Body:
The answer provided didn't work, link, as i am not able to comment yet, so made a post here
I am using the following command to try to write a spark (v3.2.0 using Ananaconda 3 Jupyter Notebook) dataframe to a parquet file in Pyspark and get a very strange error message that I cannot resolve. any help will be appreciated, i am not understanding this

df.write.mode("overwrite").parquet("test/")

the error message is as follows -

    ---------------------------------------------------------------------------
Py4JJavaError                             Traceback (most recent call last)
<ipython-input-23-38311e135ec7> in <module>
----> 1 students.write.mode("overwrite").csv("students")

~\Anaconda3\lib\site-packages\pyspark\sql\readwriter.py in csv(self, path, mode, compression, sep, quote, escape, header, nullValue, escapeQuotes, quoteAll, dateFormat, timestampFormat, ignoreLeadingWhiteSpace, ignoreTrailingWhiteSpace, charToEscapeQuoteEscaping, encoding, emptyValue, lineSep)
    953                        charToEscapeQuoteEscaping=charToEscapeQuoteEscaping,
    954                        encoding=encoding, emptyValue=emptyValue, lineSep=lineSep)
--> 955         self._jwrite.csv(path)
    956
    957     def orc(self, path, mode=None, partitionBy=None, compression=None):

~\Anaconda3\lib\site-packages\py4j\java_gateway.py in __call__(self, *args)
   1307
   1308         answer = self.gateway_client.send_command(command)
-> 1309         return_value = get_return_value(
   1310             answer, self.gateway_client, self.target_id, self.name)
   1311

~\Anaconda3\lib\site-packages\pyspark\sql\utils.py in deco(*a, **kw)
    109     def deco(*a, **kw):
    110         try:
--> 111             return f(*a, **kw)
    112         except py4j.protocol.Py4JJavaError as e:
    113             converted = convert_exception(e.java_exception)

~\Anaconda3\lib\site-packages\py4j\protocol.py in get_return_value(answer, gateway_client, target_id, name)
    324             value = OUTPUT_CONVERTER[type](answer[2:], gateway_client)
    325             if answer[1] == REFERENCE_TYPE:
--> 326                 raise Py4JJavaError(
    327                     "An error occurred while calling {0}{1}{2}.\n".
    328                     format(target_id, ".", name), value)

Py4JJavaError: An error occurred while calling o111.csv.
: org.apache.spark.SparkException: Job aborted.
    at org.apache.spark.sql.errors.QueryExecutionErrors$.jobAbortedError(QueryExecutionErrors.scala:496)
    at org.apache.spark.sql.execution.datasources.FileFormatWriter$.write(FileFormatWriter.scala:251)
    at org.apache.spark.sql.execution.datasources.InsertIntoHadoopFsRelationCommand.run(InsertIntoHadoopFsRelationCommand.scala:186)
    at org.apache.spark.sql.execution.command.DataWritingCommandExec.sideEffectResult$lzycompute(commands.scala:113)
    at org.apache.spark.sql.execution.command.DataWritingCommandExec.sideEffectResult(commands.scala:111)
    at org.apache.spark.sql.execution.command.DataWritingCommandExec.executeCollect(commands.scala:125)
    at org.apache.spark.sql.execution.QueryExecution$$anonfun$eagerlyExecuteCommands$1.$anonfun$applyOrElse$1(QueryExecution.scala:110)
    at org.apache.spark.sql.execution.SQLExecution$.$anonfun$withNewExecutionId$5(SQLExecution.scala:103)
    at org.apache.spark.sql.execution.SQLExecution$.withSQLConfPropagated(SQLExecution.scala:163)
    at org.apache.spark.sql.execution.SQLExecution$.$anonfun$withNewExecutionId$1(SQLExecution.scala:90)
    at org.apache.spark.sql.SparkSession.withActive(SparkSession.scala:775)
    at org.apache.spark.sql.execution.SQLExecution$.withNewExecutionId(SQLExecution.scala:64)
    at org.apache.spark.sql.execution.QueryExecution$$anonfun$eagerlyExecuteCommands$1.applyOrElse(QueryExecution.scala:110)
    at org.apache.spark.sql.execution.QueryExecution$$anonfun$eagerlyExecuteCommands$1.applyOrElse(QueryExecution.scala:106)
    at org.apache.spark.sql.catalyst.trees.TreeNode.$anonfun$transformDownWithPruning$1(TreeNode.scala:481)
    at org.apache.spark.sql.catalyst.trees.CurrentOrigin$.withOrigin(TreeNode.scala:82)
    at org.apache.spark.sql.catalyst.trees.TreeNode.transformDownWithPruning(TreeNode.scala:481)
    at org.apache.spark.sql.catalyst.plans.logical.LogicalPlan.org$apache$spark$sql$catalyst$plans$logical$AnalysisHelper$$super$transformDownWithPruning(LogicalPlan.scala:30)
    at org.apache.spark.sql.catalyst.plans.logical.AnalysisHelper.transformDownWithPruning(AnalysisHelper.scala:267)
    at org.apache.spark.sql.catalyst.plans.logical.AnalysisHelper.transformDownWithPruning$(AnalysisHelper.scala:263)
    at org.apache.spark.sql.catalyst.plans.logical.LogicalPlan.transformDownWithPruning(LogicalPlan.scala:30)
    at org.apache.spark.sql.catalyst.plans.logical.LogicalPlan.transformDownWithPruning(LogicalPlan.scala:30)
    at org.apache.spark.sql.catalyst.trees.TreeNode.transformDown(TreeNode.scala:457)
    at org.apache.spark.sql.execution.QueryExecution.eagerlyExecuteCommands(QueryExecution.scala:106)
    at org.apache.spark.sql.execution.QueryExecution.commandExecuted$lzycompute(QueryExecution.scala:93)
    at org.apache.spark.sql.execution.QueryExecution.commandExecuted(QueryExecution.scala:91)
    at org.apache.spark.sql.execution.QueryExecution.assertCommandExecuted(QueryExecution.scala:128)
    at org.apache.spark.sql.DataFrameWriter.runCommand(DataFrameWriter.scala:848)
    at org.apache.spark.sql.DataFrameWriter.saveToV1Source(DataFrameWriter.scala:382)
    at org.apache.spark.sql.DataFrameWriter.saveInternal(DataFrameWriter.scala:355)
    at org.apache.spark.sql.DataFrameWriter.save(DataFrameWriter.scala:239)
    at org.apache.spark.sql.DataFrameWriter.csv(DataFrameWriter.scala:839)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
    at py4j.Gateway.invoke(Gateway.java:282)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.ClientServerConnection.waitForCommands(ClientServerConnection.java:182)
    at py4j.ClientServerConnection.run(ClientServerConnection.java:106)
    at java.lang.Thread.run(Thread.java:750)
Caused by: java.lang.UnsatisfiedLinkError: org.apache.hadoop.io.nativeio.NativeIO$Windows.access0(Ljava/lang/String;I)Z
    at org.apache.hadoop.io.nativeio.NativeIO$Windows.access0(Native Method)
    at org.apache.hadoop.io.nativeio.NativeIO$Windows.access(NativeIO.java:793)
    at org.apache.hadoop.fs.FileUtil.canRead(FileUtil.java:1215)
    at org.apache.hadoop.fs.FileUtil.list(FileUtil.java:1420)
    at org.apache.hadoop.fs.RawLocalFileSystem.listStatus(RawLocalFileSystem.java:601)
    at org.apache.hadoop.fs.FileSystem.listStatus(FileSystem.java:1972)
    at org.apache.hadoop.fs.FileSystem.listStatus(FileSystem.java:2014)
    at org.apache.hadoop.fs.ChecksumFileSystem.listStatus(ChecksumFileSystem.java:761)
    at org.apache.hadoop.fs.FileSystem.listStatus(FileSystem.java:1972)
    at org.apache.hadoop.fs.FileSystem.listStatus(FileSystem.java:2014)
    at org.apache.hadoop.mapreduce.lib.output.FileOutputCommitter.getAllCommittedTaskPaths(FileOutputCommitter.java:334)
    at org.apache.hadoop.mapreduce.lib.output.FileOutputCommitter.commitJobInternal(FileOutputCommitter.java:404)
    at org.apache.hadoop.mapreduce.lib.output.FileOutputCommitter.commitJob(FileOutputCommitter.java:377)
    at org.apache.spark.internal.io.HadoopMapReduceCommitProtocol.commitJob(HadoopMapReduceCommitProtocol.scala:182)
    at org.apache.spark.sql.execution.datasources.FileFormatWriter$.$anonfun$write$20(FileFormatWriter.scala:240)
    at scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.java:23)
    at org.apache.spark.util.Utils$.timeTakenMs(Utils.scala:605)
    at org.apache.spark.sql.execution.datasources.FileFormatWriter$.write(FileFormatWriter.scala:240)
    ... 42 more

Body:
Path should in below syntax.

In Windows file format always use \ and for linux file system use /

df.write.mode("overwrite").parquet(r"C:\Users\ravi\Notes\Spark")


问:
Bash script - How to preserve new line character passed to bash function?
I have two files:

```<code>touch a.txt
touch b.txt
</code>```

In bash I would like to list them each one in its own line.

```<code>#!/bin/bash
var=$(ls -1 *.txt)
echo "$var"
</code>```

Because there are double quotes in: echo "$var" command each of file is displayed in separate lines (that is what I want):

```<code>a.txt
b.txt
</code>```

Now to the problem. If I add function:

```<code>#!/bin/bash
function fun_cmd () {
     $1
}
var=$(ls -1 *.txt)
fun_cmd "echo $var"
</code>```

and echo command displays them in one single line:

```<code>a.txt b.txt
</code>```

In the last sample (function), I would like output to be displayed in two lines, just like first sample.

答:
Always quote correctly!

Don't use a single argument, but all argument of your function with "$@"

```<code>#!/usr/bin/env bash
function fun_cmd () {
     "$@"
}
var="$(ls -1 -- *txt)"
fun_cmd echo "$var"
</code>```

Body:
I have two files:

touch a.txt
touch b.txt

In bash I would like to list them each one in its own line.

#!/bin/bash
var=$(ls -1 *.txt)
echo "$var"

Because there are double quotes in: echo "$var" command each of file is displayed in separate lines (that is what I want):

a.txt
b.txt

Now to the problem. If I add function:

#!/bin/bash
function fun_cmd () {
     $1
}
var=$(ls -1 *.txt)
fun_cmd "echo $var"

and echo command displays them in one single line:

a.txt b.txt

In the last sample (function), I would like output to be displayed in two lines, just like first sample.

Body:
Always quote correctly!

Don't use a single argument, but all argument of your function with "$@"

#!/usr/bin/env bash
function fun_cmd () {
     "$@"
}
var="$(ls -1 -- *txt)"
fun_cmd echo "$var"


问:
First three items of of NSArray into an NSString?
What would be the most efficient way of turning the first three objects (or 1 or 2 if that's how big the array is) of an array, into a string, which is comma-separated. I've got a feeling there is a way to this with blocks, but I can't work it out

The objects are Bands, stored in bandArray, and the attributes of each band include a bandName.

So the output would be something like

```<code>String
"Abba"                    <- when there is one object
"Abba, Kiss"              <- when there is two objects
"Abba, Kiss, Nirvana"     <- when there is three objects
"Abba, Kiss, Nirvana"     <- when there is four objects. after three, names are ignored
</code>```

答:
You can use subarrayWithRange: for that:

```<code>NSString *res = [[[theArray subarrayWithRange:NSMakeRange(0, fmin(3, [theArray count]))]
                  valueForKey:@"brandName"]
                 componentsJoinedByString:@", "];
</code>```

Body:
What would be the most efficient way of turning the first three objects (or 1 or 2 if that's how big the array is) of an array, into a string, which is comma-separated. I've got a feeling there is a way to this with blocks, but I can't work it out

The objects are Bands, stored in bandArray, and the attributes of each band include a bandName.

So the output would be something like

String
"Abba"                    <- when there is one object
"Abba, Kiss"              <- when there is two objects
"Abba, Kiss, Nirvana"     <- when there is three objects
"Abba, Kiss, Nirvana"     <- when there is four objects. after three, names are ignored

Body:
You can use subarrayWithRange: for that:

NSString *res = [[[theArray subarrayWithRange:NSMakeRange(0, fmin(3, [theArray count]))]
                  valueForKey:@"brandName"]
                 componentsJoinedByString:@", "];


问:
how can i check if Website is currently available
I'm trying to get an exception when I try to download a file from a website. My current way is to download a .zip file from the website and check the file size of the .zip. I think that's not the best way to check if a website exists. Maybe some of you have a better idea for checking if a website is currently available, and if it isn't than get an error 404 exception.

答:
It depends on what you want to achieve.

If you just want to know if there is something alive, just use a plain TCP socket and try to connection to port 80 (HTTP) or 443 (HTTPS). If the connection is successful, close it and assume a website is there.

If you want to be sure this is a website that responds, then you must issue an HTTP command that transfers the minimum data. You can send a HEAD command for that.

If you want to get a file, just try to get it, and check the status code for success or failure.