问:
Username not inserting and relationships broken
```<code>public function index()
{
    //
    $users = \App\User::with(['roles','profile'])->get();
    return view('dashboard.users.index',compact('users'));
}

/**
 * Show the form for creating a new resource.
 *
 * @return \Illuminate\Http\Response
 */
public function create()
{
    //
    $roles = \App\Role::all();
    $countries = \App\Country::all();
    return view('dashboard.users.create',compact('countries','roles'));
}

/**
 * Store a newly created resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function store(Request $request)
{
    //
    $user = [
        'username' => $request->username,
        'name' => $request->name,
        'email' => $request->email,
        'password' => bcrypt($request->password),
    ];
    $user = \App\User::create($user);
           $filename = sprintf('thumbnail_%s.jpg',random_int(1, 1000));
    if ($request->hasFile('photo'))
     $filename = $request->file('photo')->storeAs('profiles',$filename,'public');
 else
    $filename = "profiles/dummy.jpg";
if ($user) {
    $profile = new \App\UserProfile([
        'user_id' => $user->id,
        'city' => $request->city,
        'country_id' => $request->country,
        'photo' => $filename,
        'phone' => $request->phone,
    ]);
    $user->profile()->save($profile);
    $user->roles()->attach($request->roles);
    return redirect()->route('users.index');
}
</code>```

}

This is controller

```<code>@extends('dashboard.layout')
@section('content')
<form action="{{route('users.store')}}" method="post" enctype="multipart/form-data">
    @csrf
    <div class="form-row align-item-center">
        <div class="col-md-12">
            <label for="inputUsername"> Name</label>
            <input type="text" class="form-control mb-2" name="username" id="inputUsername" placeholder="UserName">
        </div>
        <div class="col-md-12">
            <label for="inputName">Full Name</label>
            <input type="text" name="name" class="form-control mb-2" id="inputName" placeholder="Full Name">
        </div>
        <div class="col-md-12">
            <label for="inputUserEmail">Email</label>
            <input type="email" class="form-control mb-2" name="email" id="inputUserEmail" placeholder="Enter a valid Email">
        </div>
        <div class="col-md-12">
            <label for="inputPassword">Password</label>
            <input type="password" name="password" class="form-control mb-2" id="inputPassword" placeholder="************">
        </div>
        <div class="col-md-12">
            <label for="inputPhone">Phone</label>
            <input type="text" name="phone" class="form-control mb-2" id="inputPhone" placeholder="+923132244567">
        </div>
        <div class="col-md-12">
            <label for="selectCountry">Select Country</label>
            <select name="country" id="" class="form-control">
                @if(!$countries->isEmpty())
                @foreach($countries as $country)
                <option value="{{$country->id}}">{{$country->name}}</option>
                @endforeach
                @endif
            </select>
        </div>
        <div class="col-md-12 mt-3">
            <label for="inputCity">City</label>
            <input type="text" name="city" class="form-control mb-2" id="inputCity" placeholder="Enter Your City Name">
        </div>
        <div class="col-md-12">
            <label for="selectRoles">Select Roles</label>
            <select name="roles[]" id="selectRoles" class="form-control" multiple>
                @if(!$roles->isEmpty())
                @foreach($roles as $role)
                <option value="{{$role->id}}">{{$role->name}}</option>
                @endforeach
                @endif
            </select>
        </div>
        <div class="col-md-12 my-3">
            <label for="inputFileName">Profile Image</label>
            <input type="file" name="photo" class="form-custom-control mb-2" id="inputFileName">
        </div>
        <div class="col-md-12">
        <button type="submit" class="btn btn-primary mb-2">Add New User</button>
    </div>
</div>
</form>
@endsection
</code>```

This is view

```<code>class User extends Authenticatable
{
    use Notifiable;

    // protected $table = 'user';

    protected $primaryKey = 'username';

    protected $keyType = 'string';

    public $incrementing = false;

    /**
     * The name of the "created at" column.
     *
     * @var string
     */
    const CREATED_AT = 'created_at';

    /**
     * The name of the "updated at" column.
     *
     * @var string
     */
    const UPDATED_AT = 'updated_at';

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

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token','email'
    ];

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

    // public static function boot(){
    //     parent::boot();
    //     static::addGlobalScope('vfu',function(Builder $builder){
    //         return $builder->where('email_verified_at',"<>",null);

    //     });

        // public static function boot()
        // {
        //     parent::boot();
        //     static::addGlobalScope(new VerifiedUsers);

        // static::addGlobalScope(new NotVerifiedUsers);

        // static::addGlobalScope('nvfu',function(Builder $builder){
        //     return $builder->where('email_verified_at','=',null);

        //  // App\User::withoutGlobalScope('nvfu')->get();
        // });
    public function scopeVfu($query){
        return $query->where('email_verified_at','<>',null);

    }
    public function scopeNvfu($query){
        return $query->where('email_verified_at','=',null);

    }
    public function scopeFindById($query,$id)
    {
        return $query->where('id',$id);
    }
    public function profile()
    {
        return $this->hasOne(UserProfile::class,'user_id','id');
    }
    public function posts()
    {
        return $this->hasMany(Post::class,'user_id','id');
    }
    public function roles()
    {
        return $this->belongsToMany(Role::class,'role_user','user_id','role_id','id');
    }
}
</code>```

This is User Model

```<code>class UserProfile extends Model
{
    protected $guard = [];

    public function user()
    {
        return $this->belongsTo(User::class,'user_id','id');
    }
    public function country()
    {
        return $this->belongsTo(Country::class,'country_id','id');
    }
}
</code>```

This is UserProfile Model

```<code>class Country extends Model
{
    protected $guarded = [];

    public function posts()
    {
        return $this->hasManyThrough(Post::class,UserProfile::class,'country_id','user_id','id','user_id');
    }
}
</code>```

This is Country Model

I have use this code,In this code doens't insert username value i have changed in migration use nullable function and migrate refresh then relationships were broken and when create user and get Add [user_id] to fillable property to allow mass assignment on [App\UserProfile].  error

https://gist.github.com/Hammad964/85fb516517f0bc7163885bff167d29e0 this is github link please any one solve these problems

答:
I think it is because you haven't added username to your $fillable array within your User model.

It should be:

```<code>protected $fillable = [
    'name', 'email', 'password', 'username',
];
</code>```

Update:

In your UserProfile model. You have a line that is protected $guard = []; but laravel is expecting it to be protected $guarded = [];

Doing this allows all columns for the model to be mass assigneable so it is normally advisable to use the $fillable approach or to at least add the fields that do not need to be mass assigneable to the $guarded array to reduce the security risk for your application.

I hope this helps!

Body:
public function index()
{
    //
    $users = \App\User::with(['roles','profile'])->get();
    return view('dashboard.users.index',compact('users'));
}

/**
 * Show the form for creating a new resource.
 *
 * @return \Illuminate\Http\Response
 */
public function create()
{
    //
    $roles = \App\Role::all();
    $countries = \App\Country::all();
    return view('dashboard.users.create',compact('countries','roles'));
}

/**
 * Store a newly created resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function store(Request $request)
{
    //
    $user = [
        'username' => $request->username,
        'name' => $request->name,
        'email' => $request->email,
        'password' => bcrypt($request->password),
    ];
    $user = \App\User::create($user);
           $filename = sprintf('thumbnail_%s.jpg',random_int(1, 1000));
    if ($request->hasFile('photo'))
     $filename = $request->file('photo')->storeAs('profiles',$filename,'public');
 else
    $filename = "profiles/dummy.jpg";
if ($user) {
    $profile = new \App\UserProfile([
        'user_id' => $user->id,
        'city' => $request->city,
        'country_id' => $request->country,
        'photo' => $filename,
        'phone' => $request->phone,
    ]);
    $user->profile()->save($profile);
    $user->roles()->attach($request->roles);
    return redirect()->route('users.index');
}

}

This is controller

@extends('dashboard.layout')
@section('content')
<form action="{{route('users.store')}}" method="post" enctype="multipart/form-data">
    @csrf

             Name
            <input type="text" class="form-control mb-2" name="username" id="inputUsername" placeholder="UserName">

            Full Name
            <input type="text" name="name" class="form-control mb-2" id="inputName" placeholder="Full Name">

            Email
            <input type="email" class="form-control mb-2" name="email" id="inputUserEmail" placeholder="Enter a valid Email">

            Password
            <input type="password" name="password" class="form-control mb-2" id="inputPassword" placeholder="************">

            Phone
            <input type="text" name="phone" class="form-control mb-2" id="inputPhone" placeholder="+923132244567">

            Select Country
            <select name="country" id="" class="form-control">
                @if(!$countries->isEmpty())
                @foreach($countries as $country)
                <option value="{{$country->id}}">{{$country->name}}</option>
                @endforeach
                @endif
            </select>

            City
            <input type="text" name="city" class="form-control mb-2" id="inputCity" placeholder="Enter Your City Name">

            Select Roles
            <select name="roles[]" id="selectRoles" class="form-control" multiple>
                @if(!$roles->isEmpty())
                @foreach($roles as $role)
                <option value="{{$role->id}}">{{$role->name}}</option>
                @endforeach
                @endif
            </select>

            Profile Image
            <input type="file" name="photo" class="form-custom-control mb-2" id="inputFileName">

        <button type="submit" class="btn btn-primary mb-2">Add New User</button>

</form>
@endsection

This is view

class User extends Authenticatable
{
    use Notifiable;

    // protected $table = 'user';

    protected $primaryKey = 'username';

    protected $keyType = 'string';

    public $incrementing = false;

    /**
     * The name of the "created at" column.
     *
     * @var string
     */
    const CREATED_AT = 'created_at';

    /**
     * The name of the "updated at" column.
     *
     * @var string
     */
    const UPDATED_AT = 'updated_at';

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

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token','email'
    ];

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

    // public static function boot(){
    //     parent::boot();
    //     static::addGlobalScope('vfu',function(Builder $builder){
    //         return $builder->where('email_verified_at',"<>",null);

    //     });

        // public static function boot()
        // {
        //     parent::boot();
        //     static::addGlobalScope(new VerifiedUsers);

        // static::addGlobalScope(new NotVerifiedUsers);

        // static::addGlobalScope('nvfu',function(Builder $builder){
        //     return $builder->where('email_verified_at','=',null);

        //  // App\User::withoutGlobalScope('nvfu')->get();
        // });
    public function scopeVfu($query){
        return $query->where('email_verified_at','<>',null);

    }
    public function scopeNvfu($query){
        return $query->where('email_verified_at','=',null);

    }
    public function scopeFindById($query,$id)
    {
        return $query->where('id',$id);
    }
    public function profile()
    {
        return $this->hasOne(UserProfile::class,'user_id','id');
    }
    public function posts()
    {
        return $this->hasMany(Post::class,'user_id','id');
    }
    public function roles()
    {
        return $this->belongsToMany(Role::class,'role_user','user_id','role_id','id');
    }
}

This is User Model

class UserProfile extends Model
{
    protected $guard = [];

    public function user()
    {
        return $this->belongsTo(User::class,'user_id','id');
    }
    public function country()
    {
        return $this->belongsTo(Country::class,'country_id','id');
    }
}

This is UserProfile Model

class Country extends Model
{
    protected $guarded = [];

    public function posts()
    {
        return $this->hasManyThrough(Post::class,UserProfile::class,'country_id','user_id','id','user_id');
    }
}

This is Country Model

I have use this code,In this code doens't insert username value i have changed in migration use nullable function and migrate refresh then relationships were broken and when create user and get Add [user_id] to fillable property to allow mass assignment on [App\UserProfile].  error

https://gist.github.com/Hammad964/85fb516517f0bc7163885bff167d29e0 this is github link please any one solve these problems

Body:
I think it is because you haven't added username to your $fillable array within your User model.

It should be:

protected $fillable = [
    'name', 'email', 'password', 'username',
];

Update:

In your UserProfile model. You have a line that is protected $guard = []; but laravel is expecting it to be protected $guarded = [];

Doing this allows all columns for the model to be mass assigneable so it is normally advisable to use the $fillable approach or to at least add the fields that do not need to be mass assigneable to the $guarded array to reduce the security risk for your application.

I hope this helps!


来源: stackexchange

问:
WPF/XAML Style set Property for child items?
I working on a XAML style for my controls.
The code below is for setting the color of a stackpanel. It works fine but there is something else I want to do. If the trigger is activated I want to set the font color for all child items inside the stackpanel.

At the moment I only have textblocks inside the stackpanel and I know I could easily create a separate style for a textbock. But if this style is triggered it will only affect ONE and not ALL textblocks.
But I want to change all items inside the stackpanel as soon as I got a mouseover trigger for the panel.

Is this even possible in XAML or do I have to code a regular event?

```<code><Style x:Key="XStack" TargetType="StackPanel">
    <Setter Property="Background">
        <Setter.Value>
            <LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
                <GradientStop Color="White" Offset="0"/>
                <GradientStop Color="SkyBlue" Offset="6"/>
            </LinearGradientBrush>
        </Setter.Value>
    </Setter>
    <!-- Trigger-->
    <Style.Triggers>
        <Trigger Property="IsMouseOver" Value="True" >
            <Setter Property="Background" Value="SkyBlue"/>
        </Trigger>
    </Style.Triggers>
</Style>
</code>```

答:
Like Olle said, you can set the attached property TextElement.Foreground to a custom value. For a child control/UI node in the visual tree, if the property is not set, WPF will walk up the UI hierarchy till it finds a value and use it. This means that all child controls can share a property value defined at the parent level.

This should work for all TextBlocks... however if your StackPanel contained a TextBox, its text color wouldn't be affected. It uses the Foreground property from the Control base class... So be sure to test it out with all possible child element types.

OwnerDisplayName: Holli

ContentLicense: CC BY-SA 2.5

Body:
I working on a XAML style for my controls.
The code below is for setting the color of a stackpanel. It works fine but there is something else I want to do. If the trigger is activated I want to set the font color for all child items inside the stackpanel.

At the moment I only have textblocks inside the stackpanel and I know I could easily create a separate style for a textbock. But if this style is triggered it will only affect ONE and not ALL textblocks.
But I want to change all items inside the stackpanel as soon as I got a mouseover trigger for the panel.

Is this even possible in XAML or do I have to code a regular event?

</Style>

LastEditorDisplayName: Drew Noakes

OwnerDisplayName: Gishu


问:
How to convert a `const char *` to simply `char *`?
I'm using the pdCurses library and am aiming to only really use strings in my C++ console game but the curses mvinstr() function or any insert function requires a non-const char * as a parameter.

My solution at first to this problem was simply entering in string.c_str(), but that returns a const char * which apparently doesn't work with the function.

Next I put (char *)string.c_str() but this only causes an unhandled exception.

Finally I just tried char *test = string.c_str() but that's not compatible with const either.

What do I do to solve this?

K i just tried const_cast() and i still get an exception thrown and break....
I don't know why PDcurses only takes non-const char pointers.... =(

alright making a char* buffer didn't work when i used this code (time_s is the sting):

```<code>size_t length;
    char buffer[12];
    length=time_s.copy(buffer,5,0);
    buffer[length]='\0';
mvinstr(time_loc_y, time_loc_x, buffer);
</code>```

i even put a stop before mvinstr() and checked the buffer's contents which was "00   /0"
EXACTLY WHAT I WANTED.

but i get an access violation point to "xutility"....

答:
mvinstr(x,y,str) and others "take characters (or wide characters) from the current or specified position in the window, and return them as a string in str (or wstr)."

The function will actually modify the string, so you cannot safely cast the const away, especially since c_str specifies that you should not modify the returned string.

You need something along the lines of:

```<code>const MAX = 100;
char buf[MAX];
mvinnstr(x, y, buf, MAX);
...error checking...
string s = buf;
</code>```

Note that I avoided mvinstr in favour of mvinnstr to avoid the potential for buffer overflows.

ContentLicense: CC BY-SA 3.0

Body:
I'm using the pdCurses library and am aiming to only really use strings in my C++ console game but the curses mvinstr() function or any insert function requires a non-const char * as a parameter.

My solution at first to this problem was simply entering in string.c_str(), but that returns a const char * which apparently doesn't work with the function.

Next I put (char *)string.c_str() but this only causes an unhandled exception.

Finally I just tried char *test = string.c_str() but that's not compatible with const either.

What do I do to solve this?

K i just tried const_cast() and i still get an exception thrown and break....
I don't know why PDcurses only takes non-const char pointers.... =(

alright making a char* buffer didn't work when i used this code (time_s is the sting):

size_t length;
    char buffer[12];
    length=time_s.copy(buffer,5,0);
    buffer[length]='\0';
mvinstr(time_loc_y, time_loc_x, buffer);

i even put a stop before mvinstr() and checked the buffer's contents which was "00   /0"
EXACTLY WHAT I WANTED.

but i get an access violation point to "xutility"....

Body:
mvinstr(x,y,str) and others "take characters (or wide characters) from the current or specified position in the window, and return them as a string in str (or wstr)."

The function will actually modify the string, so you cannot safely cast the const away, especially since c_str specifies that you should not modify the returned string.

You need something along the lines of:

const MAX = 100;
char buf[MAX];
mvinnstr(x, y, buf, MAX);
...error checking...
string s = buf;

Note that I avoided mvinstr in favour of mvinnstr to avoid the potential for buffer overflows.


问:
Trying to group an array of objects under same keys resulting in a new array of objects
I have an array of messages consisting of objects, where each object represents a single message and the created_at key representing the date of the message. I am receiving this data from the API. Here is the structure that I get:

```<code>let messages = [
  {text: "A", status: 'r', created_at: "2020-02-06"},
  {text: "B", status: 's', created_at: "2020-02-06"},
  {text: "C", status: 'r', created_at: "2020-02-06"},
  {text: "D", status: 's', created_at: "2020-02-07"},
  {text: "E", status: 's', created_at: "2020-02-07"},
  {text: "F", status: 'r', created_at: "2020-02-09"},
  {text: "G", status: 's', created_at: "2020-02-09"},
  {text: "H", status: 's', created_at: "2020-02-10"}
]
</code>```

I am using vuejs to render these messages in a chat application (similar to WhatsApp), where I want to display the date on top and the messages under that date in chronological order, just like WhatsApp. I am receiving the messages from the API in chronological order like the messages array I pasted above.
I would like to have the following output, so that I can use v-for directive in vuejs to loop through the messages and render them according to the date they were created:

```<code>  output:
    [
      {
        dt: "2020-02-06",
        arr: [
            {text: "A", status: 'r', created_at: "2020-02-06"},
            {text: "B", status: 's', created_at: "2020-02-06"},
            {text: "C", status: 'r', created_at: "2020-02-06"},
        ]
      },
      {
        dt: "2020-02-07",
        arr: [
            {text: "D", status: 's', created_at: "2020-02-06"},
            {text: "E", status: 's', created_at: "2020-02-06"},
        ]
      },
      {
        dt: "2020-02-09",
        arr: [
            {text: "F", status: 'r', created_at: "2020-02-09"},
            {text: "G", status: 's', created_at: "2020-02-09"},
        ]
      },
        {
        dt: "2020-02-10",
        arr: [
           {text: "H", status: 's', created_at: "2020-02-10"}
        ]
      },
    ]
</code>```

Is there a library in lodash that can achieve this directly?

What I have tried so far:

I was able to group the dates in an array without the dates repeating, like so:

```<code>let dates = messages.map((item => {
    return item.created_at
}))
let uniq = [...new Set(dates)];
console.log(uniq)
</code>```

...which gives the following output:

```<code>uniq = ["2020-02-06", "2020-02-07", "2020-02-09", "2020-02-10"]
</code>```

I am not able to move ahead of this.

Thanks in advance!

答:
Use lodash to group by the created_at, and then map to the required format:

const messages = [
  {text: "A", status: 'r', created_at: "2020-02-06"},
  {text: "B", status: 's', created_at: "2020-02-06"},
  {text: "C", status: 'r', created_at: "2020-02-06"},
  {text: "D", status: 's', created_at: "2020-02-07"},
  {text: "E", status: 's', created_at: "2020-02-07"},
  {text: "F", status: 'r', created_at: "2020-02-09"},
  {text: "G", status: 's', created_at: "2020-02-09"},
  {text: "H", status: 's', created_at: "2020-02-10"}
]

const result = _.map(
  _.groupBy(messages, 'created_at'),
  (arr, dt) => ({ dt, arr })
)

console.log(result)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script></code>```

ContentLicense: CC BY-SA 4.0

Body:
I have an array of messages consisting of objects, where each object represents a single message and the created_at key representing the date of the message. I am receiving this data from the API. Here is the structure that I get:

let messages = [
  {text: "A", status: 'r', created_at: "2020-02-06"},
  {text: "B", status: 's', created_at: "2020-02-06"},
  {text: "C", status: 'r', created_at: "2020-02-06"},
  {text: "D", status: 's', created_at: "2020-02-07"},
  {text: "E", status: 's', created_at: "2020-02-07"},
  {text: "F", status: 'r', created_at: "2020-02-09"},
  {text: "G", status: 's', created_at: "2020-02-09"},
  {text: "H", status: 's', created_at: "2020-02-10"}
]

I am using vuejs to render these messages in a chat application (similar to WhatsApp), where I want to display the date on top and the messages under that date in chronological order, just like WhatsApp. I am receiving the messages from the API in chronological order like the messages array I pasted above.
I would like to have the following output, so that I can use v-for directive in vuejs to loop through the messages and render them according to the date they were created:

  output:
    [
      {
        dt: "2020-02-06",
        arr: [
            {text: "A", status: 'r', created_at: "2020-02-06"},
            {text: "B", status: 's', created_at: "2020-02-06"},
            {text: "C", status: 'r', created_at: "2020-02-06"},
        ]
      },
      {
        dt: "2020-02-07",
        arr: [
            {text: "D", status: 's', created_at: "2020-02-06"},
            {text: "E", status: 's', created_at: "2020-02-06"},
        ]
      },
      {
        dt: "2020-02-09",
        arr: [
            {text: "F", status: 'r', created_at: "2020-02-09"},
            {text: "G", status: 's', created_at: "2020-02-09"},
        ]
      },
        {
        dt: "2020-02-10",
        arr: [
           {text: "H", status: 's', created_at: "2020-02-10"}
        ]
      },
    ]

Is there a library in lodash that can achieve this directly?

What I have tried so far:

I was able to group the dates in an array without the dates repeating, like so:

let dates = messages.map((item => {
    return item.created_at
}))
let uniq = [...new Set(dates)];
console.log(uniq)

...which gives the following output:

uniq = ["2020-02-06", "2020-02-07", "2020-02-09", "2020-02-10"]

I am not able to move ahead of this.

Thanks in advance!

Body:
Use lodash to group by the created_at, and then map to the required format:

const messages = [
  {text: "A", status: 'r', created_at: "2020-02-06"},
  {text: "B", status: 's', created_at: "2020-02-06"},
  {text: "C", status: 'r', created_at: "2020-02-06"},
  {text: "D", status: 's', created_at: "2020-02-07"},
  {text: "E", status: 's', created_at: "2020-02-07"},
  {text: "F", status: 'r', created_at: "2020-02-09"},
  {text: "G", status: 's', created_at: "2020-02-09"},
  {text: "H", status: 's', created_at: "2020-02-10"}
]

const result = _.map(
  _.groupBy(messages, 'created_at'),
  (arr, dt) => ({ dt, arr })
)

console.log(result)

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>


问:
Is no of processor and paralell running threads are always same in .Net?
Suppose I create 10 new Task in a loop and run on 2 core processor, maximum how many threads can run in parallel. Is it 2 because all I have is 2 core processor?
Is it correct that there can be more than 2 threads created but only 2 threads run in parallel and there will be context switching with other threads?

答:
The number of processors used to execute a program is defined as the degree of parallelism.
So if you have n processors then only n threads could be run in parallel, all the other threads will be context switching.</p>


问:
How can I Read the file with Lua doing search filter and store the entries as a variable
So I want to read a text file with the following format:

Bob, G92f22f, Fggggfdff32
Rob, f3h9123, fdsgfdsg3
Sally, f2g4g, g3g3hgdsd
```

<p>I want a simple Lua program that can filter out say "bob" and then say throw the data into a variable to use in a program.</p>

<pre class="lang-lua prettyprint-override"><code>a = Bob
b = G92f22f
c = Fggggfdff32
</code>```

I assume then I could do
print(a,b,c)

Still quite new to Lua having a heck of a time with anything read / variable though.

答:
You'll want to look at the io and string modules; they handle things like reading from / writing to files and doing pattern matching on strings.

Luas pattern matching is a bit simple compared to the regular expressions most modern languages use, but from what I see in your example, you could probably match a "word" as [^, ]+, that is, one or more characters that aren't a comma or a space

Body:
So I want to read a text file with the following format:

Bob, G92f22f, Fggggfdff32
Rob, f3h9123, fdsgfdsg3
Sally, f2g4g, g3g3hgdsd

I want a simple Lua program that can filter out say "bob" and then say throw the data into a variable to use in a program.

a = Bob
b = G92f22f
c = Fggggfdff32

I assume then I could do
print(a,b,c)

Still quite new to Lua having a heck of a time with anything read / variable though.


问:
Interlinear text editor
Is there a way in Java to display interlinear text so you can make only the alternate (odd-numbered xor even-numbered) lines editable? And, if so, would it be possible for the user to dynamically select which of the two sets of lines is editable?

Could this be simulated with two separate panels one on top of the other where the upper one has a transparent background?

答: jEdit provides an editor pane that allows for collapsing/expanding controls within the textual content.  See the screenshot at http://www.jedit.org/index.php?page=screenshot&image=22</p>

Title: Interlinear text editor


问:
GraphQL Clojure: Getting the GQL query fields
I'm using lacinia library for my GraphQL Clojure server.

For this simple schema:

```<code>input QueryConfig {
  startDate: String!
  endDate: String!
}

type MyData{
  x: Float!
  y: Float!
  z: Float!
}

schema {
    query: Query
}

type Query {
  myQuery(config:QueryConfig) : [MyData]
}
</code>```

I'm posting the following query:

```<code>{
  myQuery(config:{startDate:"2020-01-01",endDate:"2020-01-01"}){
    x
  }
}
</code>```

In my resolver code, I would like to know what fields were asked (x in the example above), So I won't over fetch results from my DB and retrieve only the x values.

In the resolver code the context contains :graphql-query key which contains the entire query. However, parsing the query text seems awkward.

```<code>(defn my-resolver
  [context args value]
  ;TODO find out what fields were asked and fetch from DB
  )
</code>```

What would be the right way of getting the query fields?

答:
From the docs:

It is also possible to get all the fields that will be selected, using
  selections-seq. This a lazy, breadth-first navigation of all fields in
  the selection tree.

So you can use: (executor/selections-seq context) to get all fields that were sent by the query.

Body:
I'm using lacinia library for my GraphQL Clojure server.

For this simple schema:

input QueryConfig {
  startDate: String!
  endDate: String!
}

type MyData{
  x: Float!
  y: Float!
  z: Float!
}

schema {
    query: Query
}

type Query {
  myQuery(config:QueryConfig) : [MyData]
}

I'm posting the following query:

{
  myQuery(config:{startDate:"2020-01-01",endDate:"2020-01-01"}){
    x
  }
}

In my resolver code, I would like to know what fields were asked (x in the example above), So I won't over fetch results from my DB and retrieve only the x values.

In the resolver code the context contains :graphql-query key which contains the entire query. However, parsing the query text seems awkward.

(defn my-resolver
  [context args value]
  ;TODO find out what fields were asked and fetch from DB
  )

What would be the right way of getting the query fields?


问:
How can I make timediff functions returned negative time to positive?
I have query where I have to find the difference between two times , it works well when the first time is greater than the second time .

But when the first one is smaller than the second one it returns a negative time; Just wondering is there any way to make it positive?

Below is the query that returns negative time.

```<code>SELECT TIMEDIFF("13:10:11", "13:20:10");
</code>```

output

```<code>-00:09:59
</code>```

expected output

```<code>00:09:59
</code>```

答:
If what you want is to get the absolute time difference between two times, you could use a CASE expression to swap the times so that the first was always greater than the second e.g.

```<code>SELECT CASE WHEN time1 < time2 THEN TIMEDIFF(time2, time1)
            ELSE TIMEDIFF(time1, time2)
       END AS delta
</code>```

Body:
I have query where I have to find the difference between two times , it works well when the first time is greater than the second time .

But when the first one is smaller than the second one it returns a negative time; Just wondering is there any way to make it positive?

Below is the query that returns negative time.

SELECT TIMEDIFF("13:10:11", "13:20:10");

output

-00:09:59

expected output

00:09:59

Body:
If what you want is to get the absolute time difference between two times, you could use a CASE expression to swap the times so that the first was always greater than the second e.g.

SELECT CASE WHEN time1 < time2 THEN TIMEDIFF(time2, time1)
            ELSE TIMEDIFF(time1, time2)
       END AS delta


问:
Modify inputType:number|phone Android Studio
Is it possible to modify inputType:Phone in android studio somehow?
It would be handy to get the # * keys to other icons and submit. The only way to submit now is to press back button on the phone to get out of the input-keypad. </p>

答:
add these two lines in your EditText xml

```<code><EditText
 android:imeOptions="actionGo"
 android:inputType="number"/>
//the action button of keyboard will change to go button
</code>```

then you can set on click of that button in java

```<code>edittext.setOnEditorActionListener(new OnEditorActionListener() {
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
    if (actionId == EditorInfo.IME_ACTION_GO) {
        Log.i(TAG,"Here you can perform actions");   //like btn.performClick();
        return true;
    }
    return false;
}
});
</code>```

Body:
add these two lines in your EditText xml

<EditText
 android:imeOptions="actionGo"
 android:inputType="number"/>
//the action button of keyboard will change to go button

then you can set on click of that button in java

edittext.setOnEditorActionListener(new OnEditorActionListener() {
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
    if (actionId == EditorInfo.IME_ACTION_GO) {
        Log.i(TAG,"Here you can perform actions");   //like btn.performClick();
        return true;
    }
    return false;
}
});


问:
Installing Shell Commands in Atom on macOS returns error and fails
I wanted to install shell commands on my MacBook Air 2017 (macOS: 10.15.3) in Atom. It asks for my root password and then returns an error in Atom:

```<code>Failed to install shell commands
mkdir failed with exit status 1
</code>```

How do I fix this and install shell commands?
When I try which atom in Terminal, it returns with atom not found

答:
Can you provide more information? What command have you used (mkdir)? Is that directory already exists? Have you installed atom command?

This might help you

Body:
I wanted to install shell commands on my MacBook Air 2017 (macOS: 10.15.3) in Atom. It asks for my root password and then returns an error in Atom:

Failed to install shell commands
mkdir failed with exit status 1

How do I fix this and install shell commands?
When I try which atom in Terminal, it returns with atom not found


问:
Need Clarity on the Implementation Part of the Diamond Problem
Answers for Why multiple inheritances are not possible?

If there is a method in A that B and C have overridden, and D does not override it, then which version of the method does D inherit: that of B, or that of C?

Okay. Fine

Why it does not apply to Interfaces?
Because it is not implemented.

This answer is confusing to me. I have seen many articles talking about why multiple inheritances with class are not possible and they never talk about the implementation. When we ask the same question about Interfaces, they don't go with the same logic and now they are saying the code is not implemented. Why don't we go with the same logic? Its implementation is the real problem here? Please address only this part.

答:
Interface is a contract that specify what method the class need to implement, so when you call this method there is only one implementation, unlike multiple inheritance where the compiler wouldn't know what method to take.

In multiple inheritance

```<code>class A
{
    public void DoSomething() {}
}

class B
{
    public void DoSomething() {}
}

class C : A, B
{
    public override void DoSomething() {} // which DoSomething() is it?
}
</code>```

In multiple interfaces

```<code>interface A
{
    void DoSomething();
}

interface B
{
    void DoSomething();
}

class C : A, B {
    public void DoSomething() { }
}
</code>```

DoSomething() is implemented in class C, so the contract with both interfaces is fulfilled.

Body:
Interface is a contract that specify what method the class need to implement, so when you call this method there is only one implementation, unlike multiple inheritance where the compiler wouldn't know what method to take.

In multiple inheritance

class A
{
    public void DoSomething() {}
}

class B
{
    public void DoSomething() {}
}

class C : A, B
{
    public override void DoSomething() {} // which DoSomething() is it?
}

In multiple interfaces

interface A
{
    void DoSomething();
}

interface B
{
    void DoSomething();
}

class C : A, B {
    public void DoSomething() { }
}

DoSomething() is implemented in class C, so the contract with both interfaces is fulfilled.


问:
AttributeError: 'Button' object has no attribute
I try to bind a function (in .py) to button (in kv.) after directory selection with Filechooser (all at one Screen) as follows:

.py:

```<code>class SyllWindow(Screen): #screen where all happens

    def select(self, *args):

        if args[1]:

            filepath = args[1][0]

            try: self.label.text = filepath

            except: pass

    def output_csv(corpus_root): #function

        corpus = PlaintextCorpusReader(corpus_root, '.*') #this must be irrelevant actually
        def reduce_dip(corpus_string):
            corpus_string = corpus_string.replace("Ei", "ö")
            corpus_string = corpus_string.replace("ei", "ö")
            # reduced
            corpus_string = corpus_string.replace("ie", "ö")
            return corpus_string
        vowels = [' ','a','e','i','o','u','ä','ö','ü','A','E','I','O','U','Ä','Ö','Ü']
        cfd_syll = nltk.ConditionalFreqDist(
            (textname, num_syll)
            for textname in corpus.fileids()
            for num_syll in [len(w) for w in ''.join(char for char in reduce_dip(corpus.raw(fileids=textname)) if char in vowels).split()])
        syll_dataframe = DataFrame(cfd_syll)
        return syll_dataframe.to_csv(path + '\silben.csv')

    pass
</code>```

.kv (button block):

```<code>Button:

                            text: '.csv'
                            font_size: 14
                            on_release: self.output_csv(self.filepath)
</code>```

Looks like this:

After pressing ".csv" I get an error AttributeError: 'Button' object has no attribute 'output_csv'
I'm aware of similar issues described here, here and here, but all examples there are in Python language, while my issue seems to be more about Kivy language.

I'd be grateful for any advice.

Full error traceback:

```<code>File "C:\Users\gavrk\AppData\Local\Programs\Python\Python37-32\Lib\runpy.py", line 193, in _run_module_as_main
  "__main__", mod_spec)
File "C:\Users\gavrk\AppData\Local\Programs\Python\Python37-32\Lib\runpy.py", line 85, in _run_code
  exec(code, run_globals)
File "C:\GUI Projects\gercort\main.py", line 147, in <module>
  Gercort().run()
File "C:\Users\gavrk\AppData\Local\Programs\Python\Python37-32\Lib\site-packages\kivy\app.py", line 855, in run
  runTouchApp()
File "C:\Users\gavrk\AppData\Local\Programs\Python\Python37-32\Lib\site-packages\kivy\base.py", line 504, in runTouchApp
  EventLoop.window.mainloop()
File "C:\Users\gavrk\AppData\Local\Programs\Python\Python37-32\Lib\site-packages\kivy\core\window\window_sdl2.py", line 747, in mainloop
  self._mainloop()
File "C:\Users\gavrk\AppData\Local\Programs\Python\Python37-32\Lib\site-packages\kivy\core\window\window_sdl2.py", line 479, in _mainloop
  EventLoop.idle()
File "C:\Users\gavrk\AppData\Local\Programs\Python\Python37-32\Lib\site-packages\kivy\base.py", line 342, in idle
  self.dispatch_input()
File "C:\Users\gavrk\AppData\Local\Programs\Python\Python37-32\Lib\site-packages\kivy\base.py", line 327, in dispatch_input
  post_dispatch_input(*pop(0))
File "C:\Users\gavrk\AppData\Local\Programs\Python\Python37-32\Lib\site-packages\kivy\base.py", line 293, in post_dispatch_input
  wid.dispatch('on_touch_up', me)
File "C:\Users\gavrk\AppData\Local\Programs\Python\Python37-32\Lib\site-packages\kivy\_event.cp37-win32.pyd", line 707, in kivy._event.EventDispatcher.dispatch
File "C:\Users\gavrk\AppData\Local\Programs\Python\Python37-32\Lib\site-packages\kivy\uix\behaviors\button.py", line 179, in on_touch_up
  self.dispatch('on_release')
File "C:\Users\gavrk\AppData\Local\Programs\Python\Python37-32\Lib\site-packages\kivy\_event.cp37-win32.pyd", line 703, in kivy._event.EventDispatcher.dispatch
File "C:\Users\gavrk\AppData\Local\Programs\Python\Python37-32\Lib\site-packages\kivy\_event.cp37-win32.pyd", line 1214, in kivy._event.EventObservers.dispatch
File "C:\Users\gavrk\AppData\Local\Programs\Python\Python37-32\Lib\site-packages\kivy\_event.cp37-win32.pyd", line 1098, in kivy._event.EventObservers._dispatch
File "C:\Users\gavrk\AppData\Local\Programs\Python\Python37-32\Lib\site-packages\kivy\lang\builder.py", line 64, in custom_callback
  exec(__kvlang__.co_value, idmap)
File "C:\GUI Projects\gercort\gercort.kv", line 489, in <module>
  on_release: self.output_csv(self.filepath2)
File "C:\Users\gavrk\AppData\Local\Programs\Python\Python37-32\Lib\site-packages\kivy\weakproxy.cp37-win32.pyd", line 32, in kivy.weakproxy.WeakProxy.__getattr__

builtins.AttributeError: 'Button' object has no attribute 'output_csv'
</code>```

答:
```<code>on_release: self.output_csv(self.filepath2)
</code>```

self means that you are calling function from Button class, and there's no function called output_csv, so error tells you that. You defined that function in the SyllWindow class. If that button is also on that screen, just change it to

```<code>on_release: root.output_csv(root.filepath)
</code>```

Body:
I try to bind a function (in .py) to button (in kv.) after directory selection with Filechooser (all at one Screen) as follows:

.py:

class SyllWindow(Screen): #screen where all happens

    def select(self, *args):

        if args[1]:

            filepath = args[1][0]

            try: self.label.text = filepath

            except: pass

    def output_csv(corpus_root): #function

        corpus = PlaintextCorpusReader(corpus_root, '.*') #this must be irrelevant actually
        def reduce_dip(corpus_string):
            corpus_string = corpus_string.replace("Ei", "ö")
            corpus_string = corpus_string.replace("ei", "ö")
            # reduced
            corpus_string = corpus_string.replace("ie", "ö")
            return corpus_string
        vowels = [' ','a','e','i','o','u','ä','ö','ü','A','E','I','O','U','Ä','Ö','Ü']
        cfd_syll = nltk.ConditionalFreqDist(
            (textname, num_syll)
            for textname in corpus.fileids()
            for num_syll in [len(w) for w in ''.join(char for char in reduce_dip(corpus.raw(fileids=textname)) if char in vowels).split()])
        syll_dataframe = DataFrame(cfd_syll)
        return syll_dataframe.to_csv(path + '\silben.csv')

    pass

.kv (button block):

Button:

                            text: '.csv'
                            font_size: 14
                            on_release: self.output_csv(self.filepath)

Looks like this:

After pressing ".csv" I get an error AttributeError: 'Button' object has no attribute 'output_csv'
I'm aware of similar issues described here, here and here, but all examples there are in Python language, while my issue seems to be more about Kivy language.

I'd be grateful for any advice.

Full error traceback:

File "C:\Users\gavrk\AppData\Local\Programs\Python\Python37-32\Lib\runpy.py", line 193, in _run_module_as_main
  "__main__", mod_spec)
File "C:\Users\gavrk\AppData\Local\Programs\Python\Python37-32\Lib\runpy.py", line 85, in _run_code
  exec(code, run_globals)
File "C:\GUI Projects\gercort\main.py", line 147, in <module>
  Gercort().run()
File "C:\Users\gavrk\AppData\Local\Programs\Python\Python37-32\Lib\site-packages\kivy\app.py", line 855, in run
  runTouchApp()
File "C:\Users\gavrk\AppData\Local\Programs\Python\Python37-32\Lib\site-packages\kivy\base.py", line 504, in runTouchApp
  EventLoop.window.mainloop()
File "C:\Users\gavrk\AppData\Local\Programs\Python\Python37-32\Lib\site-packages\kivy\core\window\window_sdl2.py", line 747, in mainloop
  self._mainloop()
File "C:\Users\gavrk\AppData\Local\Programs\Python\Python37-32\Lib\site-packages\kivy\core\window\window_sdl2.py", line 479, in _mainloop
  EventLoop.idle()
File "C:\Users\gavrk\AppData\Local\Programs\Python\Python37-32\Lib\site-packages\kivy\base.py", line 342, in idle
  self.dispatch_input()
File "C:\Users\gavrk\AppData\Local\Programs\Python\Python37-32\Lib\site-packages\kivy\base.py", line 327, in dispatch_input
  post_dispatch_input(*pop(0))
File "C:\Users\gavrk\AppData\Local\Programs\Python\Python37-32\Lib\site-packages\kivy\base.py", line 293, in post_dispatch_input
  wid.dispatch('on_touch_up', me)
File "C:\Users\gavrk\AppData\Local\Programs\Python\Python37-32\Lib\site-packages\kivy\_event.cp37-win32.pyd", line 707, in kivy._event.EventDispatcher.dispatch
File "C:\Users\gavrk\AppData\Local\Programs\Python\Python37-32\Lib\site-packages\kivy\uix\behaviors\button.py", line 179, in on_touch_up
  self.dispatch('on_release')
File "C:\Users\gavrk\AppData\Local\Programs\Python\Python37-32\Lib\site-packages\kivy\_event.cp37-win32.pyd", line 703, in kivy._event.EventDispatcher.dispatch
File "C:\Users\gavrk\AppData\Local\Programs\Python\Python37-32\Lib\site-packages\kivy\_event.cp37-win32.pyd", line 1214, in kivy._event.EventObservers.dispatch
File "C:\Users\gavrk\AppData\Local\Programs\Python\Python37-32\Lib\site-packages\kivy\_event.cp37-win32.pyd", line 1098, in kivy._event.EventObservers._dispatch
File "C:\Users\gavrk\AppData\Local\Programs\Python\Python37-32\Lib\site-packages\kivy\lang\builder.py", line 64, in custom_callback
  exec(__kvlang__.co_value, idmap)
File "C:\GUI Projects\gercort\gercort.kv", line 489, in <module>
  on_release: self.output_csv(self.filepath2)
File "C:\Users\gavrk\AppData\Local\Programs\Python\Python37-32\Lib\site-packages\kivy\weakproxy.cp37-win32.pyd", line 32, in kivy.weakproxy.WeakProxy.__getattr__

builtins.AttributeError: 'Button' object has no attribute 'output_csv'

Body:
on_release: self.output_csv(self.filepath2)

self means that you are calling function from Button class, and there's no function called output_csv, so error tells you that. You defined that function in the SyllWindow class. If that button is also on that screen, just change it to

on_release: root.output_csv(root.filepath)


问:
python populating array using while loop
All I am trying to do is populate an array with numbers in order. So, array[0][0] = 0, array[0][1]=1, etc. Why is this not working?  I cannot figure it out.</p>

```<code>def populateArray(ar):
    count = 0
    i=0
    j=0
    while (i<len(ar)):
        while (j<len(ar[i])):
            ar[i][j] = count
            count = count + 1
            j=j+1
        j=0
        i=i+1
    return ar

numColumns = input('how many columns?')
numRows = input('how many rows?')
arr = [[0]*int(numColumns)]*int(numRows)
arr=populateArray(arr)
print(arr)
</code>```

答:
You can do this:

```<code>numColumns = input('how many columns?')
numRows = input('how many rows?')
arr = [[i+j for i in range(int(numRows))] for j in range(int(numColumns))]
arr=populateArray(arr)
print(arr)
</code>```

The problem with your code is that you append same array to the main array multiple times, like this [l, l, l] and l is a list.

So when ever you change an elemenet of l it will change all of ls in your list.

So, your code works fine but each time you change another list, all of previous list will be effected.

Body:
All I am trying to do is populate an array with numbers in order. So, array[0][0] = 0, array[0][1]=1, etc. Why is this not working?  I cannot figure it out.

def populateArray(ar):
    count = 0
    i=0
    j=0
    while (i<len(ar)):
        while (j<len(ar[i])):
            ar[i][j] = count
            count = count + 1
            j=j+1
        j=0
        i=i+1
    return ar

numColumns = input('how many columns?')
numRows = input('how many rows?')
arr = [[0]*int(numColumns)]*int(numRows)
arr=populateArray(arr)
print(arr)

Body:
You can do this:

numColumns = input('how many columns?')
numRows = input('how many rows?')
arr = [[i+j for i in range(int(numRows))] for j in range(int(numColumns))]
arr=populateArray(arr)
print(arr)

The problem with your code is that you append same array to the main array multiple times, like this [l, l, l] and l is a list.

So when ever you change an elemenet of l it will change all of ls in your list.

So, your code works fine but each time you change another list, all of previous list will be effected.


答:
when you initiate your arr variable, you are multiplying a list of lists with a number, this results in a "mess" because what you actually do it is to multiply only the reference of the first list (from your list of lists), so actually you have in your arr only one list and a bunch of reference to that list, to fix this you can do:

```<code>arr = [[0] * int(numColumns) for _ in range(int(numRows))]
</code>```

or:

```<code>arr = [[0 for _ in range(int(numColumns))] for _ in range(int(numRows))]
</code>```

after changing this in your code, for numRows = 3 and numColumns = 4 you get:

```<code>[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]
</code>```

Title: python populating array using while loop

Body:
when you initiate your arr variable, you are multiplying a list of lists with a number, this results in a "mess" because what you actually do it is to multiply only the reference of the first list (from your list of lists), so actually you have in your arr only one list and a bunch of reference to that list, to fix this you can do:

arr = [[0] * int(numColumns) for _ in range(int(numRows))]

or:

arr = [[0 for _ in range(int(numColumns))] for _ in range(int(numRows))]

after changing this in your code, for numRows = 3 and numColumns = 4 you get:

[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]


问:
How do I draw this box plot in pandas?
I currently have this dataframe like this:

| patient type                |   asir |    aspr |
|:----------------------------|-------:|--------:|
| definitive dyalisis patient | 2975.6 | 15808.1 |
| kidney transplant patient   |  362   |  4469.3 |
```

<p><strong>Here patient type is the index</strong></p>

<p>Right now, I'm trying to create a pandas box plot that has 4 box plots in total, 2 of which are the <code>asir</code> and <code>aspr</code> values for <code>definitive dialysis patient</code> and 2 more for <code>kidney transplant patient</code>.</p>

<p>Currently, I've tried to code it out with this following code:</p>

<pre class="lang-py prettyprint-override"><code>%matplotlib inline
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

# import the csv file
dataname = 'Datasets\\age-standardised-incidence-rate-and-prevalence-rate-for-definitive-dialysis-and-transplant.csv'
data = pd.read_csv(dataname)
df = pd.DataFrame(data)

# drop the year column away as we want together all the definitive dialysis patient data and the kidney transplant patient data together.abs
df2 = df.drop(['year'],axis=1)

# sum up all the data for the respective patien_type according to their respective asir and aspr
df3 = df2.groupby(df2['patient_type']).sum()
df4 = df3.rename(columns = {'patient_type':'patient_type','asir':'asir','aspr':'aspr'})

# pivot the table so that we can use the patient_type to plot out the bar plot
# df4 = df4.pivot_table(columns=['patient_type'])

# plot out the box plot
bplot = df4.boxplot(by='patient_type',column=['asir','aspr'],grid=True,figsize=(40,20),patch_artist=True,fontsize=20)
plt.title('Boxplot Of Age Standardised incidence rate and prevalence rate for definitive dialysis and transplant patients.',fontsize=20)
# plt.legend(df4['patient_type'],fontsize=20)
plt.show()
df4
</code>```

But it ended up looking like this:

答:
So I'm assuming that you want 4 box plots with each type: asir, aspr, definitive dyalisis patient and kidney transplant patient.

Let's say your initial dataframe looks like this:

df = pd.DataFrame({'asir': [2975.6, 362.0], 'aspr':[15808.1, 4469.3],
    'patient type': ['definitive dyalisis patient',
            'kidney transplant patient']})
```

<pre class="lang-py prettyprint-override"><code>| patient type                |   asir |    aspr |
|:----------------------------|-------:|--------:|
| definitive dyalisis patient | 2975.6 | 15808.1 |
| kidney transplant patient   |  362   |  4469.3 |
</code>```

Draw the first plot where we show asir and the aspr counts:

df = df.set_index('patient type')
df.boxplot(grid=True,figsize=(40,20),patch_artist=True,fontsize=20)
```

<p>This shows,
<img src="https://i.stack.imgur.com/ZWIsn.png" alt="enter image description here"></p>

<p>Now transpose your data frame to plot the <code>definitive dyalisis patient</code> and <code>kidney transplant process</code>.</p>

<pre class="lang-py prettyprint-override"><code>t_df = df.T
</code>```

The data frame looks like this now:

|      |   definitive dyalisis patient |   kidney transplant patient |
|:-----|------------------------------:|----------------------------:|
| asir |                        2975.6 |                       362   |
| aspr |                       15808.1 |                      4469.3 |
```

<p>Now plot this just like before:</p>

<pre class="lang-py prettyprint-override"><code>t_df.boxplot(grid=True,figsize=(40,20),patch_artist=True,fontsize=20)
</code>```

The plot looks like this:

Title: How do I draw this box plot in pandas?

Body:
I currently have this dataframe like this:

| patient type                |   asir |    aspr |
|:----------------------------|-------:|--------:|
| definitive dyalisis patient | 2975.6 | 15808.1 |
| kidney transplant patient   |  362   |  4469.3 |

Here patient type is the index

Right now, I'm trying to create a pandas box plot that has 4 box plots in total, 2 of which are the asir and aspr values for definitive dialysis patient and 2 more for kidney transplant patient.

Currently, I've tried to code it out with this following code:

%matplotlib inline
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

# import the csv file
dataname = 'Datasets\\age-standardised-incidence-rate-and-prevalence-rate-for-definitive-dialysis-and-transplant.csv'
data = pd.read_csv(dataname)
df = pd.DataFrame(data)

# drop the year column away as we want together all the definitive dialysis patient data and the kidney transplant patient data together.abs
df2 = df.drop(['year'],axis=1)

# sum up all the data for the respective patien_type according to their respective asir and aspr
df3 = df2.groupby(df2['patient_type']).sum()
df4 = df3.rename(columns = {'patient_type':'patient_type','asir':'asir','aspr':'aspr'})

# pivot the table so that we can use the patient_type to plot out the bar plot
# df4 = df4.pivot_table(columns=['patient_type'])

# plot out the box plot
bplot = df4.boxplot(by='patient_type',column=['asir','aspr'],grid=True,figsize=(40,20),patch_artist=True,fontsize=20)
plt.title('Boxplot Of Age Standardised incidence rate and prevalence rate for definitive dialysis and transplant patients.',fontsize=20)
# plt.legend(df4['patient_type'],fontsize=20)
plt.show()
df4

But it ended up looking like this:

Body:
So I'm assuming that you want 4 box plots with each type: asir, aspr, definitive dyalisis patient and kidney transplant patient.

Let's say your initial dataframe looks like this:

df = pd.DataFrame({'asir': [2975.6, 362.0], 'aspr':[15808.1, 4469.3],
    'patient type': ['definitive dyalisis patient',
            'kidney transplant patient']})

| patient type                |   asir |    aspr |
|:----------------------------|-------:|--------:|
| definitive dyalisis patient | 2975.6 | 15808.1 |
| kidney transplant patient   |  362   |  4469.3 |

Draw the first plot where we show asir and the aspr counts:

df = df.set_index('patient type')
df.boxplot(grid=True,figsize=(40,20),patch_artist=True,fontsize=20)

This shows,

Now transpose your data frame to plot the definitive dyalisis patient and kidney transplant process.

t_df = df.T

The data frame looks like this now:

|      |   definitive dyalisis patient |   kidney transplant patient |
|:-----|------------------------------:|----------------------------:|
| asir |                        2975.6 |                       362   |
| aspr |                       15808.1 |                      4469.3 |

Now plot this just like before:

t_df.boxplot(grid=True,figsize=(40,20),patch_artist=True,fontsize=20)

The plot looks like this:


问:
SQL database: use one table with 3,5M entries or many tables with less entries?
I'm building a football game that allows people to create leagues online.

Say I have 1000 league after some time. I store my data in SQL. Should I:

1) Create 1 single database with the table "rosters" and insert all the players of all the leagues into it (which would approximate 3,5 to 4 million entries for 1000 leagues)

2) Create 1 single database with 20 tables "rosters1, rosters2, etc" and split the leagues rosters between those 20 tables

3) Create 1 database for each league with a table "rosters" in each

4) Create 20 databases with one table "rosters" in each and split the leagues rosters between the 20 databases.

What is the best option for performance and quick SQL queries?

答:
I think you want option 1 in principle. You have to consider use cases like moving someone from one roster to another: you don't want that to occur across databases. And I imagine many queries that you want to run against all rosters. You may find it helpful to research partitioning, even though MySQL does not offer it. (Postgresql does.)

You also need to look at normalization. Example: I assume you have a teams table, and PlayerTeam is just a Foreign Key into it (you should index this column in both tables BTW). If this doesn't make sense to you, spend a little time on a database design book or web site.


问:
Creating HTML Lists Purely in CSS
Trying to make it easy for a disabled friend to enter content into the site that I created for him without excessive typing, is there some way in CSS to create bulleted and ordered lists using existing line breaks or tabs rather than putting in list elements? These examples are for unordered but ordered is also needed.

For example, this:

```<code><div class="Unordered"><br />
    List item 1<br />
    List item 2<br />
    List item 3<br />
</div>
</code>```

. . . with the br coming from nl2br() and CSS something like this?

```<code>.Unordered {
    margin: auto;
    display: flex;
    flex-direction: row;
    width: 100%;
    text-align: center;
}

.Unordered br {
    list-style-type: disc;
}
</code>```

I'm trying to produce a list with the visual appearance created by a regular list like this:

```<code><ul>
    <li>List item 1</li>
    <li>List item 2</li>
    <li>List item 3</li>
</ul>
</code>```

I am not adverse to doing this using PHP either.

答:
use "before" for span tag to make bullet!

.Unordered {
    margin: auto;
    float:left;
    flex-direction: row;
    width: 100%;
    text-align: center;
}

.Unordered br {
    list-style-type: disc;
}

span:before {
  content: ' \25CF';
  font-size: 20px;
}

span{
    display:block;
    width:100%;
    text-align:left;
    float:left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="Unordered">
<span>List item 1</span>
<span>List item 2</span>
<span>List item 3</span>
</div></code>```

Title: Creating HTML Lists Purely in CSS

Body:
Trying to make it easy for a disabled friend to enter content into the site that I created for him without excessive typing, is there some way in CSS to create bulleted and ordered lists using existing line breaks or tabs rather than putting in list elements? These examples are for unordered but ordered is also needed.

For example, this:

    List item 1

    List item 2

    List item 3

. . . with the br coming from nl2br() and CSS something like this?

.Unordered {
    margin: auto;
    display: flex;
    flex-direction: row;
    width: 100%;
    text-align: center;
}

.Unordered br {
    list-style-type: disc;
}

I'm trying to produce a list with the visual appearance created by a regular list like this:

List item 1

List item 2

List item 3

I am not adverse to doing this using PHP either.

Body:
use "before" for span tag to make bullet!

.Unordered {
    margin: auto;
    float:left;
    flex-direction: row;
    width: 100%;
    text-align: center;
}

.Unordered br {
    list-style-type: disc;
}

span:before {
  content: ' \25CF';
  font-size: 20px;
}

span{
    display:block;
    width:100%;
    text-align:left;
    float:left;
}

<div class="Unordered">
<span>List item 1</span>
<span>List item 2</span>
<span>List item 3</span>
</div>


问:
make the first tab the active tab when open a bootstrap modal
i have a button that will show a bootstrap modal when clicks on it
the modal contains sidebar tabs.

my problem is when i close the modal and open it again by clicking on the button it will open with the last activated tab
i want the activated tab to be the first tab once i close the modal and open the modal again without reloading the page.

my html

```<code> // the button that will open the bootstrap modal
            <div>
            <a href="#"  class="popupLink" data-toggle="modal" data-target="#yDetailsModal">
            </a>
            </div>

// bootstrap modal

<div class="modal" id="MyDetailsModal" tabindex="-1" role="dialog" arialabelledby="myDetailsModal" aria-hidden="true" >

 <div class="modal-dialog modal-details" role="document">

  <div class="modal-content modal-details">

   <div class="modal-header">

 <button type="button" class="close close-button"  data-dismiss="modal" aria-label="Close" id="btnId"> </button>

  </div>

 <div class="modal-body">
  <div class=" tabs-left" id= "modal-tabs">
   <ul class="nav nav-tabs">

   <li class="active">
   <a href="#personal"  data-toggle="tab"></a></li>

  <li>
   <a  href="#promotion" data-toggle="tab"> </a> </li>
    <li>
    <a  href="#vacation" data-toggle="tab"> </a> </li>

</ul>
 </div>

<div class="tab-content" id="tab-content">
 <div class="tab-pane active" id="personalInformation">
  <div>
   <ul>
     <li>

      <span> this is a personal information</span>
      </li>
</ul>
</div>
</div>

</code>```

答:
Can you add below mentioned jQuery Hope this help you.</p>

```<code>$(".popupLink").click(function(){
    jQuery('.nav-tabs li').removeClass('active');
    jQuery('.nav-tabs li:first-child').addClass('active');
});
</code>```

Body:
i have a button that will show a bootstrap modal when clicks on it
the modal contains sidebar tabs.

my problem is when i close the modal and open it again by clicking on the button it will open with the last activated tab
i want the activated tab to be the first tab once i close the modal and open the modal again without reloading the page.

my html

 // the button that will open the bootstrap modal

// bootstrap modal

 <button type="button" class="close close-button"  data-dismiss="modal" aria-label="Close" id="btnId"> </button>

       this is a personal information

Body:
Can you add below mentioned jQuery Hope this help you.

$(".popupLink").click(function(){
    jQuery('.nav-tabs li').removeClass('active');
    jQuery('.nav-tabs li:first-child').addClass('active');
});


问:
Can't style Fancybox modal
I'm having problems styling a modal I've set to open with fancy box. The content for the modal/div shows up after clicking with no issues but it seems all the styling I applied to that modal div refuses to show up.

.hidden{
display:none;
}

.red{
background: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>modal</title>

   <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.css">
</head>

<body>
  <div>
     Open modal  box
  </div>

  <div class="hidden">
     <div class="red" id="open">
          <h2>Hello</h2>
          <p>You are awesome.</p>
       </div>
   </div>

</body>
   <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
    <script src="https://cdn.jsdelivr.net/gh/fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.js"></script>
</html></code>```

Here is my setup on Codepen

答:
Fancybox adds fancybox-content classname to the content to add some necessary CSS properties and some default styling, for example, white background color, padding.

Therefore you simply override these rules, example:

```<code>.fancybox-content.red {
  background: red;
  padding: 10px 20px;
}
</code>```

Title: Can't style Fancybox modal

Body:
I'm having problems styling a modal I've set to open with fancy box. The content for the modal/div shows up after clicking with no issues but it seems all the styling I applied to that modal div refuses to show up.

.hidden{
display:none;
}

.red{
background: red;
}

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>modal</title>

   <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.css">

     Open modal  box

Hello

You are awesome.

Here is my setup on Codepen

Body:
Fancybox adds fancybox-content classname to the content to add some necessary CSS properties and some default styling, for example, white background color, padding.

Therefore you simply override these rules, example:

.fancybox-content.red {
  background: red;
  padding: 10px 20px;
}


问:
Issue with functions in program for C
I am having a major issue with my functions for my program. I know it has to do with how I made my functions, but am not sure where the problem is. Please keep in mind that this is for an assignment for school and obviously I am lacking some understanding.

```<code>#include <stdio.h>

/* Define structure */

struct date
{
    int day, month, year;
};

/* Function prototype */

int calc_date_number(struct date);

/* Begin Main */

 int main()
{
    /* Declare variable */

    struct date a;

    int valid=0, c;

    char *days[7] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

    /* Issue greeting */

    printf("Welcome to the Date to Day-of-Week program. \n\n");
    printf("The program will give the day of the week for any date from 1/1/1900\n\n");

    /*Prompt user for date */

    do
    {
        printf("Enter date (mm/dd/yyyy): ");
        scanf("%i/%i/%i", &a.month, &a.day, &a.year);

        /* Validate inputted date and re-prompt user for valid date */

        if(a.year>=1900 && a.year<=9999)
        {
            if(a.month>=1 && a.month<=12)
            {
                if((a.day>=1 && a.day<=31) && (a.month==1 || a.month==3 || a.month==5 || a.month==7 || a.month==8 || a.month==10 || a.month==12))
                valid = 1;
                else if((a.day>=1 && a.day<=30) && (a.month==4 || a.month==6 || a.month==9 || a.month==11))
                valid = 1;
                else if((a.day>=1 && a.day<=28) && (a.month==2))
                valid = 1;
                else if(a.day==29 && a.month==2 && (a.year%400==0 ||(a.year%4==0 && a.year%100!=0)))
                valid = 1;
                else
                printf("Invalid day. Please re-enter date.\n");
            }
            else
            {
                printf("Invalid month. Please re-enter date.\n");
            }
         }
        else
        {
            printf("Invalid year. Please re-enter date. Year must be greater than 1900.\n");
        }
    }while(valid=0);

    /* Call function to calculate the number to represent the date */

    c = calc_date_number(a);

    /* Output date and day of the week */

    printf("%.2i/%.2i/%.2i falls on a %s\n\n", a.month, a.day, a.year, days[c]);
    printf("Thank you for using the Date to Day-of-Week program.");

    return 0;
}/* end of main */

/* Begin function calc_date_number */

  int calc_date_number(struct date d)
{
    int f, g, n;
    long long n1, n2;

    /* Establish the calculation for N1 1/1/1900 */

    n1 = (1461 * 1899) / 4 + (153 * 15) / 5 + 1;

    /* Establish the calculation for f and g for N2 calculation */

    if (d.month <= 2)
    {
        f = d.year- 1;
    }
    else
    {
        f = d.year;
    }

    if(d.month <= 2)
    {
        g = d.month + 13;
    }
    else
    {
        g = d.month + 1;
    }

    /* Calculate N2 for inputted date */

    n2 = (1461 * f) / 4 + (153 * g) / 5 + d.day;

    /* Calculate numeric day of the week */

    n =(n2 - 621049) % 7;

    return n;

} /* end of function */
</code>```

My Output is
Welcome to the Date to Day-of-Week program.

The program will give the day of the week for any date from 1/1/1900

Enter date (mm/dd/yyyy): 09/24/1994
Invalid year. Please re-enter date. Year must be greater than 1900.
00/1961062381/6356776 falls on a Monday

Thank you for using the Date to Day-of-Week program.

答:
There are some issues like

Functions not returning anything

Using void as return value for the  main function (possible, but not
advised)

Calling the main function  (it possible, but not advised)

In printf("%.2i/%.2i/%.2i falls on a %s\n\n",a.month, a.day, a.day,
days[c]); you write a.day instead  of a.year as 4th argument.

This one seems to work, although I did not validate your calculation of the dates.

```<code>#include <stdio.h>

/* Define structure */

struct date
{
    int day, month, year;
};

/* Function prototype */

int calc_date_number(struct date);

int calc_day_number(long long);

/* Begin Main */
int main()
{
    /* Declare variable */
    struct date a;
    long long c;
    int valid=0;

    char *days[7] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

    /* Issue greeting */
    printf("Welcome to the Date to Day-of-Week program. \n\n");
    printf("The program will give the day of the week for any date from 1/1/1900\n\n");

    /*Prompt user for date */
    do
    {
        printf("Enter date (mm/dd/yyyy): ");
        scanf("%i/%i/%i", &a.month, &a.day, &a.year);

        /* Validate inputted date and re-prompt user for valid date */

        if(a.year>=1900 && a.year<=9999)
            if(a.month>=1 && a.month<=12)
                if((a.day>=1 && a.day<=31) && (a.month==1 || a.month==3 || a.month==5 || a.month==7 || a.month==8 || a.month==10 || a.month==12))
                    valid = 1;
                else if((a.day>=1 && a.day<=30) && (a.month==4 || a.month==6 || a.month==9 || a.month==11))
                    valid = 1;
                else if((a.day>=1 && a.day<=28) && (a.month==2))
                    valid = 1;
                else if(a.day==29 && a.month==2 && (a.year%400==0 ||(a.year%4==0 && a.year%100!=0)))
                    valid = 1;
                else
                    printf("Invalid day. Please re-enter date.\n");
            else
                printf("Invalid month. Please re-enter date.\n");
        else
            printf("Invalid year. Please re-enter date. Year must be greater than 1900.\n");
    } while(valid=0);

    /* Call function to calculate the number to represent the date */
    c = calc_date_number(a);

    /* Output date and day of the week */
    printf("%.2i/%.2i/%.2i falls on a %s\n\n", a.month, a.day, a.year, days[c]);
    printf("Thank you for using the Date to Day-of-Week program.");

    return 0;
}/* end of main */

/* Begin function calc_date_number */

int calc_date_number(struct date d)
{
    int f, g;
    long long n1, n2;

    /* Establish the calculation for N1 1/1/1900 */
    n1 = (1461 * 1899) / 4 + (153 * 15) / 5 + 1;

    /* Establish the calculation for f and g for N2 calculation */
    if (d.month <= 2)
        f = d.year- 1;
    else
        f = d.year;

    if(d.month <= 2)
        g = d.month + 13;
    else
        g = d.month + 1;

    /* Calculate N2 for inputted date */
    n2 = (1461 * f) / 4 + (153 * g) / 5 + d.day;

    /* Call function to calculate the day number */
    return calc_day_number(n2); // you could just do return (n2 - 621049) % 7 and get rid of calc_day_number function

} /* end of function */

/* Begin function calc_day_number */
/* Calculate numeric day of the week */
int calc_day_number(long long n2)
{
    return (n2 - 621049) % 7;
} /* end of function */
</code>```

Title: Issue with functions in program for C

Body:
I am having a major issue with my functions for my program. I know it has to do with how I made my functions, but am not sure where the problem is. Please keep in mind that this is for an assignment for school and obviously I am lacking some understanding.

#include <stdio.h>

/* Define structure */

struct date
{
    int day, month, year;
};

/* Function prototype */

int calc_date_number(struct date);

/* Begin Main */

 int main()
{
    /* Declare variable */

    struct date a;

    int valid=0, c;

    char *days[7] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

    /* Issue greeting */

    printf("Welcome to the Date to Day-of-Week program. \n\n");
    printf("The program will give the day of the week for any date from 1/1/1900\n\n");

    /*Prompt user for date */

    do
    {
        printf("Enter date (mm/dd/yyyy): ");
        scanf("%i/%i/%i", &a.month, &a.day, &a.year);

        /* Validate inputted date and re-prompt user for valid date */

        if(a.year>=1900 && a.year<=9999)
        {
            if(a.month>=1 && a.month<=12)
            {
                if((a.day>=1 && a.day<=31) && (a.month==1 || a.month==3 || a.month==5 || a.month==7 || a.month==8 || a.month==10 || a.month==12))
                valid = 1;
                else if((a.day>=1 && a.day<=30) && (a.month==4 || a.month==6 || a.month==9 || a.month==11))
                valid = 1;
                else if((a.day>=1 && a.day<=28) && (a.month==2))
                valid = 1;
                else if(a.day==29 && a.month==2 && (a.year%400==0 ||(a.year%4==0 && a.year%100!=0)))
                valid = 1;
                else
                printf("Invalid day. Please re-enter date.\n");
            }
            else
            {
                printf("Invalid month. Please re-enter date.\n");
            }
         }
        else
        {
            printf("Invalid year. Please re-enter date. Year must be greater than 1900.\n");
        }
    }while(valid=0);

    /* Call function to calculate the number to represent the date */

    c = calc_date_number(a);

    /* Output date and day of the week */

    printf("%.2i/%.2i/%.2i falls on a %s\n\n", a.month, a.day, a.year, days[c]);
    printf("Thank you for using the Date to Day-of-Week program.");

    return 0;
}/* end of main */

/* Begin function calc_date_number */

  int calc_date_number(struct date d)
{
    int f, g, n;
    long long n1, n2;

    /* Establish the calculation for N1 1/1/1900 */

    n1 = (1461 * 1899) / 4 + (153 * 15) / 5 + 1;

    /* Establish the calculation for f and g for N2 calculation */

    if (d.month <= 2)
    {
        f = d.year- 1;
    }
    else
    {
        f = d.year;
    }

    if(d.month <= 2)
    {
        g = d.month + 13;
    }
    else
    {
        g = d.month + 1;
    }

    /* Calculate N2 for inputted date */

    n2 = (1461 * f) / 4 + (153 * g) / 5 + d.day;

    /* Calculate numeric day of the week */

    n =(n2 - 621049) % 7;

    return n;

} /* end of function */

My Output is
Welcome to the Date to Day-of-Week program.

The program will give the day of the week for any date from 1/1/1900

Enter date (mm/dd/yyyy): 09/24/1994
Invalid year. Please re-enter date. Year must be greater than 1900.
00/1961062381/6356776 falls on a Monday

Thank you for using the Date to Day-of-Week program.

Body:
There are some issues like

Functions not returning anything

Using void as return value for the  main function (possible, but not
advised)

Calling the main function  (it possible, but not advised)

In printf("%.2i/%.2i/%.2i falls on a %s\n\n",a.month, a.day, a.day,
days[c]); you write a.day instead  of a.year as 4th argument.

This one seems to work, although I did not validate your calculation of the dates.

#include <stdio.h>

/* Define structure */

struct date
{
    int day, month, year;
};

/* Function prototype */

int calc_date_number(struct date);

int calc_day_number(long long);

/* Begin Main */
int main()
{
    /* Declare variable */
    struct date a;
    long long c;
    int valid=0;

    char *days[7] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

    /* Issue greeting */
    printf("Welcome to the Date to Day-of-Week program. \n\n");
    printf("The program will give the day of the week for any date from 1/1/1900\n\n");

    /*Prompt user for date */
    do
    {
        printf("Enter date (mm/dd/yyyy): ");
        scanf("%i/%i/%i", &a.month, &a.day, &a.year);

        /* Validate inputted date and re-prompt user for valid date */

        if(a.year>=1900 && a.year<=9999)
            if(a.month>=1 && a.month<=12)
                if((a.day>=1 && a.day<=31) && (a.month==1 || a.month==3 || a.month==5 || a.month==7 || a.month==8 || a.month==10 || a.month==12))
                    valid = 1;
                else if((a.day>=1 && a.day<=30) && (a.month==4 || a.month==6 || a.month==9 || a.month==11))
                    valid = 1;
                else if((a.day>=1 && a.day<=28) && (a.month==2))
                    valid = 1;
                else if(a.day==29 && a.month==2 && (a.year%400==0 ||(a.year%4==0 && a.year%100!=0)))
                    valid = 1;
                else
                    printf("Invalid day. Please re-enter date.\n");
            else
                printf("Invalid month. Please re-enter date.\n");
        else
            printf("Invalid year. Please re-enter date. Year must be greater than 1900.\n");
    } while(valid=0);

    /* Call function to calculate the number to represent the date */
    c = calc_date_number(a);

    /* Output date and day of the week */
    printf("%.2i/%.2i/%.2i falls on a %s\n\n", a.month, a.day, a.year, days[c]);
    printf("Thank you for using the Date to Day-of-Week program.");

    return 0;
}/* end of main */

/* Begin function calc_date_number */

int calc_date_number(struct date d)
{
    int f, g;
    long long n1, n2;

    /* Establish the calculation for N1 1/1/1900 */
    n1 = (1461 * 1899) / 4 + (153 * 15) / 5 + 1;

    /* Establish the calculation for f and g for N2 calculation */
    if (d.month <= 2)
        f = d.year- 1;
    else
        f = d.year;

    if(d.month <= 2)
        g = d.month + 13;
    else
        g = d.month + 1;

    /* Calculate N2 for inputted date */
    n2 = (1461 * f) / 4 + (153 * g) / 5 + d.day;

    /* Call function to calculate the day number */
    return calc_day_number(n2); // you could just do return (n2 - 621049) % 7 and get rid of calc_day_number function

} /* end of function */

/* Begin function calc_day_number */
/* Calculate numeric day of the week */
int calc_day_number(long long n2)
{
    return (n2 - 621049) % 7;
} /* end of function */


问:
Filter an array of repeated objects and get the sum of them
So I have the next information, what I want to achieve is filter the array of objects and sum the qty of the objects repeated

```<code>//Original Data
var data = {
    sublists = [
    { item: 1, qty: 2},
    { item: 2, qty: 2},
    { item: 3, qty: 2},
    { item: 1, qty: 5}
    { item: 3, qty: 3}
    ],
    ...
};
//This is what I want to achieve
var result = {
    sublists = [
    { item: 1, qty: 7},
    { item: 2, qty: 2},
    { item: 3, qty: 5}

    ],
    ...
};
</code>```

So far what I got is the items name that repeat and an object that has the data of this variables

```<code>var repeatedObjects = {
  1: [{ item: 1, qty: 2}, { item: 1, qty: 5}],
  3: [{ item: 3, qty: 2}, { item: 3, qty: 3}]
}
var repeatedItems = [1, 3];
</code>```

But Im stuck at reducing the object so I can get the original data, with just one of the repeated objects and the sum of all of them. Any ideas?

答:
It could be done using Map & reduce :)

const dataSample = {
    sublists: [
      { item: 1, qty: 2},
      { item: 2, qty: 2},
      { item: 3, qty: 2},
      { item: 1, qty: 5},
      { item: 3, qty: 3}
    ],
};

const mergeItems = list => {
  return [...list.reduce((acc, val) => {
    const oldVal = acc.get(val.item) || { qty: 0 }
    const newVal = {
      ...val,
      qty: oldVal.qty + val.qty
    }
    acc.set(val.item, newVal)
    return acc
  }, new Map()).values()]
}

console.log(mergeItems(dataSample.sublists))```

Body:
So I have the next information, what I want to achieve is filter the array of objects and sum the qty of the objects repeated

//Original Data
var data = {
    sublists = [
    { item: 1, qty: 2},
    { item: 2, qty: 2},
    { item: 3, qty: 2},
    { item: 1, qty: 5}
    { item: 3, qty: 3}
    ],
    ...
};
//This is what I want to achieve
var result = {
    sublists = [
    { item: 1, qty: 7},
    { item: 2, qty: 2},
    { item: 3, qty: 5}

    ],
    ...
};

So far what I got is the items name that repeat and an object that has the data of this variables

var repeatedObjects = {
  1: [{ item: 1, qty: 2}, { item: 1, qty: 5}],
  3: [{ item: 3, qty: 2}, { item: 3, qty: 3}]
}
var repeatedItems = [1, 3];

But Im stuck at reducing the object so I can get the original data, with just one of the repeated objects and the sum of all of them. Any ideas?


问:
Create a key map for all paths in a recursive/nested object array
I have an n levels deep nested array of tag objects with title and ID. What I'm trying to create is a an object with IDs as keys and values being an array describing the title-path to that ID.

I'm no master at recursion so my attempt below doesn't exactly provide the result I need.

Here's the original nested tag array:

```<code>const tags = [
  {
    title: 'Wood',
    id: 'dkgkeixn',
    tags: [
      {
        title: 'Material',
        id: 'ewyherer'
      },
      {
        title: 'Construction',
        id: 'cchtfyjf'
      }
    ]
  },
  {
    title: 'Steel',
    id: 'drftgycs',
    tags: [
      {
        title: 'Surface',
        id: 'sfkstewc',
        tags: [
          {
            title: 'Polished',
            id: 'vbraurff'
          },
          {
            title: 'Coated',
            id: 'sdusfgsf'
          }
        ]
      },
      {
        title: 'Quality',
        id: 'zsasyewe'
      }
    ]
  }
]
</code>```

The output I'm trying to get is this:

```<code>{
  'dkgkeixn': ['Wood'],
  'ewyherer': ['Wood', 'Material'],
  'cchtfyjf': ['Wood', 'Construction'],
  'drftgycs': ['Steel'],
  'sfkstewc': ['Steel', 'Surface'],
  'vbraurff': ['Steel', 'Surface', 'Polished'],
  'sdusfgsf': ['Steel', 'Surface', 'Coated'],
  'zsasyewe': ['Steel', 'Quality']
}
</code>```

So I'm building this recursive function which is almost doing it's job, but I keep getting the wrong paths in my flat/key map:

```<code>function flatMap(tag, acc, pathBefore) {
  if (!acc[tag.id]) acc[tag.id] = [...pathBefore];
  acc[tag.id].push(tag.title);

  if (tag.tags) {
    pathBefore.push(tag.title)
    tag.tags.forEach(el => flatMap(el, acc, pathBefore))
  }
  return acc
}

const keyMap = flatMap({ title: 'Root', id: 'root', tags}, {}, []);
console.log("keyMap", keyMap)
</code>```

I'm trying to get the path until a tag with no tags and then set that path as value for the ID and then push the items 'own' title. But somehow the paths get messed up.

答:
Check this, makePaths arguments are tags, result object and prefixed titles.

const makePaths = (tags, res = {}, prefix = []) => {
  tags.forEach(tag => {
    const values = [...prefix, tag.title];
    Object.assign(res, { [tag.id]: values });
    if (tag.tags) {
      makePaths(tag.tags, res, values);
    }
  });
  return res;
};

const tags = [
  {
    title: "Wood",
    id: "dkgkeixn",
    tags: [
      {
        title: "Material",
        id: "ewyherer"
      },
      {
        title: "Construction",
        id: "cchtfyjf"
      }
    ]
  },
  {
    title: "Steel",
    id: "drftgycs",
    tags: [
      {
        title: "Surface",
        id: "sfkstewc",
        tags: [
          {
            title: "Polished",
            id: "vbraurff"
          },
          {
            title: "Coated",
            id: "sdusfgsf"
          }
        ]
      },
      {
        title: "Quality",
        id: "zsasyewe"
      }
    ]
  }
];

console.log(makePaths(tags));```

Body:
I have an n levels deep nested array of tag objects with title and ID. What I'm trying to create is a an object with IDs as keys and values being an array describing the title-path to that ID.

I'm no master at recursion so my attempt below doesn't exactly provide the result I need.

Here's the original nested tag array:

const tags = [
  {
    title: 'Wood',
    id: 'dkgkeixn',
    tags: [
      {
        title: 'Material',
        id: 'ewyherer'
      },
      {
        title: 'Construction',
        id: 'cchtfyjf'
      }
    ]
  },
  {
    title: 'Steel',
    id: 'drftgycs',
    tags: [
      {
        title: 'Surface',
        id: 'sfkstewc',
        tags: [
          {
            title: 'Polished',
            id: 'vbraurff'
          },
          {
            title: 'Coated',
            id: 'sdusfgsf'
          }
        ]
      },
      {
        title: 'Quality',
        id: 'zsasyewe'
      }
    ]
  }
]

The output I'm trying to get is this:

{
  'dkgkeixn': ['Wood'],
  'ewyherer': ['Wood', 'Material'],
  'cchtfyjf': ['Wood', 'Construction'],
  'drftgycs': ['Steel'],
  'sfkstewc': ['Steel', 'Surface'],
  'vbraurff': ['Steel', 'Surface', 'Polished'],
  'sdusfgsf': ['Steel', 'Surface', 'Coated'],
  'zsasyewe': ['Steel', 'Quality']
}

So I'm building this recursive function which is almost doing it's job, but I keep getting the wrong paths in my flat/key map:

function flatMap(tag, acc, pathBefore) {
  if (!acc[tag.id]) acc[tag.id] = [...pathBefore];
  acc[tag.id].push(tag.title);

  if (tag.tags) {
    pathBefore.push(tag.title)
    tag.tags.forEach(el => flatMap(el, acc, pathBefore))
  }
  return acc
}

const keyMap = flatMap({ title: 'Root', id: 'root', tags}, {}, []);
console.log("keyMap", keyMap)

I'm trying to get the path until a tag with no tags and then set that path as value for the ID and then push the items 'own' title. But somehow the paths get messed up.


问:
Value Cannot be Null; Parameter Name 'Source'
```<code> @if ( Model.Select(p=>p.Payments.Any(o=>o.Expires>DateTime.Now))!= null)
 {

 <table class="table">
     <tr>
         <th>
             @Html.DisplayName("Student ID")
         </th>

         <th>
             @Html.DisplayName("Full Name")
         </th>

         <th>
             @Html.DisplayName("Expiry Date")
         </th>

         <th>
             @Html.DisplayName("Contact Number")
         </th>
         <th></th>

         @foreach (var item in Model.Where(p => p.Payments.Any(o => o.Expires > DateTime.Now)))
         {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.StudentID)
</code>```

This is in MVC project this is the home page I want to show the student who have expired on the current day. I have used the If statement and i am confused why i'm getting that exception.

答:
I have tested the code and if the model is null you will indeed get the null exception.

The issue here is with the logic flow as you - first making your selection and then checking for nullability.

In the if block - check for null first and then select the results:

```<code>if (Model != null && Model.Select(p => p.Payments.Any(o => o.Expires > DateTime.Now)).Any())
</code>```

Body:
 @if ( Model.Select(p=>p.Payments.Any(o=>o.Expires>DateTime.Now))!= null)
 {

             @Html.DisplayName("Student ID")

             @Html.DisplayName("Full Name")

             @Html.DisplayName("Expiry Date")

             @Html.DisplayName("Contact Number")

         @foreach (var item in Model.Where(p => p.Payments.Any(o => o.Expires > DateTime.Now)))
         {

                @Html.DisplayFor(modelItem => item.StudentID)

This is in MVC project this is the home page I want to show the student who have expired on the current day. I have used the If statement and i am confused why i'm getting that exception.

Body:
I have tested the code and if the model is null you will indeed get the null exception.

The issue here is with the logic flow as you - first making your selection and then checking for nullability.

In the if block - check for null first and then select the results:

if (Model != null && Model.Select(p => p.Payments.Any(o => o.Expires > DateTime.Now)).Any())


问:
Using GitLab token to clone without authentication
I want to clone GitLab repository without prompt for my automation script, by using my private token from my GitLab account.

Can someone provide me a sample?

I know I can do so with user and password:

```<code>git clone https://" + user + ":" + password + "@" + gitlaburl;
</code>```

and I know it is possible with ssh key

But, both options are insufficient.

答:
Customising the URL is not needed. Just use a git configuration for gitlab tokens such as

```<code>git config --global gitlab.accesstoken {TOKEN_VALUE}
</code>```

extended description here

Body:
I want to clone GitLab repository without prompt for my automation script, by using my private token from my GitLab account.

Can someone provide me a sample?

I know I can do so with user and password:

git clone https://" + user + ":" + password + "@" + gitlaburl;

and I know it is possible with ssh key

But, both options are insufficient.

Body:
Customising the URL is not needed. Just use a git configuration for gitlab tokens such as

git config --global gitlab.accesstoken {TOKEN_VALUE}

extended description here


问:
I can't get members from a 16k member server, what am I doing wrong?
I'm trying to get certain user objects from a discord server using their IDs, but it can't get the guild object for some reason. My code:

```<code>@botclient.event
async def on_ready():
    for x in all_ids:
        guild = botclient.get_guild(GUILD)
        user=guild.get_member(x)
        all_urls[x]=user.avatar_url

botclient.run(TOKEN)
</code>```

[TOKEN and GUILD are specified further above, I've checked multiple times and there seems to be nothing wrong with them]

It's worked in a smaller server before and I've tried several variations of this, but each gave me an AttributeError:

```<code>    user=guild.get_member(x)
AttributeError: 'NoneType' object has no attribute 'get_member'
</code>```

(sometimes this would also happen when trying to get the avatar URLs)

I enabled logging and after the exception, it would output(I've removed the guild ID)

```<code>INFO:discord.state:Processed a chunk for 1000 members in guild ID -.
INFO:discord.state:Processed a chunk for 1000 members in guild ID -.
INFO:discord.state:Processed a chunk for 1000 members in guild ID -.
INFO:discord.state:Processed a chunk for 1000 members in guild ID -.
INFO:discord.state:Processed a chunk for 1000 members in guild ID -.
INFO:discord.state:Processed a chunk for 1000 members in guild ID -.
INFO:discord.state:Processed a chunk for 1000 members in guild ID -.
INFO:discord.state:Processed a chunk for 1000 members in guild ID -.
INFO:discord.state:Processed a chunk for 1000 members in guild ID -.
INFO:discord.state:Processed a chunk for 1000 members in guild ID -.
INFO:discord.state:Processed a chunk for 1000 members in guild ID -.
INFO:discord.state:Processed a chunk for 1000 members in guild ID -.
INFO:discord.state:Processed a chunk for 1000 members in guild ID -.
INFO:discord.state:Processed a chunk for 1000 members in guild ID -.
INFO:discord.state:Processed a chunk for 1000 members in guild ID -.
INFO:discord.state:Processed a chunk for 1000 members in guild ID -.
INFO:discord.state:Processed a chunk for 107 members in guild ID -.
</code>```

..which led me to believe that it actually succeeded at getting the guild, but for some reason it did not work in the code

I couldn't find any documentation on this, if anyone could point out where to find it/point out any mistakes I made that'd be much appreciated!

答:
Did you add the bot to the server?

After testing a bit it seems you can't get that data without the bot being allowed access to the server. If not, add it and then try again, that should work.

EDIT

```<code>@bot.command()
async def getMembers(ctx):
    members = ctx.guild.members

    print(members[:10])
</code>```

Body:
I'm trying to get certain user objects from a discord server using their IDs, but it can't get the guild object for some reason. My code:

@botclient.event
async def on_ready():
    for x in all_ids:
        guild = botclient.get_guild(GUILD)
        user=guild.get_member(x)
        all_urls[x]=user.avatar_url

botclient.run(TOKEN)

[TOKEN and GUILD are specified further above, I've checked multiple times and there seems to be nothing wrong with them]

It's worked in a smaller server before and I've tried several variations of this, but each gave me an AttributeError:

    user=guild.get_member(x)
AttributeError: 'NoneType' object has no attribute 'get_member'

(sometimes this would also happen when trying to get the avatar URLs)

I enabled logging and after the exception, it would output(I've removed the guild ID)

INFO:discord.state:Processed a chunk for 1000 members in guild ID -.
INFO:discord.state:Processed a chunk for 1000 members in guild ID -.
INFO:discord.state:Processed a chunk for 1000 members in guild ID -.
INFO:discord.state:Processed a chunk for 1000 members in guild ID -.
INFO:discord.state:Processed a chunk for 1000 members in guild ID -.
INFO:discord.state:Processed a chunk for 1000 members in guild ID -.
INFO:discord.state:Processed a chunk for 1000 members in guild ID -.
INFO:discord.state:Processed a chunk for 1000 members in guild ID -.
INFO:discord.state:Processed a chunk for 1000 members in guild ID -.
INFO:discord.state:Processed a chunk for 1000 members in guild ID -.
INFO:discord.state:Processed a chunk for 1000 members in guild ID -.
INFO:discord.state:Processed a chunk for 1000 members in guild ID -.
INFO:discord.state:Processed a chunk for 1000 members in guild ID -.
INFO:discord.state:Processed a chunk for 1000 members in guild ID -.
INFO:discord.state:Processed a chunk for 1000 members in guild ID -.
INFO:discord.state:Processed a chunk for 1000 members in guild ID -.
INFO:discord.state:Processed a chunk for 107 members in guild ID -.

..which led me to believe that it actually succeeded at getting the guild, but for some reason it did not work in the code

I couldn't find any documentation on this, if anyone could point out where to find it/point out any mistakes I made that'd be much appreciated!

Body:
Did you add the bot to the server?

After testing a bit it seems you can't get that data without the bot being allowed access to the server. If not, add it and then try again, that should work.

EDIT

@bot.command()
async def getMembers(ctx):
    members = ctx.guild.members

    print(members[:10])