问:
Array extension to remove object by value
```<code>extension Array {
    func removeObject<T where T : Equatable>(object: T) {
        var index = find(self, object)
        self.removeAtIndex(index)
    }
}
</code>```

However, I get an error on var index = find(self, object)

'T' is not convertible to 'T'

I also tried with this method signature: func removeObject(object: AnyObject), however, I get the same error:

'AnyObject' is not convertible to 'T'

What is the proper way to do this?

答:
Your problem is T is not related to the type of your array in anyway for example you could have

```<code>var array = [1,2,3,4,5,6]

array.removeObject(object:"four")
</code>```

"six" is Equatable, but its not a type that can be compared to Integer, if you change it to

```<code>var array = [1,2,3,4,5,6]

extension Array where Element : Equatable {
    mutating func removeObject(object: Element) {
        filter { $0 != object }
    }
}

array.removeObject(object:"four")
</code>```

it now produces an error on calling removeObject for the obvious reason its not an array of strings, to remove 4 you can just

```<code>array.removeObject(object:4)
</code>```

Other problem you have is its a self modifying struct so the method has to be labeled as so and your reference to it at the top has to be a var

Body:
extension Array {
    func removeObject<T where T : Equatable>(object: T) {
        var index = find(self, object)
        self.removeAtIndex(index)
    }
}

However, I get an error on var index = find(self, object)

'T' is not convertible to 'T'

I also tried with this method signature: func removeObject(object: AnyObject), however, I get the same error:

'AnyObject' is not convertible to 'T'

What is the proper way to do this?

Body:
Your problem is T is not related to the type of your array in anyway for example you could have

var array = [1,2,3,4,5,6]

array.removeObject(object:"four")

"six" is Equatable, but its not a type that can be compared to Integer, if you change it to

var array = [1,2,3,4,5,6]

extension Array where Element : Equatable {
    mutating func removeObject(object: Element) {
        filter { $0 != object }
    }
}

array.removeObject(object:"four")

it now produces an error on calling removeObject for the obvious reason its not an array of strings, to remove 4 you can just

array.removeObject(object:4)

Other problem you have is its a self modifying struct so the method has to be labeled as so and your reference to it at the top has to be a var


来源: stackexchange

问:
Any way to do a local CVS proxy/server?
I have an online CVS repository that I need to check code into. However, the server is outside my control and is often down.

So, is there a way to set up some sort of local CVS server/proxy such that I can check my code into the local CVS server regularly and have the local CVS server batch commit the changes to the online CVS repo periodically?

The local repository could possibly run some other SCM system, if that was necessary to prevent conflict with CVS. Online commits could possibly be done manually, or via cron. I'm open to suggestions.

I guess that my main concern would be the problems faced in trying to set up some sort of repository 'hierarchy'.

PS: I'm running Linux all along the 'hierarchy'.

Edit: Found a similar item here.

答: I have never used it, but CVSup may do what you need. As others have mentioned, though, a distributed VCS system like git or mercurial would probably be better.</p>

OwnerDisplayName: sybreon

ContentLicense: CC BY-SA 2.5

Title: Any way to do a local CVS proxy/server?

LastEditorDisplayName: sybreon

OwnerDisplayName: Brian Campbell


问:
How do I bind an iTunes style source list to an NSTableView using Core Data?
I have an iTunes style interface in my application: Source list (NSOutlineView) on the left that contains different libraries and playlists with an NSTableView on the right side of the interface displaying information for "Presentations".  Similar to iTunes, I am showing the same type of information in the table view whether a library or playlist is selected (title, author, date created, etc).

I currently have an NSArrayController connected to my NSTableView and was setting the fetch predicate based on what was selected in the source list.  This works fine when selecting a library because I can just set the fetch predicate to filter by the "type" field in my Presentation Core Data entity.  When I try to adjust the fetch predicate for the playlist however, it doesn't look like there is any way to set the fetch predicate because I've got a table in between Playlists and Presentations to keep up with the order within the Playlist.  According to the Apple docs, these type of predicates are not doable with Core Data (it basically doesn't multiple inner joins).  Below is the relevant portion of my Data Model.

Is my data model setup incorrectly?  Should I drop the NSArrayController and handle connecting the NSTableView up by hand?  I'm trying to figure out if there is a simple fix, or really a design flaw.

答:
There is a documentation for creating relationships in CoreData

http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CoreData/Articles/cdRelationships.html

http://developer.apple.com/library/mac/#documentation/cocoa/conceptual/CoreData/Articles/cdBindings.html

But afais from your DB model, you are doing it right with three tables:

Presentation with info about song
PlaylistItem with one-to-one relationship to Presentation
Playlist with one-to-many relationship to PlaylistItem

Presentation [ID TITLE URL ALBUM ARTIST ....]

PlaylistItem [ID Presentation_ID Playlist_ID]

Playlists    [ID Title MoreInfo]

So in language of IB CoreData implementation:

Start with fetching out every Playlist to NSOutlineView in left column

On select, get Playlist ID and Fetch all PlaylistItem based on Playlist_ID filtering

PlaylistItem will have Presentation object inside to access releated song info

And yes, if I were you, I would preffer to take care about connecting nstableview by hand

ContentLicense: CC BY-SA 3.0


问:
How do I insert in a <mat-toolbar> a clickable logo with Angular material?
Is there a way to insert in a <mat-toolbar> a clickable logo? I'm using Angular material and I want to insert the clickable image instead of aPHrodite in the following html code, in order to intercept the click event on that image.

```<code><mat-toolbar>
  <button mat-button [matMenuTriggerFor]="menu">
    <mat-icon>menu</mat-icon>
  </button>
  <mat-menu #menu="matMenu">
        ....
  <span>aPHrodite</span>
  <span class="spacer"></span>
        ....
</mat-toolbar>
</code>```

答:
An image tag with a click listener?

<mat-toolbar>
  ...

  ...
</mat-toolbar>
```

ContentLicense: CC BY-SA 4.0

Body:
Is there a way to insert in a <mat-toolbar> a clickable logo? I'm using Angular material and I want to insert the clickable image instead of aPHrodite in the following html code, in order to intercept the click event on that image.

<mat-toolbar>
  <button mat-button [matMenuTriggerFor]="menu">
    <mat-icon>menu</mat-icon>
  </button>
  <mat-menu #menu="matMenu">
        ....
  aPHrodite

        ....
</mat-toolbar>

Body:
An image tag with a click listener?

<mat-toolbar>
  ...
  <img [src]="myImageUrl" (click)="myMethod()">
  ...
</mat-toolbar>


问:
Search Data from multiple tables laravel
I am trying to search multiple data from two related tables. To be specific I want to get only "name column" from the users table and the rest of the columns from the posts table. But whenever I tried to search it prints the following error "Trying to get property 'name' of non-object"

Below is my user model

```<code><?php

namespace App;

use App\Mail\NewUserWelcomeMail;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Facades\Mail;

class User extends Authenticatable
{
    use Notifiable;

    protected $fillable = [
        'name', 'email','phone', 'username', 'password',
        'admin', 'address', 'description', 'approved_at',
    ];

    protected $hidden = [
        'password', 'remember_token',
    ];

    public function posts()
    {
        return $this->hasMany(Post::class)->orderBy('created_at', 'DESC');
    }
}
</code>```

And post model

```<code><?php

namespace App;

use Illuminate\Database\Eloquent\Model;

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

    public function user()
    {
        return $this->belongsTo(User::class);
    }
}
</code>```

And my Controller

```<code>public function showcampaign(User $user) {
    $q = Input::get( 'q' );

    if( !empty( $q ) ) {
        $showcampaign = User::join('posts','posts.user_id','users.id')
            ->where('name','LIKE','%'.$q.'%')
            ->orWhere('caption','LIKE','%'.$q.'%')
            ->orWhere('description','LIKE','%'.$q.'%')
            ->orWhere('duration','LIKE','%'.$q.'%')
            ->orWhere('amount','LIKE','%'.$q.'%')
            ->get();

        if(count($showcampaign) > 0) {
            return view('admin.campaignreport', ['show' => $showcampaign]);
        } else {
            return redirect('/campaignreport')->with('status', 'No Details found. Try to search again !');
        }
    } else {
        $showcampaign = Post::all();

        return view('admin.campaignreport')->with('show', $showcampaign);
    }
}
</code>```

Please help thanks

答:
I use scope query to create search functions. It makes my code more flexible and easy to understand.
Here is how you can do this.

In your "user" Model, you have to write "scopeFunctionName". you can write any functionName with scope. And in your Controller, you can simply call this function whenever you need as functionName(). and pass here your search term from request as functionName(request(['search']))

And now as you have declared relations for these tables to search data from related tables, try using this code in your user Model

```<code>public function scopeFilter($query, array $filters)
{
    /*
    Hey $query! whenever u get 'search term' in URL, call the function.
    If ['search'] exists or != null, then pass its value to the function
    else return false and don't execute the $query. If value exists,
    Then the function will execute the query and returns a result.
    */
    $query->when(
        $filters['search'] ?? false,
        fn ($query, $search) =>
        $query
            ->whereHas('users', function ($query) use ($search) {
                return $query
                    ->where('name', 'like', '%' . $search . '%')
            })
            ->where('name', 'like', '%' . $search . '%')
            ->orWhere('caption', 'like', '%', . $search . '%')
            ->orWhere('description', 'like', '%', . $search . '%')
            ->orWhere('id', $search)
    );
}
</code>```

And in Controller, you can pass the value to the scope function as:

```<code>public function index()
{
    return view('posts.index', [
        'show' => Post::all()->filter(request(['search']))->with('user')
    ]);
}
</code>```

Note: The code above has not been tested but it might solve your problem.

Body:
I am trying to search multiple data from two related tables. To be specific I want to get only "name column" from the users table and the rest of the columns from the posts table. But whenever I tried to search it prints the following error "Trying to get property 'name' of non-object"

Below is my user model

<?php

namespace App;

use App\Mail\NewUserWelcomeMail;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Facades\Mail;

class User extends Authenticatable
{
    use Notifiable;

    protected $fillable = [
        'name', 'email','phone', 'username', 'password',
        'admin', 'address', 'description', 'approved_at',
    ];

    protected $hidden = [
        'password', 'remember_token',
    ];

    public function posts()
    {
        return $this->hasMany(Post::class)->orderBy('created_at', 'DESC');
    }
}

And post model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

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

    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

And my Controller

public function showcampaign(User $user) {
    $q = Input::get( 'q' );

    if( !empty( $q ) ) {
        $showcampaign = User::join('posts','posts.user_id','users.id')
            ->where('name','LIKE','%'.$q.'%')
            ->orWhere('caption','LIKE','%'.$q.'%')
            ->orWhere('description','LIKE','%'.$q.'%')
            ->orWhere('duration','LIKE','%'.$q.'%')
            ->orWhere('amount','LIKE','%'.$q.'%')
            ->get();

        if(count($showcampaign) > 0) {
            return view('admin.campaignreport', ['show' => $showcampaign]);
        } else {
            return redirect('/campaignreport')->with('status', 'No Details found. Try to search again !');
        }
    } else {
        $showcampaign = Post::all();

        return view('admin.campaignreport')->with('show', $showcampaign);
    }
}

Please help thanks

Body:
I use scope query to create search functions. It makes my code more flexible and easy to understand.
Here is how you can do this.

In your "user" Model, you have to write "scopeFunctionName". you can write any functionName with scope. And in your Controller, you can simply call this function whenever you need as functionName(). and pass here your search term from request as functionName(request(['search']))

And now as you have declared relations for these tables to search data from related tables, try using this code in your user Model

public function scopeFilter($query, array $filters)
{
    /*
    Hey $query! whenever u get 'search term' in URL, call the function.
    If ['search'] exists or != null, then pass its value to the function
    else return false and don't execute the $query. If value exists,
    Then the function will execute the query and returns a result.
    */
    $query->when(
        $filters['search'] ?? false,
        fn ($query, $search) =>
        $query
            ->whereHas('users', function ($query) use ($search) {
                return $query
                    ->where('name', 'like', '%' . $search . '%')
            })
            ->where('name', 'like', '%' . $search . '%')
            ->orWhere('caption', 'like', '%', . $search . '%')
            ->orWhere('description', 'like', '%', . $search . '%')
            ->orWhere('id', $search)
    );
}

And in Controller, you can pass the value to the scope function as:

public function index()
{
    return view('posts.index', [
        'show' => Post::all()->filter(request(['search']))->with('user')
    ]);
}

Note: The code above has not been tested but it might solve your problem.


问:
C# graphs algorithms library
I'm looking for .NET library with the next graphs algorithms:

algorithm for finding a minimum
spanning tree;

algorithm for partitioning graph for N subgraphs with minimal number of connections.

I can write my own realization, but don't have too much time. Tell me, please, names of any existing libraries that can do this. Thanks.

答: The best solution was to use QuickGraph library. It already has algorithm for finding a minimum spanning tree. And I used their implementation of graph to write my own algorithm for partitioning it.

Title: C# graphs algorithms library


问:
Override create() method in ModelSerializer and get object by ID (Django 3.2)
Main Model

```<code>class Main(models.Model):
   title = models.CharField(max_length=255)
   event = models.ForeignKey('Event', null=True, on_delete=models.CASCADE)
</code>```

Event Model

```<code>class Event(models.Model):
   day = models.DateField(u'Day of the event', help_text=u'Day of the event', null=True)
</code>```

JSON Structure example:

```<code>{
   "titre": "main",
   "event": {
        "id": 13, #can't filter or get object by id
        "day": "2022-01-30"
    }
}
</code>```

Override create() in Serializer:

```<code>class MainSerializer(serializers.ModelSerializer):
    event = EventSerializer()

    class Meta:
        model = Main
        fields = '__all__'

    def create(self, validated_data):
        event_data = validated_data.pop('event')
        event = Event.objects.get(id=event_data['id'])
        main = Main.objects.create(event=event, **validated_data)
        return main
</code>```

Event Serializer:

```<code>class EventSerializer(serializers.ModelSerializer):

class Meta:
    model = Event
    fields = '__all__'
</code>```

So I encounter an error "KeyError id" and I can't add the object.

答:
The solution was quite simple : just add this line to the EventSerializer</p>
```<code>id = serializers.IntegerField(required=False)
</code>```

Body:
Main Model

class Main(models.Model):
   title = models.CharField(max_length=255)
   event = models.ForeignKey('Event', null=True, on_delete=models.CASCADE)

Event Model

class Event(models.Model):
   day = models.DateField(u'Day of the event', help_text=u'Day of the event', null=True)

JSON Structure example:

{
   "titre": "main",
   "event": {
        "id": 13, #can't filter or get object by id
        "day": "2022-01-30"
    }
}

Override create() in Serializer:

class MainSerializer(serializers.ModelSerializer):
    event = EventSerializer()

    class Meta:
        model = Main
        fields = '__all__'

    def create(self, validated_data):
        event_data = validated_data.pop('event')
        event = Event.objects.get(id=event_data['id'])
        main = Main.objects.create(event=event, **validated_data)
        return main

Event Serializer:

class EventSerializer(serializers.ModelSerializer):

class Meta:
    model = Event
    fields = '__all__'

So I encounter an error "KeyError id" and I can't add the object.

Body:
The solution was quite simple : just add this line to the EventSerializer

id = serializers.IntegerField(required=False)


问:
Kotlin Multiplatform project import jvm variant
I have a Kotlin Multiplatform project that targets both Jvm and Android.

Creating separate javafx and android sample projects, but for my javafx module when I add the dependency for my multiplatform module, it is importing the -android variant.

// sample-javafx build.gradle.kts

plugins {
    kotlin("jvm")
    // javafx plugins
    id("application")
}

// gradle stuff...

dependencies {
    // this imports the -android variant
    implementation(project("my-multiplatform-module"))
}
```
<p>For example, when importing a published multiplatform library you can specify the <code>-jvm</code> variant, like:</p>
<pre class="lang-kotlin prettyprint-override"><code>// build.gradle.kts

dependencies {
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core-jvm:1.6.0")
}
</code>```

How can I configure the dependency for my javafx sample to import the -jvm variant of my kmp library project module?

答:
My wild guess is that in this case the multiplatform library is not exposing a jvm artifact explicitly, this could be a potential feature request

Alternatively you could try publishToMavenLocal() and consume it from local maven

Body:
I have a Kotlin Multiplatform project that targets both Jvm and Android.

Creating separate javafx and android sample projects, but for my javafx module when I add the dependency for my multiplatform module, it is importing the -android variant.

// sample-javafx build.gradle.kts

plugins {
    kotlin("jvm")
    // javafx plugins
    id("application")
}

// gradle stuff...

dependencies {
    // this imports the -android variant
    implementation(project("my-multiplatform-module"))
}

For example, when importing a published multiplatform library you can specify the -jvm variant, like:

// build.gradle.kts

dependencies {
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core-jvm:1.6.0")
}

How can I configure the dependency for my javafx sample to import the -jvm variant of my kmp library project module?


问:
Figure out from where user landing on a URL
I have an onboarding page like this www.abc.com/ welcome. On continuing users land on /set-profile image page.

There is a Submit on this page.

When users click on Submit button, if the user has come from /welcome,  I want users to go to the configuration page,  else I want users to go to /home.

The issue I am facing is, I tried both window.location and use history but I can't figure out how to find the "from" location.

What I am doing wrong?

答:
You can't access the browser history from JS (that would be a security issue).
What you can do is add a query string to your /set-profile route (such as ?returnTo=/welcome) and use it for the redirection.</p>


问:
Struggling to have DayJs available for all tests in cypress
I'm currently starting a new Cypress project, the application to test is quite "calendar centered" and I'll have to play a lot with dates.

My issue is I can't get DayJs available for the whole project without having to import it in every spec files.

For instance, in a test.spec.ts, this is working

```<code>import dayjs = require('dayjs');

describe('Some suite', () => {
   it('Some Test', () => {
      // some stuff
      const myDate = dayjs('11-11-2022', 'dd-MM-YYYY' );
      // other stuff
   })
})
</code>```

But when I do this in support/index.ts

```<code>import dayjs = require('dayjs')

declare namespace Cypress {
    interface Cypress {
        dayjs: dayjs.Dayjs;
    }
}
</code>```

and then this in my spec

```<code>describe('Some suite', () => {
    it('Some Test', () => {
       // some stuff
       const myDate = Cypress.dayjs('11-11-2022', 'dd-MM-YYYY' );
       // other stuff
    })
})
</code>```

it says

Cypress.dayjs is not a function

Any idea on how I could get this work?
Thanks for the help

答:
In /cypress/support/index.ts, add dayjs to the global Cypress (just like momentjs used to be included).

/cypress/support/index.ts

const dayjs = require('dayjs')

declare namespace Cypress {
  interface Cypress {
    dayjs: dayjs.Dayjs;
  }
}

Cypress.dayjs = dayjs
```

Now const myDate = Cypress.dayjs('11-11-2022', 'dd-MM-YYYY') should work.

Body:
I'm currently starting a new Cypress project, the application to test is quite "calendar centered" and I'll have to play a lot with dates.

My issue is I can't get DayJs available for the whole project without having to import it in every spec files.

For instance, in a test.spec.ts, this is working

import dayjs = require('dayjs');

describe('Some suite', () => {
   it('Some Test', () => {
      // some stuff
      const myDate = dayjs('11-11-2022', 'dd-MM-YYYY' );
      // other stuff
   })
})

But when I do this in support/index.ts

import dayjs = require('dayjs')

declare namespace Cypress {
    interface Cypress {
        dayjs: dayjs.Dayjs;
    }
}

and then this in my spec

describe('Some suite', () => {
    it('Some Test', () => {
       // some stuff
       const myDate = Cypress.dayjs('11-11-2022', 'dd-MM-YYYY' );
       // other stuff
    })
})

it says

Cypress.dayjs is not a function

Any idea on how I could get this work?
Thanks for the help

Body:
In /cypress/support/index.ts, add dayjs to the global Cypress (just like momentjs used to be included).

/cypress/support/index.ts

const dayjs = require('dayjs')

declare namespace Cypress {
  interface Cypress {
    dayjs: dayjs.Dayjs;
  }
}

Cypress.dayjs = dayjs

Now const myDate = Cypress.dayjs('11-11-2022', 'dd-MM-YYYY') should work.


问:
allow service to be used with both http and https URL
Http url is working fine, but if I try the same for https url , I am getting the following exception :

Cannot find the X.509 certificate using the following search criteria:
  StoreName 'TrustedPeople', StoreLocation 'LocalMachine', FindType
  'FindByThumbprint', FindValue
  '67C54590FD5ECDD33901E6440F81B5EE60F9BF40'.

答: You need to get the SSL certificate and put it on your IIS.</p>


问:
Dropdown in Grafana dynamically populate with values pulled from BigQuery
I want to add a dynamic drop down menu in Grafana that populates the drop down list with the list of tests that are pulled from BigQuery.

There will be hundreds of tests pulled from BigQuery and I don't want the panel to become too cluttered with tests at the bottom so I want to have a drop down that dynamically populates with all the test names pulled from BigQuery.

The image below shows just a small sample but this will grow to be much larger.

答:
You can make use of Grafana variables.

Go to the dashboard Settings -> Variables and create a new variable with the type set to Query. Select your BigQuery data source as Data Source. Then you can write a SQL query that returns one column with all your test names. Save the variable.

Then there should be a dropdown at the top of the dashboard where you can choose the test name you want from. Then use the variable in your query, for example in the WHERE clause to filter for those test names only.


问:
Get data from django database model
I have a django model, PhoneNumberVerification.

It has two columns: phone number, and code.
I want to be able to get the code if I am given a phone number. Essentially, search the table for which row has the phone number as my phone number, and fetch the code for that given row.

I could write SQL for this, but I do not know how to execute that to fetch data in django models, and I was wondering if there was a better non-sql way to do this.

My model:

```<code>class PhoneNumberVerification(models.Model):
    phone_number = models.TextField(max_length = 20, blank = False, unique = True)
    code = models.CharField(max_length = 8, blank = False)
</code>```

What I want:

from .models import PhoneNumberVerification

def get_code(phone_number):
    # do some stuff
    return code
```

答:
to get the object, you can simply use:

def get_code(phone_number):
   try:
        phone_number_verification = PhoneNumberVerification.objects.get(phone_numer=phone_number)
        code = phone_number_verification.code
        return code
    except PhoneNumberVerification.DoesNotExist:
        pass # django will raise exception in case if number does not exist
```

if you know there is only one object that matches your query, you can use the get(), which will return the object directly.

Otherwise, you can use filter(), more on that here

Title: Get data from django database model

Body:
I have a django model, PhoneNumberVerification.

It has two columns: phone number, and code.
I want to be able to get the code if I am given a phone number. Essentially, search the table for which row has the phone number as my phone number, and fetch the code for that given row.

I could write SQL for this, but I do not know how to execute that to fetch data in django models, and I was wondering if there was a better non-sql way to do this.

My model:

class PhoneNumberVerification(models.Model):
    phone_number = models.TextField(max_length = 20, blank = False, unique = True)
    code = models.CharField(max_length = 8, blank = False)

What I want:

from .models import PhoneNumberVerification

def get_code(phone_number):
    # do some stuff
    return code

Body:
to get the object, you can simply use:

def get_code(phone_number):
   try:
        phone_number_verification = PhoneNumberVerification.objects.get(phone_numer=phone_number)
        code = phone_number_verification.code
        return code
    except PhoneNumberVerification.DoesNotExist:
        pass # django will raise exception in case if number does not exist

if you know there is only one object that matches your query, you can use the get(), which will return the object directly.

Otherwise, you can use filter(), more on that here


问:
Memory efficient alternative to rbind - in-place rbind?
I need to rbind two large data frames. Right now I use

```<code>df <- rbind(df, df.extension)
</code>```

but I (almost) instantly run out of memory. I guess its because df is held in the memory twice. I might see even bigger data frames in the future, so I need some kind of in-place rbind.

So my question is: Is there a way to avoid data duplication in memory when using rbind?

I found this question, which uses SqlLite, but I really want to avoid using the hard drive as a cache.

答:
Right now I worked out the following solution:

```<code>nextrow = nrow(df)+1
df[nextrow:(nextrow+nrow(df.extension)-1),] = df.extension
# we need to assure unique row names
row.names(df) = 1:nrow(df)
</code>```

Now I don't run out of memory. I think its because I store

```<code>object.size(df) + 2 * object.size(df.extension)
</code>```

while with rbind R would need

```<code>object.size(rbind(df,df.extension)) + object.size(df) + object.size(df.extension).
</code>```

After that I use

```<code>rm(df.extension)
gc(reset=TRUE)
</code>```

to free the memory I don't need anymore.

This solved my problem for now, but I feel that there is a more advanced way to do a memory efficient rbind. I appreciate any comments on this solution.

Body:
I need to rbind two large data frames. Right now I use

df <- rbind(df, df.extension)

but I (almost) instantly run out of memory. I guess its because df is held in the memory twice. I might see even bigger data frames in the future, so I need some kind of in-place rbind.

So my question is: Is there a way to avoid data duplication in memory when using rbind?

I found this question, which uses SqlLite, but I really want to avoid using the hard drive as a cache.

Body:
Right now I worked out the following solution:

nextrow = nrow(df)+1
df[nextrow:(nextrow+nrow(df.extension)-1),] = df.extension
# we need to assure unique row names
row.names(df) = 1:nrow(df)

Now I don't run out of memory. I think its because I store

object.size(df) + 2 * object.size(df.extension)

while with rbind R would need

object.size(rbind(df,df.extension)) + object.size(df) + object.size(df.extension).

After that I use

rm(df.extension)
gc(reset=TRUE)

to free the memory I don't need anymore.

This solved my problem for now, but I feel that there is a more advanced way to do a memory efficient rbind. I appreciate any comments on this solution.


问:
Why can I use std::nullptr_t without including any file in MSVC
Like this

auto func() {
    std::nullptr_t p;
    p=nullptr;
    return p;
}
```

I can build this code in msvc, but error in gcc

答:
std::nullptr_t is defined in <cstddef>, to use it you must include that header. That does not imply that your code must fail to compile when you do not include the header.

Due to the way includes work in C++ you often can get away without explicitly including a header, but the commonly accepted rule is that you should include what you use to ensure that your code is portable. Here it is not a transitive include that makes it work, but MSVC decided to have std::nullptr_t defined without any explicit include. That does not mean that you should not include what you use.

TL;DR: Include headers for what you use to write portable code.

Body:
Like this

auto func() {
    std::nullptr_t p;
    p=nullptr;
    return p;
}

I can build this code in msvc, but error in gcc


问:
Test if a webpage was opened succesfully via intent using Robolectric
I am having simple function as Below

```<code>fun openWebPage(url: String) {
    val openURL = Intent(Intent.ACTION_VIEW)
    openURL.data = Uri.parse(url)
    startActivity(openURL)
}
</code>```

How to test and verify that webpage is opened successfully using Robolectric?

答:
This code snippet helped to capture that scenario</p>
```<code>    val shadow = Shadows.shadowOf(activity)
    val exp_url = "www.google.com"
    val intent =  shadow.nextStartedActivity
    val url = intent.data.toString()
    assertEquals(exp_url,url)
</code>```

Body:
I am having simple function as Below

fun openWebPage(url: String) {
    val openURL = Intent(Intent.ACTION_VIEW)
    openURL.data = Uri.parse(url)
    startActivity(openURL)
}

How to test and verify that webpage is opened successfully using Robolectric?

Body:
This code snippet helped to capture that scenario

    val shadow = Shadows.shadowOf(activity)
    val exp_url = "www.google.com"
    val intent =  shadow.nextStartedActivity
    val url = intent.data.toString()
    assertEquals(exp_url,url)


问:
Exception: Unsupported Android Plugin version: 3.6.3. Flutter Android Studio
i'm having trouble while running my app.
I'm getting Exception: Unsupported Android Plugin version: 3.6.3. error.
Can any one help me to fix that?
I've also tried to change the graddle version but it doesn't seems to work also.
Attaching screenshot of flutter doctor and my error.
Thanks in advance.

答: Had the same issue...solved it buy upgrading the android gradle to the latest version</p>


问:
How to position antd notification - i want it to be centered
Im using this

```<code>export function notificationWithIcon(type, title, description, placement) {
  notification[type]({
    message: title,
    description: description,
    placement
  });
}
</code>```

However, the only options are topRight, bottomRight, bottomLeft or topLeft

I would like it to appear in the center of my screen. Is there any way to achieve that

EDIT: I used Majid's idea and this is how it looks like now. It's still positioned a bit to the right

答:
Based on documentations:

A notification box can appear from the topRight, bottomRight,
bottomLeft or topLeft of the viewport.

But you can customize it yourself with css classes:

```<code>.ant-notification-center {
  left: 50%;
  bottom: 50% !important;
  margin-right: 30%;
  transform: translate(-50%, -50%);
}
</code>```

and use the notification same as following sample:

```<code>import React from "react";
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import "./index.css";
import { Button, notification, Space } from "antd";
import { RadiusUpleftOutlined } from "@ant-design/icons";

const openNotification = (placement) => {
  notification.info({
    message: `Notification ${placement}`,
    duration: 10000,
    description:
      "This is the content of the notification. This is the content of the notification. This is the content of the notification.",
    placement
  });
};

ReactDOM.render(
  <div>
    <Space>
      <Button type="primary" onClick={() => openNotification("center")}>
        <RadiusUpleftOutlined />
        center
      </Button>
    </Space>
  </div>,
  document.getElementById("container")
);
</code>```

Body:
Im using this

export function notificationWithIcon(type, title, description, placement) {
  notification[type]({
    message: title,
    description: description,
    placement
  });
}

However, the only options are topRight, bottomRight, bottomLeft or topLeft

I would like it to appear in the center of my screen. Is there any way to achieve that

EDIT: I used Majid's idea and this is how it looks like now. It's still positioned a bit to the right

Body:
Based on documentations:

A notification box can appear from the topRight, bottomRight,
bottomLeft or topLeft of the viewport.

But you can customize it yourself with css classes:

.ant-notification-center {
  left: 50%;
  bottom: 50% !important;
  margin-right: 30%;
  transform: translate(-50%, -50%);
}

and use the notification same as following sample:

import React from "react";
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import "./index.css";
import { Button, notification, Space } from "antd";
import { RadiusUpleftOutlined } from "@ant-design/icons";

const openNotification = (placement) => {
  notification.info({
    message: `Notification ${placement}`,
    duration: 10000,
    description:
      "This is the content of the notification. This is the content of the notification. This is the content of the notification.",
    placement
  });
};

ReactDOM.render(
  <div>
    <Space>
      <Button type="primary" onClick={() => openNotification("center")}>
        <RadiusUpleftOutlined />
        center
      </Button>
    </Space>
  </div>,
  document.getElementById("container")
);


问:
Numpy arange but doubling step size
I am currently looking for a way to use something similar to np.arange, but with the option of doubling the step size.

I know that np.arangecreates evenly spaced arrays and is not supposed to support variable step sizes.
What I want as an output is something similar to np.array([0,1,3,7,15,31,...]).

Is there any built-in function that does this?

I have to use this very often and therefore would prefer to avoid for-loops or similar slow approaches.

答:
Try this answer

Numpy arange() function is directly a static step function. We can customize it a little to get the desired array np.array([0, 1, 3, 7, 15, 31, ...])

```<code>n = 10                     #number of elements
2**np.arange(0, n, 1)-1    #range function
</code>```

This can also provide certain results. This code is much easier than other for loop methods.

Comparing the results

Using for loops for array creations like this is more efficient in processing than other methods

```<code>import timeit

print(timeit.timeit(f'np.array([2**i-1 for i in range(10)])', setup='import numpy as np'))
# 3.5182215999811888

print(timeit.timeit(f'np.fromiter((2**i-1 for i in range(10)), int)', setup='import numpy as np'))
# 3.74799029994756

print(timeit.timeit(f'2 ** np.arange(0,10,1) - 1', setup='import numpy as np'))
# 4.791339100105688
</code>```

Hope you found the best answer for you :)

Title: Numpy arange but doubling step size

Body:
Try this answer

Numpy arange() function is directly a static step function. We can customize it a little to get the desired array np.array([0, 1, 3, 7, 15, 31, ...])

n = 10                     #number of elements
2**np.arange(0, n, 1)-1    #range function

This can also provide certain results. This code is much easier than other for loop methods.

Comparing the results

Using for loops for array creations like this is more efficient in processing than other methods

import timeit

print(timeit.timeit(f'np.array([2**i-1 for i in range(10)])', setup='import numpy as np'))
# 3.5182215999811888

print(timeit.timeit(f'np.fromiter((2**i-1 for i in range(10)), int)', setup='import numpy as np'))
# 3.74799029994756

print(timeit.timeit(f'2 ** np.arange(0,10,1) - 1', setup='import numpy as np'))
# 4.791339100105688

Hope you found the best answer for you :)


问:
moved to left and right after click?
My code does not work. What I want is to move my pagination to the left and to the right after #prev_pag and #next_pag are clicked on. I don't know why this code isn't working?

EXAMPLE: http://jsfiddle.net/szVKD/

JS code:

```<code>$('#next_pag').click(function() {
        $('#pagination').animate({
            marginLeft: '-=100px'
        },
        500);
    });
    $('#prev_pag').click(function() {
        $('#pagination').animate({
            marginLeft: '+=100px'
        },
        500);
    });
});
</code>```

答:
you nedd to play with left not marginleft...see here

```<code>$('#next_pag').click(function() {
        $('#pagination').animate({
            left: '-=100px'
        },
        500);
    });
    $('#prev_pag').click(function() {
        $('#pagination').animate({
            left: '+=100px'
        },
        500);
    });
});
</code>```

Title: moved to left and right after click?

Body:
My code does not work. What I want is to move my pagination to the left and to the right after #prev_pag and #next_pag are clicked on. I don't know why this code isn't working?

EXAMPLE: http://jsfiddle.net/szVKD/

JS code:

$('#next_pag').click(function() {
        $('#pagination').animate({
            marginLeft: '-=100px'
        },
        500);
    });
    $('#prev_pag').click(function() {
        $('#pagination').animate({
            marginLeft: '+=100px'
        },
        500);
    });
});

Body:
you nedd to play with left not marginleft...see here

$('#next_pag').click(function() {
        $('#pagination').animate({
            left: '-=100px'
        },
        500);
    });
    $('#prev_pag').click(function() {
        $('#pagination').animate({
            left: '+=100px'
        },
        500);
    });
});


问:
local storage don't save data after page reload react
I need to keep some data in local storage. I am making new object and put it into local storage. Then I see what is in local storage and I see changed data. After page reload local storage keeping default data. What the reason of this?

this is my function code:

```<code>const changeTitle = () => {
    const newObjData = cardData.map((item) => {
      if (item.id === cardId) {
        item.title = inputValue
      }
      return item
    })
    setCardsData(newObjData)
    localStorage.setItem('cardsData', JSON.stringify(newObjData))

    const newObjCards = cards.map((item) => {
      if (item.id === cardId) {
        item.title = inputValue
      }
      return item
    })
    localStorage.setItem('cards', JSON.stringify(newObjCards))

    setIsEdit(false)
  }
</code>```

How I get all data from storage for component

```<code>const [comments, setComments] = useState<ICommentsData[]>(JSON.parse(localStorage.getItem('comments') as string));
  const columns: IColumnData[] = JSON.parse(localStorage.getItem('columns') as string);
  const cardData: ICardData[] = JSON.parse(localStorage.getItem('cardsData') as string);
  const cards: ICard[] = JSON.parse(localStorage.getItem('cards') as string);
  const [colTitle, setColTitle] = useState<string>("");
  const [cardsData, setCardsData] = useState<ICardData[]>(JSON.parse(localStorage.getItem('cardsData') as string));
  const [inputValue, setInputValue] = useState('');
  const [isEdit, setIsEdit] = useState(false);

  useEffect(() => {
    setCardsData(cardsData.filter((item) => item.id === cardId))
    setComments(comments.filter((item) => item.cardId === cardId))
    getColTitle()
  }, [isEdit])
</code>```

答: I recommend you to create a custom hook useLocalSotrage here as an example. And try to use it.</p>

Body:
I need to keep some data in local storage. I am making new object and put it into local storage. Then I see what is in local storage and I see changed data. After page reload local storage keeping default data. What the reason of this?

this is my function code:

const changeTitle = () => {
    const newObjData = cardData.map((item) => {
      if (item.id === cardId) {
        item.title = inputValue
      }
      return item
    })
    setCardsData(newObjData)
    localStorage.setItem('cardsData', JSON.stringify(newObjData))

    const newObjCards = cards.map((item) => {
      if (item.id === cardId) {
        item.title = inputValue
      }
      return item
    })
    localStorage.setItem('cards', JSON.stringify(newObjCards))

    setIsEdit(false)
  }

How I get all data from storage for component

const [comments, setComments] = useState<ICommentsData[]>(JSON.parse(localStorage.getItem('comments') as string));
  const columns: IColumnData[] = JSON.parse(localStorage.getItem('columns') as string);
  const cardData: ICardData[] = JSON.parse(localStorage.getItem('cardsData') as string);
  const cards: ICard[] = JSON.parse(localStorage.getItem('cards') as string);
  const [colTitle, setColTitle] = useState<string>("");
  const [cardsData, setCardsData] = useState<ICardData[]>(JSON.parse(localStorage.getItem('cardsData') as string));
  const [inputValue, setInputValue] = useState('');
  const [isEdit, setIsEdit] = useState(false);

  useEffect(() => {
    setCardsData(cardsData.filter((item) => item.id === cardId))
    setComments(comments.filter((item) => item.cardId === cardId))
    getColTitle()
  }, [isEdit])


问:
Foreign key in Owned entity: "There is no corresponding CLR property or field"
This is a tale of optional owned entities and foreign keys.

I'm working with EF 5 (code first) and I do this :

```<code>public class Parent {
   public Guid Id  { get; private set; }
   public OwnedType1? Owned1  { get; private set; }
   public OwnedType2? Owned2  { get; private set; }

   public Parent(Guid id, OwnedType1? owned1, OwnedType2? owned2) {
     Id = id; Owned1 = owned1; Owned2 = owned2;
   }
}

public class OwnedType1 {
   public Guid? OptionalExternalId  { get; private set; }

   public OwnedType1 (Guid? optionalExternalId) {
     OptionalExternalId = optionalExternalId;
   }
}

public class OwnedType2 {
   public Guid? OptionalExternalId  { get; private set; }

   public OwnedType2 (Guid? optionalExternalId) {
     OptionalExternalId = optionalExternalId;
   }
}

public class Shared {
   public Guid Id  { get; private set; }
   public Shared (Guid id) {
     Id = id;
   }
}
</code>```

Now, the configuration :

```<code>//-------- for Parent ------------

       public void Configure(EntityTypeBuilder<Parent> builder) {

            builder
                .ToTable("Parents")
                .HasKey(p => p.Id);

            builder
                .OwnsOne(p => p.Owned1)
                .HasOne<Shared>()
                .WithMany()
                .HasForeignKey(x => x.OptionalExternalId);

             builder
                .OwnsOne(p => p.Owned2)
                .HasOne<Shared>()
                .WithMany()
                .HasForeignKey(x => x.OptionalExternalId);

       }

//-------- for OwnedType1 ------------

       // (there's no builder as they're owned and EntityTypeBuilder<Parent> is enough)

//-------- for OwnedType2 ------------

       // (there's no builder as they're owned and EntityTypeBuilder<Parent> is enough)

//-------- for Shared ---------------

       public void Configure(EntityTypeBuilder<Shared> builder) {

            builder
                .ToTable("Shareds")
                .HasKey(p => p.Id);
       }
</code>```

Side note : If you're wondering why OwnedType1 and OwnedType2 don't each have a property called 'ParentId', it's because it's created implicitly by the "OwnsOne".

My problem is this :

When I create a new Migration, then OwnedType1 works like a charm, but for OwnedType2 (which is quasi-identical), I get his error :

The property 'OptionalExternalId' cannot be added to the type
'MyNameSpace.OwnedType2' because no property type was specified and
there is no corresponding CLR property or field. To add a shadow state
property, the property type must be specified.

I don't understand what it's complaining about. And why it's complaining only for one of them.

I know that you probably can't work it out with this simplified version of my schema, but what I'm asking is what you think it might be (follow your guts of EF guru) :

Some missing constructor?

Incorrect visibility on one of the fields?

Bad navigation definition?

A typo?

Something tricky (like : If you're going to have TWO different entity classes having a one-to-many relation with Shared, then they can't use the same name for external key. Or I need to use a composite key. Or whatnot).

答:
It was a configuration issue that had nothing to do with Owned entities. Another case of "EF error message is obscure but issue is somewhere there in plain sight".

Unfortunately I don't remember how I fixed it. But it was along the lines of "Need an extra constructor with all the paramaters" or "one of the fields had a different name in the constructor parameters" or one of those classic EF mishaps.

Body:
This is a tale of optional owned entities and foreign keys.

I'm working with EF 5 (code first) and I do this :

public class Parent {
   public Guid Id  { get; private set; }
   public OwnedType1? Owned1  { get; private set; }
   public OwnedType2? Owned2  { get; private set; }

   public Parent(Guid id, OwnedType1? owned1, OwnedType2? owned2) {
     Id = id; Owned1 = owned1; Owned2 = owned2;
   }
}

public class OwnedType1 {
   public Guid? OptionalExternalId  { get; private set; }

   public OwnedType1 (Guid? optionalExternalId) {
     OptionalExternalId = optionalExternalId;
   }
}

public class OwnedType2 {
   public Guid? OptionalExternalId  { get; private set; }

   public OwnedType2 (Guid? optionalExternalId) {
     OptionalExternalId = optionalExternalId;
   }
}

public class Shared {
   public Guid Id  { get; private set; }
   public Shared (Guid id) {
     Id = id;
   }
}

Now, the configuration :

//-------- for Parent ------------

       public void Configure(EntityTypeBuilder<Parent> builder) {

            builder
                .ToTable("Parents")
                .HasKey(p => p.Id);

            builder
                .OwnsOne(p => p.Owned1)
                .HasOne<Shared>()
                .WithMany()
                .HasForeignKey(x => x.OptionalExternalId);

             builder
                .OwnsOne(p => p.Owned2)
                .HasOne<Shared>()
                .WithMany()
                .HasForeignKey(x => x.OptionalExternalId);

       }

//-------- for OwnedType1 ------------

       // (there's no builder as they're owned and EntityTypeBuilder<Parent> is enough)

//-------- for OwnedType2 ------------

       // (there's no builder as they're owned and EntityTypeBuilder<Parent> is enough)

//-------- for Shared ---------------

       public void Configure(EntityTypeBuilder<Shared> builder) {

            builder
                .ToTable("Shareds")
                .HasKey(p => p.Id);
       }

Side note : If you're wondering why OwnedType1 and OwnedType2 don't each have a property called 'ParentId', it's because it's created implicitly by the "OwnsOne".

My problem is this :

When I create a new Migration, then OwnedType1 works like a charm, but for OwnedType2 (which is quasi-identical), I get his error :

The property 'OptionalExternalId' cannot be added to the type
'MyNameSpace.OwnedType2' because no property type was specified and
there is no corresponding CLR property or field. To add a shadow state
property, the property type must be specified.

I don't understand what it's complaining about. And why it's complaining only for one of them.

I know that you probably can't work it out with this simplified version of my schema, but what I'm asking is what you think it might be (follow your guts of EF guru) :

Some missing constructor?

Incorrect visibility on one of the fields?

Bad navigation definition?

A typo?

Something tricky (like : If you're going to have TWO different entity classes having a one-to-many relation with Shared, then they can't use the same name for external key. Or I need to use a composite key. Or whatnot).


问:
Calculate n dates of next x days of the week
so I'm trying to build a function that allows me to calculate the dates of the next x days of the week, for example, I want 5 dates from now (02/08/2022), of Tuesday and Thursday, so the output should be:

```<code> 02/08/2022 - Tu
 02/10/2022 - Th
 02/15/2022 - Tu
 02/17/2022 - Th
 02/22/2022 - Tu
</code>```

I'm not sure how to achieve that, since I want to be able to input various days of the week... Is there a way to do this? My current aproach is this one, but of couse, is not doing what I want, I kinda blocked right now, sorry if the answer is too obvious:

```<code>function getNextDates($start_date, $range_weeks, $how_many_dates, $days)
{

    $range = 'P' . ($range_weeks * 7) . 'D';
    $sd = new DateTimeImmutable($start_date);
    $nd = new DateTime($start_date);
    $dates_list = array();
    $dates_list[0] = array('day' => $sd->format('D'), 'date' => $sd->format('d-m-Y'));
    $ind = 1;
    $how_many_dates--;

    while ($how_many_dates > 0) {
        // This in case I want a n weeks space
        $nd->add(new DateInterval($range));

        for ($i = 0; $i < count($days); $i++) {
            if (($i + 1) < count($days)) {
                if ($sd->modify($this->nextDay($days[$i])) < $sd->modify($this->nextDay($days[$i + 1]))) {
                    $nextDate = $nd->modify($this->nextDay($days[$i]));
                    $dates_list[$ind] = array('day' => $nextDate->format('D'), 'date' => $nextDate->format('d-m-Y'));
                    $how_many_dates--;
                    $ind++;
                }
            } else {
                $nextDate = $nd->modify($this->nextDay($days[$i]));
                //   $sd = $nextDate;
                $dates_list[$ind] = array('day' => $nextDate->format('D'), 'date' => $nextDate->format('d-m-Y'));
                $how_many_dates--;
                $ind++;
            }
            if ($how_many_dates <= 0) break;
        }
    }

    return $dates_list;
}
</code>```

Being:

```<code>$start_date: 02/08/2022
$range_weeks: 0 // Meaning every week
$how_many_dates: 5
$days: Tuesday, Thursday
</code>```

I got:

```<code>02/08/2022
02/10/2022
02/17/2022
02/24/2022
03/03/2022
</code>```

Sorry for my amateur code...

答:
Starting from the start date, a day is always added and it is checked whether it is the desired day of the week.

```<code>$start = "02/08/2022";
$number = 5;
$weekDays = ['Tue','Thu'];

$dates = [];
for($date = date_create($start); $number > 0; $date->modify('+1 Day')){
  $day = $date->format('D');
  if(in_array($day,$weekDays)) {
    $dates[] = $date->format("d/m/Y");
    $number--;
  }
}
</code>```

Result $dates

```<code>array (
  0 => "08/02/2022",
  1 => "10/02/2022",
  2 => "15/02/2022",
  3 => "17/02/2022",
  4 => "22/02/2022",
)
</code>```

Body:
so I'm trying to build a function that allows me to calculate the dates of the next x days of the week, for example, I want 5 dates from now (02/08/2022), of Tuesday and Thursday, so the output should be:

 02/08/2022 - Tu
 02/10/2022 - Th
 02/15/2022 - Tu
 02/17/2022 - Th
 02/22/2022 - Tu

I'm not sure how to achieve that, since I want to be able to input various days of the week... Is there a way to do this? My current aproach is this one, but of couse, is not doing what I want, I kinda blocked right now, sorry if the answer is too obvious:

function getNextDates($start_date, $range_weeks, $how_many_dates, $days)
{

    $range = 'P' . ($range_weeks * 7) . 'D';
    $sd = new DateTimeImmutable($start_date);
    $nd = new DateTime($start_date);
    $dates_list = array();
    $dates_list[0] = array('day' => $sd->format('D'), 'date' => $sd->format('d-m-Y'));
    $ind = 1;
    $how_many_dates--;

    while ($how_many_dates > 0) {
        // This in case I want a n weeks space
        $nd->add(new DateInterval($range));

        for ($i = 0; $i < count($days); $i++) {
            if (($i + 1) < count($days)) {
                if ($sd->modify($this->nextDay($days[$i])) < $sd->modify($this->nextDay($days[$i + 1]))) {
                    $nextDate = $nd->modify($this->nextDay($days[$i]));
                    $dates_list[$ind] = array('day' => $nextDate->format('D'), 'date' => $nextDate->format('d-m-Y'));
                    $how_many_dates--;
                    $ind++;
                }
            } else {
                $nextDate = $nd->modify($this->nextDay($days[$i]));
                //   $sd = $nextDate;
                $dates_list[$ind] = array('day' => $nextDate->format('D'), 'date' => $nextDate->format('d-m-Y'));
                $how_many_dates--;
                $ind++;
            }
            if ($how_many_dates <= 0) break;
        }
    }

    return $dates_list;
}

Being:

$start_date: 02/08/2022
$range_weeks: 0 // Meaning every week
$how_many_dates: 5
$days: Tuesday, Thursday

I got:

02/08/2022
02/10/2022
02/17/2022
02/24/2022
03/03/2022

Sorry for my amateur code...

Body:
Starting from the start date, a day is always added and it is checked whether it is the desired day of the week.

$start = "02/08/2022";
$number = 5;
$weekDays = ['Tue','Thu'];

$dates = [];
for($date = date_create($start); $number > 0; $date->modify('+1 Day')){
  $day = $date->format('D');
  if(in_array($day,$weekDays)) {
    $dates[] = $date->format("d/m/Y");
    $number--;
  }
}

Result $dates

array (
  0 => "08/02/2022",
  1 => "10/02/2022",
  2 => "15/02/2022",
  3 => "17/02/2022",
  4 => "22/02/2022",
)


问:
Query building for filter based on select dropdown in laravel
I'm a bit starter in the Laravel system so please bear with me.

Currently I have stored images in the database and they have columns featured and approved. They both have status 0, and 1. Approved/Not approved.

What I'm trying to to is to be able to filter from the admin dashboard:

All images ( this will be all images no mater what status they have - 0 and 1

Only approved - status 1

Not approved - status 0

This is what I have in my index.blade.php

```<code><div class="col-md-2">
   <div class="form-group">
      <label for="featured">Featured</label>
          <select class="form-control" name="featured" id="featured">
          <option value=""> All</option>
          <option value="1">Yes</option>
          <option value="0">No</option>
      </select>
   </div>
</div>
<div class="form-group">
   <label for="approved">Approved</label>
       <select class="form-control" name="approved" id="approved">
            <option value=""> All</option>
            <option value="1">Yes</option>
            <option value="0">No</option>
       </select>
</div>
<button type="submit" class="btn btn-primary">Search</button>
</code>```

And this is the query that I'm trying to build in the controller

```<code>public function index(Request $request)
{
    $approved = $request->approved;
    $featured = $request->featured;

    $images = Images::when($approved, function($query, $approved) {
        if ($approved == '0') {
            return $query->where('approved', 0);
        } else if ($approved == '1' ){
            return $query->where('approved', 1);
        } else {
            return $query->where('approved', [0,1]);
        }
    })
    ->when($featured, function($query, $featured) {
        if ($featured == '0') {
            return $query->where('featured', 0);
        } else if ($featured == '1' ){
            return $query->where('featured', 1);
        } else {
            return $query->where('featured', [0,1]);
        }
    })
    ->latest()->get();

    return view( .... );
}
</code>```

This is what I have in route

```<code>Route::resource('images', 'ImagesController')->except('show');
</code>```

First problem is that when I choose option "All" it doesn't show anything, and when I choose "No" or "Yes" it shows same results.

I also don't think that this is the correct way of building such query.

答:
Just try this code hop it will help you</p>
```<code><form action="{{route('images.index')}}">
        <div class="col-md-2">
            <div class="form-group">
                <label for="featured">Featured</label>
                <select class="form-control" name="featured" id="featured">
                    <option {{is_null(request()->input('featured')) ? 'selected' : ''}} value=""> All</option>
                    <option {{request()->input('featured') == 1 ? 'selected' : ''}} value="1">Yes</option>
                    <option {{!is_null(request()->input('featured')) && request()->input('featured') == 0 ? 'selected' : ''}} value="0">No</option>
                </select>
            </div>
        </div>
        <div class="form-group">
            <label for="approved">Approved</label>
            <select class="form-control" name="approved" id="approved">
                <option {{is_null(request()->input('approved')) ? 'selected' : ''}} value=""> All</option>
                <option {{request()->input('approved') == 1 ? 'selected' : ''}} value="1">Yes</option>
                <option {{!is_null(request()->input('approved')) && request()->input('approved') == 0 ? 'selected' : ''}} value="0">No</option>
            </select>
        </div>
        <button type="submit" class="btn btn-primary">Search</button>
    </form>

public function index(Request $request)
{
    $approved = $request->approved;
    $featured = $request->featured;

$images = Images::when(!is_null($approved), function ($query) use ($approved) {
            return $query->where('approved', $approved);
        })->when(!is_null($featured), function ($query) use ($featured) {
            return $query->where('featured', $featured);
        })->latest()->get();

    return view( .... );
}
</code>```

Body:
I'm a bit starter in the Laravel system so please bear with me.

Currently I have stored images in the database and they have columns featured and approved. They both have status 0, and 1. Approved/Not approved.

What I'm trying to to is to be able to filter from the admin dashboard:

All images ( this will be all images no mater what status they have - 0 and 1

Only approved - status 1

Not approved - status 0

This is what I have in my index.blade.php

      Featured
          <select class="form-control" name="featured" id="featured">
          <option value=""> All</option>
          <option value="1">Yes</option>
          <option value="0">No</option>
      </select>

   Approved
       <select class="form-control" name="approved" id="approved">
            <option value=""> All</option>
            <option value="1">Yes</option>
            <option value="0">No</option>
       </select>

<button type="submit" class="btn btn-primary">Search</button>

And this is the query that I'm trying to build in the controller

public function index(Request $request)
{
    $approved = $request->approved;
    $featured = $request->featured;

    $images = Images::when($approved, function($query, $approved) {
        if ($approved == '0') {
            return $query->where('approved', 0);
        } else if ($approved == '1' ){
            return $query->where('approved', 1);
        } else {
            return $query->where('approved', [0,1]);
        }
    })
    ->when($featured, function($query, $featured) {
        if ($featured == '0') {
            return $query->where('featured', 0);
        } else if ($featured == '1' ){
            return $query->where('featured', 1);
        } else {
            return $query->where('featured', [0,1]);
        }
    })
    ->latest()->get();

    return view( .... );
}

This is what I have in route

Route::resource('images', 'ImagesController')->except('show');

First problem is that when I choose option "All" it doesn't show anything, and when I choose "No" or "Yes" it shows same results.

I also don't think that this is the correct way of building such query.

Body:
Just try this code hop it will help you

<form action="{{route('images.index')}}">
        <div class="col-md-2">
            <div class="form-group">
                <label for="featured">Featured</label>
                <select class="form-control" name="featured" id="featured">
                    <option {{is_null(request()->input('featured')) ? 'selected' : ''}} value=""> All</option>
                    <option {{request()->input('featured') == 1 ? 'selected' : ''}} value="1">Yes</option>
                    <option {{!is_null(request()->input('featured')) && request()->input('featured') == 0 ? 'selected' : ''}} value="0">No</option>
                </select>
            </div>
        </div>
        <div class="form-group">
            <label for="approved">Approved</label>
            <select class="form-control" name="approved" id="approved">
                <option {{is_null(request()->input('approved')) ? 'selected' : ''}} value=""> All</option>
                <option {{request()->input('approved') == 1 ? 'selected' : ''}} value="1">Yes</option>
                <option {{!is_null(request()->input('approved')) && request()->input('approved') == 0 ? 'selected' : ''}} value="0">No</option>
            </select>
        </div>
        <button type="submit" class="btn btn-primary">Search</button>
    </form>

public function index(Request $request)
{
    $approved = $request->approved;
    $featured = $request->featured;

$images = Images::when(!is_null($approved), function ($query) use ($approved) {
            return $query->where('approved', $approved);
        })->when(!is_null($featured), function ($query) use ($featured) {
            return $query->where('featured', $featured);
        })->latest()->get();

    return view( .... );
}


问:
TypeError: int() argument must be a string, a bytes-like object or a number, not 'TextInput'
I am developing a Kivy password generator. The user is required to input a number (digit) into the app for password generate depending on how many characters are intended. Then, the app will generate a random character from the randint, finally, the output will be displayed into the output entry for a copy to the click board. Following are my code:

password_generator.py

```<code>from kivy.app import App
from kivy.lang import Builder
from kivy.uix.widget import Widget
from kivy.core.window import Window

from random  import randint

Builder.load_file('password_generator.kv')

Window.size = (350, 600)

class MainApp(App):
    title='Password Generator'
    def build(self):
        Window.clearcolor = (255/255, 255/255, 0, 1)
        return Mylayout()

    def password(self):

        self.root.ids.output_entry = ''

        pw_length = int(self.root.ids.input_entry)

        my_password = ''

        for x in range(pw_length):
            my_password += chr(randint(33, 126))

        self.root.ids.output_entry = my_password

    def clip_board(self):
        self.root.clipboard_clear()

        self.root.clipboard_append(self.root.ids.output_entry)

    def delete(self):
        self.root.ids.input_entry = ''
        self.root.ids.output_entry = ''

class Mylayout(Widget):
    pass

if __name__ == '__main__':
    MainApp().run()
</code>```

password_generator.kv

```<code>#:import Factory kivy.factory.Factory

<MyLayout>

    FloatLayout:

        Label:
            id: label_frame
            text: 'How Many Characters?'
            pos_hint: {'x': .8, 'y':5}
            size_hint: (2, .4)
            color: (0, 0, 0, 1)
            font_size: 24

        TextInput:
            id: input_entry
            text: ''
            multiline: False
            font_family: 'Helvatica'
            font_size: 24
            pos_hint: {'x': .8, 'y':4.5}
            size_hint: (2, .4)
            halign: "center"
            focus: True
            color: 'black'

        Button:
            text:'Generate A Strong Password'
            on_press: app.password()
            pos_hint: {'x': .8, 'y':3.8}
            size_hint: (2, .4)
            font_size: 15

        TextInput:
            id: output_entry
            text: ''
            multiline: False
            font_family: 'Helvatica'
            font_size: 24
            pos_hint: {'x': .8, 'y':3}
            size_hint: (2, .4)
            halign: "center"
            focus: True
            color: 'black'
            background_color : (255/255, 255/255, 0, 1)
            #foreground_color:  self.background_color
            color : 'black'

        Button:
            text : 'Copy To Clickboard'
            on_release: Factory.MyPopup().open(),
            on_press: app.clip_board()
            pos_hint: {'x': .8, 'y':2.5}
            size_hint: (2, .4)
            font_size: 15

        Button:
            text : "Reset"
            on_press : app.delete()
            pos_hint: {'x': .8, 'y':1.5}
            size_hint: (2, .4)
            font_size: 15

<MyPopup@Popup>
    # auto_dismiss: False
    auto_dismiss: True
    size_hint: 0.6, 0.2
    pos_hint: {'x':0.2, 'top':0.6}

    title: "Message Informed"

    BoxLayout
        orientation: "vertical"
        size: root.width, root.height
        Label:
            text: "Password Copied!"
            font_size: 15
        Button:
            text: "Close!"
            font_size: 15
            on_release: root.dismiss()
</code>```

When I click Generate Strong Password button and was required to output a random password character in the output entry, however, the following error was incurred:

```<code>Traceback (most recent call last):
   File "c:\Users\Kelvin Loh\Documents\kivyMD\password_generator.py", line 53, in <module>
     MainApp().run()
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\app.py", line 950, in run
     runTouchApp()
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\base.py", line 582, in runTouchApp
     EventLoop.mainloop()
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\base.py", line 347, in mainloop
     self.idle()
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\base.py", line 391, in idle
     self.dispatch_input()
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\base.py", line 342, in dispatch_input
     post_dispatch_input(*pop(0))
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\base.py", line 248, in post_dispatch_input
     listener.dispatch('on_motion', etype, me)
   File "kivy\_event.pyx", line 709, in kivy._event.EventDispatcher.dispatch
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\core\window\__init__.py", line 1412, in on_motion
     self.dispatch('on_touch_down', me)
   File "kivy\_event.pyx", line 709, in kivy._event.EventDispatcher.dispatch
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\core\window\__init__.py", line 1428, in on_touch_down
     if w.dispatch('on_touch_down', touch):
   File "kivy\_event.pyx", line 709, in kivy._event.EventDispatcher.dispatch
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\uix\widget.py", line 545, in on_touch_down
     if child.dispatch('on_touch_down', touch):
   File "kivy\_event.pyx", line 709, in kivy._event.EventDispatcher.dispatch
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\uix\widget.py", line 545, in on_touch_down
     if child.dispatch('on_touch_down', touch):
   File "kivy\_event.pyx", line 709, in kivy._event.EventDispatcher.dispatch
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\uix\behaviors\button.py", line 151, in on_touch_down
     self.dispatch('on_press')
   File "kivy\_event.pyx", line 705, in kivy._event.EventDispatcher.dispatch
   File "kivy\_event.pyx", line 1248, in kivy._event.EventObservers.dispatch
   File "kivy\_event.pyx", line 1132, in kivy._event.EventObservers._dispatch
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\lang\builder.py", line 57, in custom_callback
     exec(__kvlang__.co_value, idmap)
   File "C:\Users\Kelvin Loh\Documents\kivyMD\password_generator.kv", line 30, in <module>
     on_press: app.password()
   File "c:\Users\Kelvin Loh\Documents\kivyMD\password_generator.py", line 24, in password
     pw_length = int(self.root.ids.input_entry)
   File "kivy\weakproxy.pyx", line 254, in kivy.weakproxy.WeakProxy.__int__
 TypeError: int() argument must be a string, a bytes-like object or a number, not 'TextInput'
</code>```

How to resolve?

答:
When you use something like self.root.ids.some_name (or, self.ids.some_name) you are supposed to access a weak reference of the named (some_name) widget from root (or, some class).

Now to get an attr. of that proxy widget you can go as usual using '.' syntax i.e. like self.root.ids.some_name.prop (or, self.ids.some_name.prop).

Here, self.root.ids.output_entry is a TextInput instance. So to access any of its properties you can do something like, self.root.ids.output_entry.prop_name. With this I modified password method as,

    def password(self):

        self.root.ids.output_entry.text = ''

        input_text = self.root.ids.input_entry.text

        # Bellow you will handle user-input. You can use try-except or if-else or whatever that suits. I just implement a simple one.
        if input_text: # Means non-empty string.
            pw_length = int(input_text)
        else: # Raise Error or warn user via a message.
            pw_length = 0

        my_password = ''

        for x in range(pw_length):
            my_password += chr(randint(33, 126))

        self.root.ids.output_entry.text = my_password
```

Don't forget to apply the required changes (as described above) wherever necessary.

Body:
I am developing a Kivy password generator. The user is required to input a number (digit) into the app for password generate depending on how many characters are intended. Then, the app will generate a random character from the randint, finally, the output will be displayed into the output entry for a copy to the click board. Following are my code:

password_generator.py

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.widget import Widget
from kivy.core.window import Window

from random  import randint

Builder.load_file('password_generator.kv')

Window.size = (350, 600)

class MainApp(App):
    title='Password Generator'
    def build(self):
        Window.clearcolor = (255/255, 255/255, 0, 1)
        return Mylayout()

    def password(self):

        self.root.ids.output_entry = ''

        pw_length = int(self.root.ids.input_entry)

        my_password = ''

        for x in range(pw_length):
            my_password += chr(randint(33, 126))

        self.root.ids.output_entry = my_password

    def clip_board(self):
        self.root.clipboard_clear()

        self.root.clipboard_append(self.root.ids.output_entry)

    def delete(self):
        self.root.ids.input_entry = ''
        self.root.ids.output_entry = ''

class Mylayout(Widget):
    pass

if __name__ == '__main__':
    MainApp().run()

password_generator.kv

#:import Factory kivy.factory.Factory

<MyLayout>

    FloatLayout:

        Label:
            id: label_frame
            text: 'How Many Characters?'
            pos_hint: {'x': .8, 'y':5}
            size_hint: (2, .4)
            color: (0, 0, 0, 1)
            font_size: 24

        TextInput:
            id: input_entry
            text: ''
            multiline: False
            font_family: 'Helvatica'
            font_size: 24
            pos_hint: {'x': .8, 'y':4.5}
            size_hint: (2, .4)
            halign: "center"
            focus: True
            color: 'black'

        Button:
            text:'Generate A Strong Password'
            on_press: app.password()
            pos_hint: {'x': .8, 'y':3.8}
            size_hint: (2, .4)
            font_size: 15

        TextInput:
            id: output_entry
            text: ''
            multiline: False
            font_family: 'Helvatica'
            font_size: 24
            pos_hint: {'x': .8, 'y':3}
            size_hint: (2, .4)
            halign: "center"
            focus: True
            color: 'black'
            background_color : (255/255, 255/255, 0, 1)
            #foreground_color:  self.background_color
            color : 'black'

        Button:
            text : 'Copy To Clickboard'
            on_release: Factory.MyPopup().open(),
            on_press: app.clip_board()
            pos_hint: {'x': .8, 'y':2.5}
            size_hint: (2, .4)
            font_size: 15

        Button:
            text : "Reset"
            on_press : app.delete()
            pos_hint: {'x': .8, 'y':1.5}
            size_hint: (2, .4)
            font_size: 15

<MyPopup@Popup>
    # auto_dismiss: False
    auto_dismiss: True
    size_hint: 0.6, 0.2
    pos_hint: {'x':0.2, 'top':0.6}

    title: "Message Informed"

    BoxLayout
        orientation: "vertical"
        size: root.width, root.height
        Label:
            text: "Password Copied!"
            font_size: 15
        Button:
            text: "Close!"
            font_size: 15
            on_release: root.dismiss()

When I click Generate Strong Password button and was required to output a random password character in the output entry, however, the following error was incurred:

Traceback (most recent call last):
   File "c:\Users\Kelvin Loh\Documents\kivyMD\password_generator.py", line 53, in <module>
     MainApp().run()
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\app.py", line 950, in run
     runTouchApp()
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\base.py", line 582, in runTouchApp
     EventLoop.mainloop()
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\base.py", line 347, in mainloop
     self.idle()
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\base.py", line 391, in idle
     self.dispatch_input()
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\base.py", line 342, in dispatch_input
     post_dispatch_input(*pop(0))
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\base.py", line 248, in post_dispatch_input
     listener.dispatch('on_motion', etype, me)
   File "kivy\_event.pyx", line 709, in kivy._event.EventDispatcher.dispatch
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\core\window\__init__.py", line 1412, in on_motion
     self.dispatch('on_touch_down', me)
   File "kivy\_event.pyx", line 709, in kivy._event.EventDispatcher.dispatch
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\core\window\__init__.py", line 1428, in on_touch_down
     if w.dispatch('on_touch_down', touch):
   File "kivy\_event.pyx", line 709, in kivy._event.EventDispatcher.dispatch
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\uix\widget.py", line 545, in on_touch_down
     if child.dispatch('on_touch_down', touch):
   File "kivy\_event.pyx", line 709, in kivy._event.EventDispatcher.dispatch
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\uix\widget.py", line 545, in on_touch_down
     if child.dispatch('on_touch_down', touch):
   File "kivy\_event.pyx", line 709, in kivy._event.EventDispatcher.dispatch
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\uix\behaviors\button.py", line 151, in on_touch_down
     self.dispatch('on_press')
   File "kivy\_event.pyx", line 705, in kivy._event.EventDispatcher.dispatch
   File "kivy\_event.pyx", line 1248, in kivy._event.EventObservers.dispatch
   File "kivy\_event.pyx", line 1132, in kivy._event.EventObservers._dispatch
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\lang\builder.py", line 57, in custom_callback
     exec(__kvlang__.co_value, idmap)
   File "C:\Users\Kelvin Loh\Documents\kivyMD\password_generator.kv", line 30, in <module>
     on_press: app.password()
   File "c:\Users\Kelvin Loh\Documents\kivyMD\password_generator.py", line 24, in password
     pw_length = int(self.root.ids.input_entry)
   File "kivy\weakproxy.pyx", line 254, in kivy.weakproxy.WeakProxy.__int__
 TypeError: int() argument must be a string, a bytes-like object or a number, not 'TextInput'

How to resolve?

Body:
When you use something like self.root.ids.some_name (or, self.ids.some_name) you are supposed to access a weak reference of the named (some_name) widget from root (or, some class).

Now to get an attr. of that proxy widget you can go as usual using '.' syntax i.e. like self.root.ids.some_name.prop (or, self.ids.some_name.prop).

Here, self.root.ids.output_entry is a TextInput instance. So to access any of its properties you can do something like, self.root.ids.output_entry.prop_name. With this I modified password method as,

    def password(self):

        self.root.ids.output_entry.text = ''

        input_text = self.root.ids.input_entry.text

        # Bellow you will handle user-input. You can use try-except or if-else or whatever that suits. I just implement a simple one.
        if input_text: # Means non-empty string.
            pw_length = int(input_text)
        else: # Raise Error or warn user via a message.
            pw_length = 0

        my_password = ''

        for x in range(pw_length):
            my_password += chr(randint(33, 126))

        self.root.ids.output_entry.text = my_password

Don't forget to apply the required changes (as described above) wherever necessary.


问:
Asp.net table display using grid view and deleting one row in the website
I am displaying a table in a grid view in a asp.net webpage. I want the user to select one row in the website and delete it. How can I do that. I have a delete button in the same page, where I will do code behind to drop the row in the database. But my problem is how can user select one row in the table .

```<code> <asp:GridView ID="GridView1" runat="server" CssClass="style29">
     <Columns>
         <asp:TemplateField HeaderText="Send Message to Group">
         <ItemTemplate>
             <asp:LinkButton ID="LinkButton2" runat="server"
             PostBackUrl='<%# Eval("GroupName", "SendMessage.aspx?GroupName={0}") %>'
             Text='Send Message'></asp:LinkButton>
        </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>
</code>```

Is it possible to do without a check box? Or can I add a delete image to the table in a separate column and on clicking the button the row will be deleted.

答:
You should add:

```<code><asp:CommandField ShowSelectButton="True"/>
</code>```

on your gridview.

Body:
I am displaying a table in a grid view in a asp.net webpage. I want the user to select one row in the website and delete it. How can I do that. I have a delete button in the same page, where I will do code behind to drop the row in the database. But my problem is how can user select one row in the table .

 <asp:GridView ID="GridView1" runat="server" CssClass="style29">
     <Columns>
         <asp:TemplateField HeaderText="Send Message to Group">
         <ItemTemplate>
             <asp:LinkButton ID="LinkButton2" runat="server"
             PostBackUrl='<%# Eval("GroupName", "SendMessage.aspx?GroupName={0}") %>'
             Text='Send Message'></asp:LinkButton>
        </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

Is it possible to do without a check box? Or can I add a delete image to the table in a separate column and on clicking the button the row will be deleted.

Body:
You should add:

<asp:CommandField ShowSelectButton="True"/>

on your gridview.


问:
What is the best way to load environment variables in your build
For a project I am working on I am setting up a BitBucket pipeline. Everything works great except for the environment vars. One of the usages of my env vars is the API_URL. I am loading the url by using process.env.API_URL. Locally this works great since it loads the .env file by using dotenv-webpack. However, in the pipeline I don't know what the best way is to load these vars. Should I add all the vars to Bitbucket and add export API_URL=$API_URL for every var in the pipeline file or are there better ways to load the vars?

答:
I think it depends on what you are using to serve your application & at build stage npm build creates a static artefacts with env values.
So you can use nginx subfilter in case using nginx to replace the values with environment variable.

Also, you can set env as mentioned here - https://support.atlassian.com/bitbucket-cloud/docs/variables-and-secrets/


问:
Loadbalancing GCP ALERT_HANDSHAKE_FAILURE

Hi im trying to config a HTTPS loadbalancer in GCP but when i made it
show me that:

```<code>Error: write EPROTO 140392502987240:error:10000410:SSL routines:OPENSSL_internal:SSLV3_ALERT_HANDSHAKE_FAILURE:../../third_party/boringssl/src/ssl/tls_record.cc:594:SSL alert number 40 140392502987240:error:1000009a:SSL routines:OPENSSL_internal:HANDSHAKE_FAILURE_ON_CLIENT_HELLO:../../third_party/boringssl/src/ssl/handshake.cc:604:
</code>```

I use GCP default as default politic ssl
And the certificate is valid:

My frontends

But is still not working, i dont know what other thing do.

答:
SSL proxy load balancers and global external HTTP(S) load balancers do not support SSL versions 3.0(SSLV3) or earlier. So, try to use a newer and more secure version to call the HTTPS Load balancer. Check whether the certificate is valid and linked properly with the page.

EDIT:

SSL fatal error, handshake failure 40 indicates the secure connection failed to establish because the client and the server couldn't agree on connection settings. Usually because the client or the server is way too old, only supporting removed protocols/ciphers. Try adding the domain name of the server to connect and a TLS connection will be established.

Example:

```<code>$ openssl s_client -connect 104.26.3.5:443 -servername external.example.com
</code>```

Body:
Hi im trying to config a HTTPS loadbalancer in GCP but when i made it
show me that:

Error: write EPROTO 140392502987240:error:10000410:SSL routines:OPENSSL_internal:SSLV3_ALERT_HANDSHAKE_FAILURE:../../third_party/boringssl/src/ssl/tls_record.cc:594:SSL alert number 40 140392502987240:error:1000009a:SSL routines:OPENSSL_internal:HANDSHAKE_FAILURE_ON_CLIENT_HELLO:../../third_party/boringssl/src/ssl/handshake.cc:604:

I use GCP default as default politic ssl
And the certificate is valid:

My frontends

But is still not working, i dont know what other thing do.

Body:
SSL proxy load balancers and global external HTTP(S) load balancers do not support SSL versions 3.0(SSLV3) or earlier. So, try to use a newer and more secure version to call the HTTPS Load balancer. Check whether the certificate is valid and linked properly with the page.

EDIT:

SSL fatal error, handshake failure 40 indicates the secure connection failed to establish because the client and the server couldn't agree on connection settings. Usually because the client or the server is way too old, only supporting removed protocols/ciphers. Try adding the domain name of the server to connect and a TLS connection will be established.

Example:

$ openssl s_client -connect 104.26.3.5:443 -servername external.example.com


问:
Configuring the parameter in the ExeCommand of Wix
In my Wix installer project, I am launching an executable through custom action and passing input parameters to the executable through ExeCommand.

```<code><CustomAction Id="LaunchExecutable" Execute="deferred"
             ExeCommand='"[INSTALLDIR]Product.exe" /install "STAGING"'
             Directory="INSTALLDIR"
             Impersonate="yes"
             Return="ignore" />
</code>```

I want to avoid hardcoding the "STAGING" in ExeCommand and pass it as a variable like $(var.Environment). I want the ExeCommand to look something like this :

```<code>   <?define Environment= Staging?>
    ExeCommand='"[INSTALLDIR]Product.exe" /install $(var.Environment)'
</code>```

Is there a way to configure the parameter ? I tried doing it but I recieved Undefined preprocessor error.

答:
I was able to get this working by enclosing the $(var.Environment) with quot like :</p>
```<code> ExeCommand=""[INSTALLDIR]Product.exe" /install "$(var.Environment)""
</code>```

Body:
In my Wix installer project, I am launching an executable through custom action and passing input parameters to the executable through ExeCommand.

<CustomAction Id="LaunchExecutable" Execute="deferred"
             ExeCommand='"[INSTALLDIR]Product.exe" /install "STAGING"'
             Directory="INSTALLDIR"
             Impersonate="yes"
             Return="ignore" />

I want to avoid hardcoding the "STAGING" in ExeCommand and pass it as a variable like $(var.Environment). I want the ExeCommand to look something like this :

   <?define Environment= Staging?>
    ExeCommand='"[INSTALLDIR]Product.exe" /install $(var.Environment)'

Is there a way to configure the parameter ? I tried doing it but I recieved Undefined preprocessor error.

Body:
I was able to get this working by enclosing the $(var.Environment) with quot like :

 ExeCommand="&quot;[INSTALLDIR]Product.exe&quot; /install &quot;$(var.Environment)&quot;"


问:
Ionic does not recognize function call
I want some help with re-writing this code because it shows there is an error but the code works fine when run.

```<code>export function loadingReducer (state: LoadingState, action) {
    return reducer(state, action);
</code>```

it says I should use const or class but when I use those the code won't run.

答:
It sounds like a linting issue rather than an actual code problem. When using const, are you using it like this? :

export const loadingReducer = (state: LoadingState, action: Action) => {
  return reducer(state, action);
}
```

Title: Ionic does not recognize function call

Body:
I want some help with re-writing this code because it shows there is an error but the code works fine when run.

export function loadingReducer (state: LoadingState, action) {
    return reducer(state, action);

it says I should use const or class but when I use those the code won't run.


问:
I cannot find my CREATE VIEW table after refreshing even after "Commands completed successfully." message. (SQL)
--Creating View to store data for later visualizations

```<code>CREATE VIEW PeopleVaccinatedpercent AS

SELECT dea.continent, dea.location, dea.date, dea.population, vac.new_vaccinations
,SUM(cast(new_vaccinations as bigint))
OVER (Partition by dea.location ORDER BY dea.location, dea.date) AS RollingPeopleVaccinated
    FROM PortofolioProject..CovidDeaths dea
    JOIN PortofolioProject..CovidVaccination vac
    ON dea.location = vac.location
    and dea.date = vac.date
    WHERE dea.continent is not null

</code>```

Commands completed successfully.

After Refreshing I still don't get any result under Views file on the left

答:
First of all, make sure that you have expanded the correct database in the Object Explorer tree view in the left pane and that the SQL editor window is connected to the correct database. (The editor's current database is displayed in the toolbar, just below the main menu.) Being connected to the wrong database (often the master database) is a regular mistake by myself, anyway.

You should be aware that the Object Explorer pane is not automatically updated when you make modifications by executing an SQL query or script. You may update the tree view manually by right-clicking the desired node (in your case the Views node) in the tree and clicking Refresh in the context menu.

Also note the error in the SQL editor, indicated by a red underline. It may be the case that the local IntelliSense cache is corrupted or not updated correctly. You can update it manually. In the main menu, go to Edit->Intellisense->Refresh local cache. Shortly after clicking it, the error message (red underline) should disappear.

Body:
--Creating View to store data for later visualizations

CREATE VIEW PeopleVaccinatedpercent AS

SELECT dea.continent, dea.location, dea.date, dea.population, vac.new_vaccinations
,SUM(cast(new_vaccinations as bigint))
OVER (Partition by dea.location ORDER BY dea.location, dea.date) AS RollingPeopleVaccinated
    FROM PortofolioProject..CovidDeaths dea
    JOIN PortofolioProject..CovidVaccination vac
    ON dea.location = vac.location
    and dea.date = vac.date
    WHERE dea.continent is not null

Commands completed successfully.

After Refreshing I still don't get any result under Views file on the left


问:
How to redirect in php project using .htaccess file (redirect url without slash to url with slash using 301 redirect)
I want to redirect the urls in PHP as following using .htaccess file.

https://beld.onepa/bood-uddevalla  ->   https://beld.onepa/bood-uddevalla/

https://beld.onempa/buten-vbras/ ->  https://beld.onempa/buten-vbras

How can I describe command in .htaccess

答:
Try this:

```<code>Redirect 301 /old/page /new/page
</code>```

or

```<code>Redirect 302 /old/page /new/page
</code>```

Keep in mind:

A 301 redirect is a status code that tells search engines and users the page has permanently moved.

A 302 redirect is a temporary change that redirects both users and search engines to the desired new location for a limited amount of time, until the redirect is removed.

Body:
Try this:

Redirect 301 /old/page /new/page

or

Redirect 302 /old/page /new/page

Keep in mind:

A 301 redirect is a status code that tells search engines and users the page has permanently moved.

A 302 redirect is a temporary change that redirects both users and search engines to the desired new location for a limited amount of time, until the redirect is removed.