问:
How to send post request from c# windows forms to a laravel api with files?
I have a windows form that will send a post request to my simple laravel api.

Here's what I have done so far:

```<code>    private async void UploadScreenshot(string employee_id, string filepath)
    {

        string url = "http://127.0.0.1:8000/api/upload-screenshot";

        using (HttpClient client = new HttpClient())
        {
            var multiForm = new MultipartFormDataContent();

            Image ssimage = Image.FromFile(filepath);
            var byteimg = ImageToByteArray(ssimage);
            ByteArrayContent screenshotimg = new ByteArrayContent(byteimg);

            multiForm.Add(new ByteArrayContent(byteimg), "files");
            multiForm.Add(new StringContent(employee_id), "emp_number");

            var response = await client.PostAsync(url, multiForm);

            var responseString = await response.Content.ReadAsStringAsync();

            System.Windows.MessageBox.Show(responseString);
            //Console.WriteLine(responseString);

        }
    }
</code>```

this code is working only for StringContent.but in my ByteArrayContent it returns null. Event using the MultipartFormDataContent. I tried every answer here in Stackoverflow since yesterday but no luck for me.

this is my Laravel API controller:

```<code>public function UploadScreenshot(Request $request){

    $emp_number = $request->emp_number; //this is working..
    $file = $request->files; //this is null

    if ($request->hasFile('screenshot')) {
        $file = request()->file('files');

        $fname = date('YmdHis');

        $ext = $request->files->extension();

        $filename = $fname . '.' . $ext;

        $file->storeAs('screenshots/', $filename, ['disk' => 'private']);

    }
}
</code>```

Thanks.

答:
Here's what I did and works like a charm:

On PrintScreen method, I first save the file to temp dir. Then call my UploadScreenshot() method,

```<code>    private void PrintScreen()
    {
        DateTime utc = DateTime.UtcNow;
        string filename = emp_number + " - " + utc.Ticks.ToString() + ".png";

        Bitmap printscreen = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);

        Graphics graphics = Graphics.FromImage(printscreen as Image);

        graphics.CopyFromScreen(0, 0, 0, 0, printscreen.Size);

        printscreen.Save(runnitsettings + filename, ImageFormat.Png);

        UploadScreenshot(emp_number, runnitsettings + filename);
    }
</code>```

In this function, I retrieve the file from the directory and load it to FileStream, instead of adding the file directly to a MultipartFormDataContent(); I created a function ImageToByte() that will first convert the file to byte and then convert to Base64String.

```<code>    private void UploadScreenshot(string employee_id, string filepath)
    {

        string url = baseurl + "upload-screenshot";

        System.IO.FileStream fsstream = new System.IO.FileStream(filepath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
        string b64image = ImageToByte(fsstream);
        fsstream.Dispose();
        File.Delete(filepath);

        //I deleted the file after convertion to free some diskspace.

        var multiForm = new MultipartFormDataContent();
        multiForm.Add(new StringContent(employee_id), "emp_number");
        multiForm.Add(new StringContent(b64image), "files");

        //Then I post the data:
        var response = await client.PostAsync(url, multiForm);
        var responseString = await response.Content.ReadAsStringAsync();
    }
</code>```

Image to Byte Function:

```<code>    public static string ImageToByte(FileStream fs)
    {
        byte[] imgBytes = new byte[fs.Length];
        fs.Read(imgBytes, 0, Convert.ToInt32(fs.Length));
        string encodeData = Convert.ToBase64String(imgBytes, Base64FormattingOptions.InsertLineBreaks);

        return encodeData;
    }
</code>```

In My Laravel Controller, I handle the file like this:

```<code>        $destinationpath = config('filesystems.disks')["private"]["root"]."/screenshots"."/";
        $emp_number = $request["emp_number"];
        $screenshot = $request["files"];

        $filename = $emp_number.'-'.date('YmdHis');

        $filePath = $destinationpath.$filename.".png";

        file_put_contents($filePath, base64_decode($screenshot));
</code>```

Body:
I have a windows form that will send a post request to my simple laravel api.

Here's what I have done so far:

    private async void UploadScreenshot(string employee_id, string filepath)
    {

        string url = "http://127.0.0.1:8000/api/upload-screenshot";

        using (HttpClient client = new HttpClient())
        {
            var multiForm = new MultipartFormDataContent();

            Image ssimage = Image.FromFile(filepath);
            var byteimg = ImageToByteArray(ssimage);
            ByteArrayContent screenshotimg = new ByteArrayContent(byteimg);

            multiForm.Add(new ByteArrayContent(byteimg), "files");
            multiForm.Add(new StringContent(employee_id), "emp_number");

            var response = await client.PostAsync(url, multiForm);

            var responseString = await response.Content.ReadAsStringAsync();

            System.Windows.MessageBox.Show(responseString);
            //Console.WriteLine(responseString);

        }
    }

this code is working only for StringContent.but in my ByteArrayContent it returns null. Event using the MultipartFormDataContent. I tried every answer here in Stackoverflow since yesterday but no luck for me.

this is my Laravel API controller:

public function UploadScreenshot(Request $request){

    $emp_number = $request->emp_number; //this is working..
    $file = $request->files; //this is null

    if ($request->hasFile('screenshot')) {
        $file = request()->file('files');

        $fname = date('YmdHis');

        $ext = $request->files->extension();

        $filename = $fname . '.' . $ext;

        $file->storeAs('screenshots/', $filename, ['disk' => 'private']);

    }
}

Thanks.

Body:
Here's what I did and works like a charm:

On PrintScreen method, I first save the file to temp dir. Then call my UploadScreenshot() method,

    private void PrintScreen()
    {
        DateTime utc = DateTime.UtcNow;
        string filename = emp_number + " - " + utc.Ticks.ToString() + ".png";

        Bitmap printscreen = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);

        Graphics graphics = Graphics.FromImage(printscreen as Image);

        graphics.CopyFromScreen(0, 0, 0, 0, printscreen.Size);

        printscreen.Save(runnitsettings + filename, ImageFormat.Png);

        UploadScreenshot(emp_number, runnitsettings + filename);
    }

In this function, I retrieve the file from the directory and load it to FileStream, instead of adding the file directly to a MultipartFormDataContent(); I created a function ImageToByte() that will first convert the file to byte and then convert to Base64String.

    private void UploadScreenshot(string employee_id, string filepath)
    {

        string url = baseurl + "upload-screenshot";

        System.IO.FileStream fsstream = new System.IO.FileStream(filepath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
        string b64image = ImageToByte(fsstream);
        fsstream.Dispose();
        File.Delete(filepath);

        //I deleted the file after convertion to free some diskspace.

        var multiForm = new MultipartFormDataContent();
        multiForm.Add(new StringContent(employee_id), "emp_number");
        multiForm.Add(new StringContent(b64image), "files");

        //Then I post the data:
        var response = await client.PostAsync(url, multiForm);
        var responseString = await response.Content.ReadAsStringAsync();
    }

Image to Byte Function:

    public static string ImageToByte(FileStream fs)
    {
        byte[] imgBytes = new byte[fs.Length];
        fs.Read(imgBytes, 0, Convert.ToInt32(fs.Length));
        string encodeData = Convert.ToBase64String(imgBytes, Base64FormattingOptions.InsertLineBreaks);

        return encodeData;
    }

In My Laravel Controller, I handle the file like this:

        $destinationpath = config('filesystems.disks')["private"]["root"]."/screenshots"."/";
        $emp_number = $request["emp_number"];
        $screenshot = $request["files"];

        $filename = $emp_number.'-'.date('YmdHis');

        $filePath = $destinationpath.$filename.".png";

        file_put_contents($filePath, base64_decode($screenshot));


来源: stackexchange

问:
How can I su from root to db2inst1 and invoke a SQL script, in one line?
How can I su from root to db2inst1 and invoke a SQL script all in 1 line?  I am thinking about something like this:

```<code>su db2inst1 | db2 CONNECT TO myDatabase USER db2inst1 USING mypw; db2 -c -i -w -td@ -f /tmp/deploy/sql/My.sql | exit;
</code>```

Any ideas?

答:
You can use the -c or --command=<command> option to execute a command with su.  In your case, something like this:

```<code>su -c 'db2 CONNECT TO myDatabase USER db2inst1 USING mypw; db2 -c -i -w -td@ -f /tmp/deploy/sql/My.sql' db2inst1
</code>```

ContentLicense: CC BY-SA 2.5

Body:
How can I su from root to db2inst1 and invoke a SQL script all in 1 line?  I am thinking about something like this:

su db2inst1 | db2 CONNECT TO myDatabase USER db2inst1 USING mypw; db2 -c -i -w -td@ -f /tmp/deploy/sql/My.sql | exit;

Any ideas?

LastEditorDisplayName: Eddie

Body:
You can use the -c or --command=<command> option to execute a command with su.  In your case, something like this:

su -c 'db2 CONNECT TO myDatabase USER db2inst1 USING mypw; db2 -c -i -w -td@ -f /tmp/deploy/sql/My.sql' db2inst1

OwnerDisplayName: David

LastEditorDisplayName: David


问:
how to emulate has_many :through with polymorphic classes
I understand why ActiveRecord can't support has_many :through on polymorphic classes.  But I would like to emulate some of its functionality.  Consider the following, where a join table associates two polymorphic classes:

```<code>class HostPest < ActiveRecord::Base
  belongs_to :host, :polymorphic => true
  belongs_to :pest, :polymorphic => true
end
class Host < ActiveRecord::Base
  self.abstract_class = true
  has_many :host_pests, :as => :host
end
class Pest < ActiveRecord::Base
  self.abstract_class = true
  has_one :host_pest, :as => :pest
end
class Dog < Host ; end
class Cat < Host ; end
class Flea < Pest ; end
class Tick < Pest ; end
</code>```

The goal

Since I can't do has_many :pests, :through=>:host_pests, :as=>:host (etc), I'd like to emulate these four methods:

```<code>dog.pests (returns a list of pests associated with this dog)
flea.host (return the host associated with this flea)
cat.pests << Tick.create (creates a HostPest record)
tick.host = Cat.create (creates a HostPest record)
</code>```

Question 1

I've got a working implementation for the first two methods (pests and host), but want to know if this is the best way (specifically, am I overlooking something in ActiveRecord associations that would help):

```<code>class Host < ActiveRecord::Base
  def pests
    HostPest.where(:host_id => self.id, :host_type => self.class).map {|hp| hp.pest}
  end
end
class Pest < ActiveRecord::Base
  def host
    HostPest.where(:pest_id => self.id, :pest_type => self.class).first.host
  end
end
</code>```

Question 2

I'm stumped on how to implement the << and = methods implied here:

```<code>cat.pests << Tick.create  # => HostPest(:host=>cat, :pest=>tick).create
tick.host = Cat.create    # => HostPest(:host=>cat, :pest=>tick).create
</code>```

Any suggestions?  (And again, can ActiveRecord associations provide any help?)

答:
You can address your problem by using STI and regular association:

```<code>class HostPest < ActiveRecord::Base
  belongs_to :host
  belongs_to :pest
end
</code>```

Store all the hosts in a table called hosts. Add a string column called type to the table.

```<code>class Host < ActiveRecord::Base
  has_many :host_pests
  has_many :pests, :through => :host_pests
end
</code>```

Inherit the Host class to create new hosts.

```<code>class Dog < Host ; end
class Cat < Host ; end
</code>```

Store all the pests in a table called pests. Add a string column called type to the table.

```<code>class Pest < ActiveRecord::Base
  has_one :host_pest
  has_one :host, :through => :host_pest
end
</code>```

Inherit the Pest class to create new pests.

```<code>class Flea < Pest ; end
class Tick < Pest ; end
</code>```

Now when you can run following commands:

```<code>dog.pests (returns a list of pests associated with this dog)
flea.host (return the host associated with this flea)
cat.pests << Tick.create (creates a HostPest record)
tick.host = Cat.create (creates a HostPest record)
</code>```

Note

Rails supports has_many :through on polymorphic classes. You need to specify the source_type for this to work.

Consider the models for tagging:

```<code>class Tag
  has_many :tag_links
end

class TagLink
  belongs_to :tag
  belongs_to :tagger, :polymorphic => true
end
</code>```

Let's say products and companies can be tagged.

```<code>class Product
  has_many :tag_links, :as => :tagger
  has_many :tags, :through => :tag_links
end

class Company
  has_many :tag_links, :as => :tagger
  has_many :tags, :through => :tag_links
end
</code>```

We can add an association on Tag model to get all the tagged products as follows:

```<code>class Tag
  has_many :tag_links
  has_many :products, :through => :tag_links,
                        :source => :tagger, :source_type => 'Product'
end
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I understand why ActiveRecord can't support has_many :through on polymorphic classes.  But I would like to emulate some of its functionality.  Consider the following, where a join table associates two polymorphic classes:

class HostPest < ActiveRecord::Base
  belongs_to :host, :polymorphic => true
  belongs_to :pest, :polymorphic => true
end
class Host < ActiveRecord::Base
  self.abstract_class = true
  has_many :host_pests, :as => :host
end
class Pest < ActiveRecord::Base
  self.abstract_class = true
  has_one :host_pest, :as => :pest
end
class Dog < Host ; end
class Cat < Host ; end
class Flea < Pest ; end
class Tick < Pest ; end

The goal

Since I can't do has_many :pests, :through=>:host_pests, :as=>:host (etc), I'd like to emulate these four methods:

dog.pests (returns a list of pests associated with this dog)
flea.host (return the host associated with this flea)
cat.pests << Tick.create (creates a HostPest record)
tick.host = Cat.create (creates a HostPest record)

Question 1

I've got a working implementation for the first two methods (pests and host), but want to know if this is the best way (specifically, am I overlooking something in ActiveRecord associations that would help):

class Host < ActiveRecord::Base
  def pests
    HostPest.where(:host_id => self.id, :host_type => self.class).map {|hp| hp.pest}
  end
end
class Pest < ActiveRecord::Base
  def host
    HostPest.where(:pest_id => self.id, :pest_type => self.class).first.host
  end
end

Question 2

I'm stumped on how to implement the << and = methods implied here:

cat.pests << Tick.create  # => HostPest(:host=>cat, :pest=>tick).create
tick.host = Cat.create    # => HostPest(:host=>cat, :pest=>tick).create

Any suggestions?  (And again, can ActiveRecord associations provide any help?)

Body:
You can address your problem by using STI and regular association:

class HostPest < ActiveRecord::Base
  belongs_to :host
  belongs_to :pest
end

Store all the hosts in a table called hosts. Add a string column called type to the table.

class Host < ActiveRecord::Base
  has_many :host_pests
  has_many :pests, :through => :host_pests
end

Inherit the Host class to create new hosts.

class Dog < Host ; end
class Cat < Host ; end

Store all the pests in a table called pests. Add a string column called type to the table.

class Pest < ActiveRecord::Base
  has_one :host_pest
  has_one :host, :through => :host_pest
end

Inherit the Pest class to create new pests.

class Flea < Pest ; end
class Tick < Pest ; end

Now when you can run following commands:

dog.pests (returns a list of pests associated with this dog)
flea.host (return the host associated with this flea)
cat.pests << Tick.create (creates a HostPest record)
tick.host = Cat.create (creates a HostPest record)

Note

Rails supports has_many :through on polymorphic classes. You need to specify the source_type for this to work.

Consider the models for tagging:

class Tag
  has_many :tag_links
end

class TagLink
  belongs_to :tag
  belongs_to :tagger, :polymorphic => true
end

Let's say products and companies can be tagged.

class Product
  has_many :tag_links, :as => :tagger
  has_many :tags, :through => :tag_links
end

class Company
  has_many :tag_links, :as => :tagger
  has_many :tags, :through => :tag_links
end

We can add an association on Tag model to get all the tagged products as follows:

class Tag
  has_many :tag_links
  has_many :products, :through => :tag_links,
                        :source => :tagger, :source_type => 'Product'
end


问:
Edit button jquery function
How do I make my to do list able edit input through the edit button using jquery? It is a to do list and i want users to be able to edit the input
Thanks in advance

To Do List

  Home

    <input type="text" class="note" placeholder="Input new note..">
    <button id="addButton">Add</button>

```

答:
I have done something like this : example

user will be able to edit by double click at the text and an input field will showed up. user can click the edit button once he/she finished edit and the text will be updated.

JS

```<code>$('#addButton').click(function() {
 var task = $(".note").val();
 $(".todo-list").append(`<li>Task: <span class='task'>${task}</span><div
 class="button-center"><button class="deleteButton">Delete</button><button
 class="editButton">Edit</button>   </div></li>`);
 $(".note").val("");
});

$(document).on('click', '.deleteButton', function() {
 $(this).parent().parent().remove();
});

$(document).on('dblclick', '.task', function() {
 var task = $(this).text();
 $(this).text('');
 $(this).append(`<input type="text" value="${task}" />`);
});

$(document).on('click', '.editButton', function() {
 var task = $(this).parents().siblings('span').children('input').val();
 $(this).parents().siblings('span').remove('input');
 $(this).parents().siblings('span').text(task);
});
</code>```

ContentLicense: CC BY-SA 4.0

Title: Edit button jquery function

Body:
I have done something like this : example

user will be able to edit by double click at the text and an input field will showed up. user can click the edit button once he/she finished edit and the text will be updated.

JS

$('#addButton').click(function() {
 var task = $(".note").val();
 $(".todo-list").append(`<li>Task: <span class='task'>${task}</span><div
 class="button-center"><button class="deleteButton">Delete</button><button
 class="editButton">Edit</button>   </div></li>`);
 $(".note").val("");
});

$(document).on('click', '.deleteButton', function() {
 $(this).parent().parent().remove();
});

$(document).on('dblclick', '.task', function() {
 var task = $(this).text();
 $(this).text('');
 $(this).append(`<input type="text" value="${task}" />`);
});

$(document).on('click', '.editButton', function() {
 var task = $(this).parents().siblings('span').children('input').val();
 $(this).parents().siblings('span').remove('input');
 $(this).parents().siblings('span').text(task);
});


问:
Can't download Android Plugin component: android-plugin-resources: Check logs for details
I used to develop android apps using Intellij in the past but ever since i got my new laptop i am completely unable to make any android apps.

At first i had issues with the java version i had installed (17, android seems to be incompatible?) where i was unable to even build or import a project, which i solved by only installing java version 11 (which currently still is the only installed version).

I can build and import projects just fine but whenever i try to launch it on my S8+ running android 9 (same thing when i use android 10 or higher using and avd), it gives me the following error: Can't download Android Plugin component: android-plugin-resources: Check logs for details and it refuses to install on my phone.

I have removed and installed a different android sdk multiple times on my pc (currently i have api 31 installed), but the issue persists. Same thing for projects i worke on in the past, i only imported the project that used to work completely fine in the past, and the error appears.

答:
export logs detail, it indicate this

```<code> WARN - oad.AndroidComponentDownloader - Can't download Android Plugin component: android-plugin-resources
java.io.IOException: Failed to download 'https://cache-redirector.jetbrains.com/intellij-dependencies/org/jetbrains/intellij/deps/android/tools/base/android-plugin-resources/27.3.0.0/android-plugin-resources-27.3.0.0.zip':
Unsupported or unrecognized SSL message
</code>```

so download this zip file and import it in your ide

Body:
export logs detail, it indicate this

 WARN - oad.AndroidComponentDownloader - Can't download Android Plugin component: android-plugin-resources
java.io.IOException: Failed to download 'https://cache-redirector.jetbrains.com/intellij-dependencies/org/jetbrains/intellij/deps/android/tools/base/android-plugin-resources/27.3.0.0/android-plugin-resources-27.3.0.0.zip':
Unsupported or unrecognized SSL message

so download this zip file and import it in your ide


问:
Convert month, day in string to date in Python
I have 2 columns as month and day in my dataframe which are of the datatypes objects. I want to sort those in ascending order (Jan, Feb, Mar) but in order to do that, I need to convert them to date format. I tried using the following code, and some more but nothing seems to work.

```<code>ff['month'] = dt.datetime.strptime(ff['month'],format='%b')

and

ff['month'] = pd.to_datetime(ff['month'], format="%b")
</code>```

Data Frame

Any help would be appreciated. Thank you

答:
This works to convert Month Names to Integers:

```<code>import datetime as dt

ff['month'] = [dt.datetime.strptime(m, "%b").month for m in ff['month']]
</code>```

(Basically, you're just passing strings one by one to the first function you mentioned, to make it work.)
You can then manipulate (e.g. sort) them.

Working with dataframe:

```<code>ff['month'] = ff['month'].apply(lambda x: dt.datetime.strptime(x, "%b"))

ff = ff.sort_values(by=['month'])
ff['month'] = ff['month'].apply(lambda x: x.strftime("%b"))
</code>```

Body:
I have 2 columns as month and day in my dataframe which are of the datatypes objects. I want to sort those in ascending order (Jan, Feb, Mar) but in order to do that, I need to convert them to date format. I tried using the following code, and some more but nothing seems to work.

ff['month'] = dt.datetime.strptime(ff['month'],format='%b')

and

ff['month'] = pd.to_datetime(ff['month'], format="%b")

Data Frame

Any help would be appreciated. Thank you

Body:
This works to convert Month Names to Integers:

import datetime as dt

ff['month'] = [dt.datetime.strptime(m, "%b").month for m in ff['month']]

(Basically, you're just passing strings one by one to the first function you mentioned, to make it work.)
You can then manipulate (e.g. sort) them.

Working with dataframe:

ff['month'] = ff['month'].apply(lambda x: dt.datetime.strptime(x, "%b"))

ff = ff.sort_values(by=['month'])
ff['month'] = ff['month'].apply(lambda x: x.strftime("%b"))


问:
Can I mix Python dataframe positional index and column name?
Can I get an entry in dataframe using negative/positional index and column name? For example,</p>
```<code>import pandas as pd
df = pd.DataFrame({'a':[0,1,2], 'b':[3,4,5]})
# df is:
#    a  b
# 0  0  3
# 1  1  4
# 2  2  5
df.iloc[-1]['a']  # got 2
df['a'].iloc[-1]  # got 2
df.loc[1,'a']     # got 1
df.loc[-1,'a']    # got KeyError: -1
</code>```

答:
No, use df.columns and get_loc, to convert column header label to index location:

```<code>df.iloc[-1, df.columns.get_loc('a')]
</code>```

Output:

```<code>2
</code>```

Body:
Can I get an entry in dataframe using negative/positional index and column name? For example,

import pandas as pd
df = pd.DataFrame({'a':[0,1,2], 'b':[3,4,5]})
# df is:
#    a  b
# 0  0  3
# 1  1  4
# 2  2  5
df.iloc[-1]['a']  # got 2
df['a'].iloc[-1]  # got 2
df.loc[1,'a']     # got 1
df.loc[-1,'a']    # got KeyError: -1

Body:
No, use df.columns and get_loc, to convert column header label to index location:

df.iloc[-1, df.columns.get_loc('a')]

Output:

2


问:
Error when importing cv2 on anaconda prompt but it is working on jupyter notebook
I am importing libraries that I installed using pip install to Jupyter Notebook using the anaconda distribution, which is working. Next, I am trying to import the same libraries in the anaconda command prompt and running it. I am getting this error message:

ModuleNotFoundError: No module named 'cv2'

答:
Two options to install cv2 with the latest conda & python3:

Open the Anaconda Prompt and switch to your environment:

$ conda activate myenv

Then install opencv from the menpo channel:

$ conda install -c menpo opencv

Open the Anaconda Prompt with admin permission and make sure you're in the base environment:
$ conda activate base

Then install opencv from the menpo channel:

$ conda install -c menpo opencv

Reconnect your notebook to the kernel to import cv2.


问:
How can I apply reinforcement learning to continuous action spaces?
I'm trying to get an agent to learn the mouse movements necessary to best perform some task in a reinforcement learning setting (i.e. the reward signal is the only feedback for learning).

I'm hoping to use the Q-learning technique, but while I've found a way to extend this method to continuous state spaces, I can't seem to figure out how to accommodate a problem with a continuous action space.

I could just force all mouse movement to be of a certain magnitude and in only a certain number of different directions, but any reasonable way of making the actions discrete would yield a huge action space. Since standard Q-learning requires the agent to evaluate all possible actions, such an approximation doesn't solve the problem in any practical sense.

答: For what you're doing I don't believe you need to work in continuous action spaces.  Although the physical mouse moves in a continuous space, internally the cursor only moves in discrete steps (usually at pixel levels), so getting any precision above this threshold seems like it won't have any effect on your agent's performance.  The state space is still quite large, but it is finite and discrete.</p>


问:
python Find if a JSON file object contains a specific value
I have a code that finds a fixed value，But i need a code to check if a JSON file key contains a specific value, how should i modify it，I am a newbie and I am learning it

my code

```<code>import json

with open ('G:\\1.json', 'w', encoding='utf-8') as out:
    with open('G:\\1.json', encoding='utf-8') as j:
        for line in j:
            if (d := json.loads(line))['_source']['sex'] == 'female':
                print(json.dumps(d), file=out)

</code>```

JSON file

```<code>
{"person":{"name":"Silva","sex":"female","age":21}}
{"person":{"name":"LANA","sex":"male","age":28}}
{"person":{"name":"Oliveira","sex":"female","age":35}}
{"person":{"name":"KENN","sex":"male","age":32}}

</code>```

I want the output，"age" contains "2"

```<code>{"person":{"name":"Silva","sex":"female","age":21}}
{"person":{"name":"LANA","sex":"male","age":28}}
{"person":{"name":"KENN","sex":"male","age":32}}

</code>```

答:
If you want to check if a number contains a digit, convert it to a string.</p>
```<code>d = json.loads(line)
age_string = str(d['_source']['age'])
if "2" in age_string:
    print(json.dumps(d), file=out)
</code>```

Body:
I have a code that finds a fixed value，But i need a code to check if a JSON file key contains a specific value, how should i modify it，I am a newbie and I am learning it

my code

import json

with open ('G:\\1.json', 'w', encoding='utf-8') as out:
    with open('G:\\1.json', encoding='utf-8') as j:
        for line in j:
            if (d := json.loads(line))['_source']['sex'] == 'female':
                print(json.dumps(d), file=out)

JSON file

{"person":{"name":"Silva","sex":"female","age":21}}
{"person":{"name":"LANA","sex":"male","age":28}}
{"person":{"name":"Oliveira","sex":"female","age":35}}
{"person":{"name":"KENN","sex":"male","age":32}}

I want the output，"age" contains "2"

{"person":{"name":"Silva","sex":"female","age":21}}
{"person":{"name":"LANA","sex":"male","age":28}}
{"person":{"name":"KENN","sex":"male","age":32}}

Body:
If you want to check if a number contains a digit, convert it to a string.

d = json.loads(line)
age_string = str(d['_source']['age'])
if "2" in age_string:
    print(json.dumps(d), file=out)


问:
spec.ts is missing from the TypeScript compilation. Please make sure it is in your tsconfig via the 'files' or 'include' property
I got following error when running ng test or
ng test --include src/folder/component-name.component.spec.ts

Error Message

Error: Module build failed (from ./node_modules/@ngtools/webpack/src/ivy/index.js):
Error: component-file.component.spec.ts is missing from the TypeScript compilation. Please make sure it is in your tsconfig via the 'files' or 'include' property.
at /node_modules/@ngtools/webpack/src/ivy/loader.js:60:26
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at runNextTicks (node:internal/process/task_queues:65:3)
at processImmediate (node:internal/timers:437:9)

tsconfig.spec.json

```<code>{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/spec",
    "baseUrl": "./",
    "module": "commonjs",
    "target": "es5",
    "types": [
      "jasmine",
      "node"
    ]
  },
  "files": [
    "test.ts",
    "polyfills.ts"
  ],
  "include": [
    "**/*.spec.ts",
    "**/*.d.ts"
  ]
}
</code>```

tsconfig.app.json

```<code>{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/app",
    "baseUrl": "./",
    "module": "esnext",
    "types": [
      "node"
    ]
  },
  "exclude": [
    "test.ts",
    "**/*.spec.ts"
  ],
  "files": [
    "main.ts",
    "polyfills.ts"
  ]
}
</code>```

tsconfig.json

```<code>{
  "compileOnSave": false,
  "compilerOptions": {
    "importHelpers": true,
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "experimentalDecorators": true,
    "target": "es6",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2015",
      "es7",
      "dom"
    ],
    "module": "esnext",
    "allowSyntheticDefaultImports": true,
    "skipLibCheck": true,
  },
  "include": [
    "src/**/*",
  "exclude": [
    "node_modules",
    "**/*.spec.ts"
  ]
}
</code>```

I guess this error, the test-component used lazy-module..,

答:
You're excluding any spec.ts files from compilation. Remove this line from the exclude arrays.

"**/*.spec.ts"
```

Body:
I got following error when running ng test or
ng test --include src/folder/component-name.component.spec.ts

Error Message

Error: Module build failed (from ./node_modules/@ngtools/webpack/src/ivy/index.js):
Error: component-file.component.spec.ts is missing from the TypeScript compilation. Please make sure it is in your tsconfig via the 'files' or 'include' property.
at /node_modules/@ngtools/webpack/src/ivy/loader.js:60:26
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at runNextTicks (node:internal/process/task_queues:65:3)
at processImmediate (node:internal/timers:437:9)

tsconfig.spec.json

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/spec",
    "baseUrl": "./",
    "module": "commonjs",
    "target": "es5",
    "types": [
      "jasmine",
      "node"
    ]
  },
  "files": [
    "test.ts",
    "polyfills.ts"
  ],
  "include": [
    "**/*.spec.ts",
    "**/*.d.ts"
  ]
}

tsconfig.app.json

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/app",
    "baseUrl": "./",
    "module": "esnext",
    "types": [
      "node"
    ]
  },
  "exclude": [
    "test.ts",
    "**/*.spec.ts"
  ],
  "files": [
    "main.ts",
    "polyfills.ts"
  ]
}

tsconfig.json

{
  "compileOnSave": false,
  "compilerOptions": {
    "importHelpers": true,
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "experimentalDecorators": true,
    "target": "es6",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2015",
      "es7",
      "dom"
    ],
    "module": "esnext",
    "allowSyntheticDefaultImports": true,
    "skipLibCheck": true,
  },
  "include": [
    "src/**/*",
  "exclude": [
    "node_modules",
    "**/*.spec.ts"
  ]
}

I guess this error, the test-component used lazy-module..,


问:
laravel 5.5 HTTP ERROR 500 unable to handle this request
My old Project use Laravel 5.4.17 It can work in server normally.But new Project use Laravel 5.5.4 It can't work when route in root/public " mydomain.com/root/public is currently unable to handle this request.
HTTP ERROR 500". Is it a problem with the version of php? Because current php version is 5.6.23. Laravel 5.5 require php 7.0? Do you think I'm right?</p>

答: I faced this problem too many times, the solution was to run #composer install and/or #composer update to update the composer dependencies packages, or you might even lost the .htaccess file during moving/copying the files in the live server


问:
Function to check for NULL and concatenating the strings
I have a SQL statement that concatenates First Name and Last Name of the person. I use the following SQL statement.

```<code>ISNULL(FullName.FirstName, '') + ' ' + ISNULL(FullName.LastName, '')
</code>```

What I need is to change this to add the FirstName and LastName only if they are not both NULL. If one of them is not NULL, use that value.

Examples:

FirstName and LastName are NULL -> NULL

FirstName is John and LastName is NULL -> John

FirstName is NULL and LastName is Doe -> Doe

-> indicates the result

答:
You can use simple case statement to solve this:

```<code>    create table emp (emp_id int4, fname varchar(10), lname varchar(10));

    insert into emp (emp_id) values(1);
    insert into emp (emp_id,fname) values(2, 'John');
    insert into emp (emp_id,lname) values(3, 'Doe');
    insert into emp (emp_id,fname,lname) values(4, 'John', 'Doe');

    select emp_id,fname, lname,
    case
        WHEN FNAME is not null and LNAME is not null then
            FNAME||' '||LNAME
        WHEN FNAME is not null and LNAME is NULL then
            FNAME
        WHEN FNAME is null and LNAME is not NULL then
            LNAME
        else null
        end as FULL_NAME
    from emp;
</code>```

Body:
I have a SQL statement that concatenates First Name and Last Name of the person. I use the following SQL statement.

ISNULL(FullName.FirstName, '') + ' ' + ISNULL(FullName.LastName, '')

What I need is to change this to add the FirstName and LastName only if they are not both NULL. If one of them is not NULL, use that value.

Examples:

FirstName and LastName are NULL -> NULL

FirstName is John and LastName is NULL -> John

FirstName is NULL and LastName is Doe -> Doe

-> indicates the result

Body:
You can use simple case statement to solve this:

    create table emp (emp_id int4, fname varchar(10), lname varchar(10));

    insert into emp (emp_id) values(1);
    insert into emp (emp_id,fname) values(2, 'John');
    insert into emp (emp_id,lname) values(3, 'Doe');
    insert into emp (emp_id,fname,lname) values(4, 'John', 'Doe');

    select emp_id,fname, lname,
    case
        WHEN FNAME is not null and LNAME is not null then
            FNAME||' '||LNAME
        WHEN FNAME is not null and LNAME is NULL then
            FNAME
        WHEN FNAME is null and LNAME is not NULL then
            LNAME
        else null
        end as FULL_NAME
    from emp;


问:
Generate SHA-1 for Flutter/React-Native/Android-Native app
I'm trying to generate a SHA-1 for a Flutter app, for Android studio to support Google Sign in, but I don't know how to do that, I saw some posts that indicate to run a command, but there I need a jks file I guess, and flutter doesn't create that.

Could someone help me?

答:
To generate SHA-1 for a Flutter :

1. Locate your android directory inside  the console

```<code>E:\<appname>\android>
</code>```

2. After locating to the android folder  run this command

```<code>./gradlew signingReport
</code>```

If this won't work and opens a daemon terminal

1. Type  signingReport in  daemon terminal

```<code>daemon> signingReport
</code>```

This would be taking a bit long time to generate your first SHA-1  as it
would be checking for all the firebase dependencies and after that
over it generate the SHA-1.

Body:
To generate SHA-1 for a Flutter :

1. Locate your android directory inside  the console

E:\<appname>\android>

2. After locating to the android folder  run this command

./gradlew signingReport

If this won't work and opens a daemon terminal

1. Type  signingReport in  daemon terminal

daemon> signingReport

This would be taking a bit long time to generate your first SHA-1  as it
would be checking for all the firebase dependencies and after that
over it generate the SHA-1.


问:
Google Cloud Composer | Airflow - Specifying or closing maintenance windows
I'm using Airflow with Cloud Composer. I have a Dag scheduled to work every hour. However, I read something like this in the composer documentation: "Maintenance operations might impact the execution of your DAGs and Airflow tasks"

But the cron job I created should run for every hour. I don't want any downtime due to maintenance windows.
I'm worried about any problems with the selected maintenance windows. Can you give me information about this? Do I have an option to close the maintenance window?

Thanks in advance.

答:
As you have mentioned, running DAGs on the maintenance window might cause scheduling or execution issues. This was also mentioned in Cloud Composer Troubleshooting Scheduler issues.

You can define specific maintenance windows for your environment.
During these time periods, maintenance events for Cloud SQL and GKE
take place.

Avoid scheduling DAG runs during maintenance windows because this
might cause scheduling or execution issues.

Also removing the maintenance window won't be considered as a feature moving forward as per Cloud Composer Issue Tracker.

Information from the Engineering team is that this feature is not in
the road map. Hence, We're not going to have this feature in the
future to remove the maintenance window once it's applied to the
composer environment.

Reason: If Environment don't have any maintenance windows then
maintenance operations are happening at random times and having
maintenance window allows to have maintenance operations in
predictable slots.

Unfortunately your only option is to deal with the scheduling or execution issues if ever you encounter one. Since you have mentioned that your DAG runs every hour.


问:
How to load old Microsoft Office XML file (Excel) using Java
I'm not able to load an Excel file in the older Office XML format (think Office 2002 or 2003 version) into Java.  I tried JXL and Apache's POI (version 3.7).  POI doesn't work since it appears to want the newer Office .xlsx format.

Here's an example of the older Office XML format.

One can generate a similar XML file from MS Excel 2010 by saving the workbook as the format "XML Spreadsheet 2003"?

Are there any open-source Java libraries that will load the XMLSS format?  Otherwise I have no choice but to write a custom parser: read the XML file then interpret the cell tags to build out the cell matrix.  In this XML format, any rows with empty cell values are skipped, the next cell with data positioned with an index attribute that acts like an offset in the columns, I assume to save space in the XML file.

答: The answer today was to ask the vendor to change their Excel file format to an Excel binary rather than the old Office XML. Doing so allowed me to use Apache POI 3.7 to read the file with no issues.  I appreciate the answers, as I had no idea there was no direct support in the Java-based open source libraries for this old Office XML format.  Now I know next time to check earlier to see what format the Excel files are in before committing to a timeline.</p>


问:
How do I match two ids against the same value (SQL)
I have a SQL question.

Say I have three tables:

Table 1: Artist

```<code>id bandid name
1  1      Paul McCartney
2  1      Ringo Starr
3  1      John Lennon
4  1      George Harrison
5  2      Mick Jagger
6  2      Keith Richards
7  2      Charlie Watts
8  2      Ronnie Wood
9  3      Travis Barker
10 3      Tom Delonge
11 3      Mark Hoppus
</code>```

Table 2: Band

```<code>bandid bandname
1      the beatles
2      rolling stones
3      blink 182
</code>```

Table 3: Artist on Album

```<code>albumid artistid
1       1
1       2
1       3
1       4
2       1
2       2
2       3
2       4
3       5
3       6
3       7
</code>```

I'm seeking to count the number of albums two artists have worked together on, listing artist #1 and artist #2 names, the band they are both in, and the number of albums between them, while using an subquery. Another note: listing artist #1 against artist #2 is not a duplicate to listing artist #2 against artist #1.

答:
A self join is one approach here:

SELECT a1.name, a2.name, COUNT(*) AS num_shared_albums
FROM ArtistOnAlbum al1
INNER JOIN ArtistOnAlbum al2
    ON al1.albumid = al2.albumid AND
       al1.artistid < al2.artistid
INNER JOIN Artist a1
    ON al1.artistid = a1.id
INNER JOIN Artist a2
    ON al2.artistid = a2.id
GROUP BY
    a1.id, a2.id;
```

Demo

Body:
I have a SQL question.

Say I have three tables:

Table 1: Artist

id bandid name
1  1      Paul McCartney
2  1      Ringo Starr
3  1      John Lennon
4  1      George Harrison
5  2      Mick Jagger
6  2      Keith Richards
7  2      Charlie Watts
8  2      Ronnie Wood
9  3      Travis Barker
10 3      Tom Delonge
11 3      Mark Hoppus

Table 2: Band

bandid bandname
1      the beatles
2      rolling stones
3      blink 182

Table 3: Artist on Album

albumid artistid
1       1
1       2
1       3
1       4
2       1
2       2
2       3
2       4
3       5
3       6
3       7

I'm seeking to count the number of albums two artists have worked together on, listing artist #1 and artist #2 names, the band they are both in, and the number of albums between them, while using an subquery. Another note: listing artist #1 against artist #2 is not a duplicate to listing artist #2 against artist #1.

Body:
A self join is one approach here:

SELECT a1.name, a2.name, COUNT(*) AS num_shared_albums
FROM ArtistOnAlbum al1
INNER JOIN ArtistOnAlbum al2
    ON al1.albumid = al2.albumid AND
       al1.artistid < al2.artistid
INNER JOIN Artist a1
    ON al1.artistid = a1.id
INNER JOIN Artist a2
    ON al2.artistid = a2.id
GROUP BY
    a1.id, a2.id;

Demo


问:
Vuejs: CSS is loaded in the head instead of the shadow-root
I'm trying to use a vue-tel-input within a Vue Web Component. However, the vue-tel-input CSS is not loaded by the the web component as expected.

The CSS that is loaded in the head instead of the shadow-root.** I'm not sure how to load the css in the shadow-root.

Steps to reproduce:

Here you can see a simple Vue.js App using a vue-tel-input field. By building the web component (npm run build-wc) and by opening the demo.html in the dist folder, you can see the vue-tel-input field not rendering correctly.

See picture here

答:
If you are using npm run build-wc command to compile your Vue component into a web component then you would also need to keep the CSS also part of the same file.

So in your code add import 'vue-tel-input/dist/vue-tel-input.css'; as well or keep in as part of  tag in your single file component. in that way the chunked CSS will be part of shadow root.


问:
ipywidgets button onclick event is not raising the onclick method
```<code>import ipywidgets as widgets

button = widgets.Button(description="Click Me!")
output = widgets.Output()

display(button, output)

def on_button_clicked():
    print("button clicked")

button.on_click(on_button_clicked)
</code>```

The button shows up.. but when I click on the button, I expect to see the message "button clicked" to show up.  But that's not happening.

Is there something I'm missing here?

I am using vscode to run my jupyter notebook.

答:
You need to pass the button b in the definition of your on_button_clicked function. See examples in the doc here and code below:

import ipywidgets as widgets

button = widgets.Button(description="Click Me!")
output = widgets.Output()

display(button, output)

def on_button_clicked(b):
  with output:
    print("button clicked")

button.on_click(on_button_clicked)
```

And the output gives:

Body:
import ipywidgets as widgets

button = widgets.Button(description="Click Me!")
output = widgets.Output()

display(button, output)

def on_button_clicked():
    print("button clicked")

button.on_click(on_button_clicked)

The button shows up.. but when I click on the button, I expect to see the message "button clicked" to show up.  But that's not happening.

Is there something I'm missing here?

I am using vscode to run my jupyter notebook.

Body:
You need to pass the button b in the definition of your on_button_clicked function. See examples in the doc here and code below:

import ipywidgets as widgets

button = widgets.Button(description="Click Me!")
output = widgets.Output()

display(button, output)

def on_button_clicked(b):
  with output:
    print("button clicked")

button.on_click(on_button_clicked)

And the output gives:


问:
Can several JOIN clauses in a MySQL query exponentiate number of rows it has to check?
So I was on tech support with our host provider about slow database response that I'd been experiencing on a crucial search page and after some investigating he told me that the query that I'm using was checking 67,998,176 rows. Now the largest table that appears on this query has at most 116 rows and the rest of them have an average of 25 rows each.

Here's the SQL of my query

```<code> SELECT COUNT( DISTINCT `A`.`id`) AS `total_num_resource_rows`
 FROM `admin_site_resources` AS `A`
 LEFT JOIN `admin_site_organization_resource` AS `B` ON `B`.`res_id`=`A`.`id`
 LEFT JOIN `admin_site_organizations` AS `C` ON `B`.`org_id`=`C`.`id`
 LEFT JOIN `admin_site_resource_res_topic` AS `D` ON `D`.`resource_id`=`A`.`id`
 LEFT JOIN `admin_site_resource_topics` AS `E` ON `E`.`id`=`D`.`res_topic_id`
 LEFT JOIN `admin_site_resource_audience` AS `F` ON `F`.`resource_id`=`A`.`id`
 LEFT JOIN `admin_site_audiences` AS `G` ON `G`.`id`=`F`.`audience_id`
 LEFT JOIN `admin_site_resource_curriculum_topic` AS `H` ON `H`.`resource_id`=`A`.`id`
 LEFT JOIN `admin_site_curriculum_topics` AS `I` ON `I`.`id`=`H`.`curriculum_topic_id`
 LEFT JOIN `admin_site_resource_curriculum_grade` AS `J` ON `J`.`resource_id`=`A`.`id`
 LEFT JOIN `admin_site_curriculum_grades` AS `K` ON `K`.`id`=`J`.`curriculum_grade_id`
 LEFT JOIN `admin_site_resource_curriculum_subject` AS `L` ON `L`.`resource_id`=`A`.`id`
 LEFT JOIN `admin_site_curriculum_subjects` AS `M` ON `M`.`id`=`L`.`curriculum_subject_id`
 LEFT JOIN `admin_site_resource_res_type` AS `N` ON `N`.`resource_id`=`A`.`id`
 LEFT JOIN `admin_site_resource_types` AS `O` ON `O`.`id`=`N`.`res_type_id`
 LEFT JOIN `admin_site_resource_res_area_location` AS `P` ON `P`.`resource_id`=`A`.`id`
 LEFT JOIN `admin_site_resource_area_locations` AS `Q` ON `Q`.`id`=`P`.`res_area_location_id`

 WHERE `A`.`post_status`='approved' AND (
`A`.`resource_name` LIKE '%alpha%'
OR `A`.`aliases` LIKE '%alpha%'
OR `A`.`short_desc` LIKE '%alpha%'
OR `A`.`resource_url` LIKE '%alpha%'
OR `A`.`other_resource_type` LIKE '%alpha%'
OR `C`.`org_name` LIKE '%alpha%'
OR `E`.`topic_label` LIKE '%alpha%'
OR `G`.`audience_label` LIKE '%alpha%'
OR `I`.`topic_label` LIKE '%alpha%'
OR `K`.`grade_label` LIKE '%alpha%'
OR `M`.`subject_label` LIKE '%alpha%'
OR `O`.`type_label` LIKE '%alpha%'
OR `Q`.`area_location_label` LIKE '%alpha%' );
</code>```

Yes, I understand this query is pretty long and ugly but I guess it's a result of all the normalization that had to be done for it. What I can't understand is how a few rows suddenly turned to almost 68 million rows. Are the LEFT JOINS to blame for this?

答:
Depending on how many rows in each table match each join condition, you can have up to 116 rows from the first table, each paired with up to 116 rows from the second table (13456 rows now), each paired with up to 116 rows from the third table (1560896 rows now), each paired with up to 116 rows from the fourth table (181063936 rows now)... do you see where this is going?

You might only have 116 rows in that largest table, but when you take every combination of 16 tables' keys... http://en.wikipedia.org/wiki/Combination

Body:
So I was on tech support with our host provider about slow database response that I'd been experiencing on a crucial search page and after some investigating he told me that the query that I'm using was checking 67,998,176 rows. Now the largest table that appears on this query has at most 116 rows and the rest of them have an average of 25 rows each.

Here's the SQL of my query

 SELECT COUNT( DISTINCT `A`.`id`) AS `total_num_resource_rows`
 FROM `admin_site_resources` AS `A`
 LEFT JOIN `admin_site_organization_resource` AS `B` ON `B`.`res_id`=`A`.`id`
 LEFT JOIN `admin_site_organizations` AS `C` ON `B`.`org_id`=`C`.`id`
 LEFT JOIN `admin_site_resource_res_topic` AS `D` ON `D`.`resource_id`=`A`.`id`
 LEFT JOIN `admin_site_resource_topics` AS `E` ON `E`.`id`=`D`.`res_topic_id`
 LEFT JOIN `admin_site_resource_audience` AS `F` ON `F`.`resource_id`=`A`.`id`
 LEFT JOIN `admin_site_audiences` AS `G` ON `G`.`id`=`F`.`audience_id`
 LEFT JOIN `admin_site_resource_curriculum_topic` AS `H` ON `H`.`resource_id`=`A`.`id`
 LEFT JOIN `admin_site_curriculum_topics` AS `I` ON `I`.`id`=`H`.`curriculum_topic_id`
 LEFT JOIN `admin_site_resource_curriculum_grade` AS `J` ON `J`.`resource_id`=`A`.`id`
 LEFT JOIN `admin_site_curriculum_grades` AS `K` ON `K`.`id`=`J`.`curriculum_grade_id`
 LEFT JOIN `admin_site_resource_curriculum_subject` AS `L` ON `L`.`resource_id`=`A`.`id`
 LEFT JOIN `admin_site_curriculum_subjects` AS `M` ON `M`.`id`=`L`.`curriculum_subject_id`
 LEFT JOIN `admin_site_resource_res_type` AS `N` ON `N`.`resource_id`=`A`.`id`
 LEFT JOIN `admin_site_resource_types` AS `O` ON `O`.`id`=`N`.`res_type_id`
 LEFT JOIN `admin_site_resource_res_area_location` AS `P` ON `P`.`resource_id`=`A`.`id`
 LEFT JOIN `admin_site_resource_area_locations` AS `Q` ON `Q`.`id`=`P`.`res_area_location_id`

 WHERE `A`.`post_status`='approved' AND (
`A`.`resource_name` LIKE '%alpha%'
OR `A`.`aliases` LIKE '%alpha%'
OR `A`.`short_desc` LIKE '%alpha%'
OR `A`.`resource_url` LIKE '%alpha%'
OR `A`.`other_resource_type` LIKE '%alpha%'
OR `C`.`org_name` LIKE '%alpha%'
OR `E`.`topic_label` LIKE '%alpha%'
OR `G`.`audience_label` LIKE '%alpha%'
OR `I`.`topic_label` LIKE '%alpha%'
OR `K`.`grade_label` LIKE '%alpha%'
OR `M`.`subject_label` LIKE '%alpha%'
OR `O`.`type_label` LIKE '%alpha%'
OR `Q`.`area_location_label` LIKE '%alpha%' );

Yes, I understand this query is pretty long and ugly but I guess it's a result of all the normalization that had to be done for it. What I can't understand is how a few rows suddenly turned to almost 68 million rows. Are the LEFT JOINS to blame for this?


问:
Selenium closing right after any request
Is it due to the site himself? If it is the case, how to bypass the problem?

I tried to make the web driver wait, but it didn't help...

This is my code :

```<code>from selenium import webdriver

PATH = '/Users/xxxx/chromedriver'
driver = webdriver.Chrome(PATH)
driver.get('https://haveibeenpwned.com/')
e_mail = driver.find_element_by_id('Account')
e_mail.send_keys('contact@gmail.com')
login_button = driver.find_element_by_id('searchPwnage')
login_button.click()
response = driver.find_element_by_id('pwnCount')
print(response.text)
</code>```

What can I do ?

答:
Try</p>
```<code>from selenium import webdriver
from webdriver_manager.firefox import GeckoDriverManager
driver = webdriver.Firefox(executable_path=GeckoDriverManager().install())
driver.get('https://haveibeenpwned.com/')
e_mail = driver.find_element_by_id('Account')
</code>```

Body:
Is it due to the site himself? If it is the case, how to bypass the problem?

I tried to make the web driver wait, but it didn't help...

This is my code :

from selenium import webdriver

PATH = '/Users/xxxx/chromedriver'
driver = webdriver.Chrome(PATH)
driver.get('https://haveibeenpwned.com/')
e_mail = driver.find_element_by_id('Account')
e_mail.send_keys('contact@gmail.com')
login_button = driver.find_element_by_id('searchPwnage')
login_button.click()
response = driver.find_element_by_id('pwnCount')
print(response.text)

What can I do ?

Body:
Try

from selenium import webdriver
from webdriver_manager.firefox import GeckoDriverManager
driver = webdriver.Firefox(executable_path=GeckoDriverManager().install())
driver.get('https://haveibeenpwned.com/')
e_mail = driver.find_element_by_id('Account')


问:
SetTimeout is confusing me and I need to be able to promisify it
I have 2 separate div elements and I have a function that defines each element and is supposed to only act on the element. so when i call typeField(name,element1) it should type into only element1 and similarly then I call typeField(address,element2) it should type into only element2.. but currently if you check my codepen implementation it's mixing the characters and I am not sure why.

Also after this I need to figure a way out where I can get the name to type in first and then after that's done I need to start the typing of the address. My assumption is I need to promisify the functions and then call them as async/await. Is that the right approach? or am I overthinking this?

So my 2 questions are

What am I doing wrong in my code that's mixing up the contents in elements innerHTML?

Once that's resolved how can I make the first element type first and on completion start the next one

Any help in resolving this would be appreciated.

This is the link to my Codepen

https://codepen.io/alimbolar/pen/Rwjoqbm?editors=1111

const typewriter1 = document.getElementById('typewriter1');
const typewriter2 = document.getElementById('typewriter2');
const name = 'Alim Bolar';
const address = "Some part of the world";
const currentLocation = "Bali, Indonesia";
const profile = "Frontend Development, Backend Development, WordPress Development"
let content = "";
let i = 0;

function typeField(x, element) {
  if (i < x.length) {
    alphabet = x.charAt(i);
    content = content + alphabet;
    element.innerHTML = content;
    i++;
    setTimeout(function() {
      typeField(x, element)
    }, 500);
  }
}
typeField(name, typewriter1);
typeField(address, typewriter2);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header>

  <div>NAME : <span id="typewriter1"></span></div>
  <div>ADDRESS : <span id="typewriter2"></span></div>

</header></code>```

答:
You need to

not have i or content be global, because then it'll be shared by all calls of typeField

have typeField assign to a persistent Promise outside that further calls are chained off of

Consider awaiting a Promise inside a loop, it'll look a lot cleaner than recursion.

const typewriter1 = document.getElementById('typewriter1');
const typewriter2 = document.getElementById('typewriter2');

const name = 'Alim Bolar';
const address = "Some part of the world";
const currentLocation = "Bali, Indonesia";
const profile = "Frontend Development, Backend Development, WordPress Development"

let prom = Promise.resolve();

const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
function typeField(textToInsert, element) {
  prom = prom.then(async () => {
    for (const char of textToInsert) {
      element.textContent += char;
      await delay(500);
    }
  });
}

typeField(name, typewriter1);
typeField(address, typewriter2);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header>
  <div>NAME : <span id="typewriter1"></span></div>
  <div>ADDRESS : <span id="typewriter2"></span></div>
</header></code>```

Body:
I have 2 separate div elements and I have a function that defines each element and is supposed to only act on the element. so when i call typeField(name,element1) it should type into only element1 and similarly then I call typeField(address,element2) it should type into only element2.. but currently if you check my codepen implementation it's mixing the characters and I am not sure why.

Also after this I need to figure a way out where I can get the name to type in first and then after that's done I need to start the typing of the address. My assumption is I need to promisify the functions and then call them as async/await. Is that the right approach? or am I overthinking this?

So my 2 questions are

What am I doing wrong in my code that's mixing up the contents in elements innerHTML?

Once that's resolved how can I make the first element type first and on completion start the next one

Any help in resolving this would be appreciated.

This is the link to my Codepen

https://codepen.io/alimbolar/pen/Rwjoqbm?editors=1111

const typewriter1 = document.getElementById('typewriter1');
const typewriter2 = document.getElementById('typewriter2');
const name = 'Alim Bolar';
const address = "Some part of the world";
const currentLocation = "Bali, Indonesia";
const profile = "Frontend Development, Backend Development, WordPress Development"
let content = "";
let i = 0;

function typeField(x, element) {
  if (i < x.length) {
    alphabet = x.charAt(i);
    content = content + alphabet;
    element.innerHTML = content;
    i++;
    setTimeout(function() {
      typeField(x, element)
    }, 500);
  }
}
typeField(name, typewriter1);
typeField(address, typewriter2);

NAME :

ADDRESS :

Body:
You need to

not have i or content be global, because then it'll be shared by all calls of typeField

have typeField assign to a persistent Promise outside that further calls are chained off of

Consider awaiting a Promise inside a loop, it'll look a lot cleaner than recursion.

const typewriter1 = document.getElementById('typewriter1');
const typewriter2 = document.getElementById('typewriter2');

const name = 'Alim Bolar';
const address = "Some part of the world";
const currentLocation = "Bali, Indonesia";
const profile = "Frontend Development, Backend Development, WordPress Development"

let prom = Promise.resolve();

const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
function typeField(textToInsert, element) {
  prom = prom.then(async () => {
    for (const char of textToInsert) {
      element.textContent += char;
      await delay(500);
    }
  });
}

typeField(name, typewriter1);
typeField(address, typewriter2);

<header>
  <div>NAME : <span id="typewriter1"></span></div>
  <div>ADDRESS : <span id="typewriter2"></span></div>
</header>


问:
TensorFlow ValueError: Input 0 is incompatible with layer model_1: expected shape=(None, 32, 32, 1), found shape=(1, 1, 32, 32)
Please help me get out of this error while building a model for face comparison/similarity check.
I am getting
X_val.shape, y_val.shape, X_train.shape, y_train.shape
(2, 2, 32, 32, 1) (2,) (40, 2, 32, 32, 1) (40,)
which are as expected
still I am getting this error.
I got the code from this link
https://github.com/mrm202/facematch

https://github.com/aleju/face-comparer(python 2.7)

```<code>-----------------------
Loading validation dataset...
-----------------------

-----------------------
Loading training dataset...
-----------------------

-----------------------

Loading image contents from hard drive...
X_val.shape, y_val.shape, X_train.shape, y_train.shape
(2, 2, 32, 32, 1) (2,) (40, 2, 32, 32, 1) (40,)
Creating model...
    Compiling model...
    Training...
    Epoch 0
    Traceback (most recent call last):
      File "train.py", line 563, in <module>
        main()
      File "train.py", line 214, in main
        la_plotter, ia_train, ia_val, X_train, y_train, X_val, y_val)
      File "train.py", line 350, in train_loop
        loss, acc = model.train_on_batch(X_batch, Y_batch)
      File "C:\Python37\lib\site-packages\tensorflow\python\keras\engine\training.py", line 1825, in train_on_batch
        logs = self.train_function(iterator)
      File "C:\Python37\lib\site-packages\tensorflow\python\eager\def_function.py", line 889, in __call__
        result = self._call(*args, **kwds)
      File "C:\Python37\lib\site-packages\tensorflow\python\eager\def_function.py", line 933, in _call
        self._initialize(args, kwds, add_initializers_to=initializers)
      File "C:\Python37\lib\site-packages\tensorflow\python\eager\def_function.py", line 764, in _initialize
        *args, **kwds))
      File "C:\Python37\lib\site-packages\tensorflow\python\eager\function.py", line 3050, in _get_concrete_function_internal_garbage_collected
        graph_function, _ = self._maybe_define_function(args, kwargs)
      File "C:\Python37\lib\site-packages\tensorflow\python\eager\function.py", line 3444, in _maybe_define_function
        graph_function = self._create_graph_function(args, kwargs)
      File "C:\Python37\lib\site-packages\tensorflow\python\eager\function.py", line 3289, in _create_graph_function
        capture_by_value=self._capture_by_value),
      File "C:\Python37\lib\site-packages\tensorflow\python\framework\func_graph.py", line 999, in func_graph_from_py_func
        func_outputs = python_func(*func_args, **func_kwargs)
      File "C:\Python37\lib\site-packages\tensorflow\python\eager\def_function.py", line 672, in wrapped_fn
        out = weak_wrapped_fn().__wrapped__(*args, **kwds)
      File "C:\Python37\lib\site-packages\tensorflow\python\framework\func_graph.py", line 986, in wrapper
        raise e.ag_error_metadata.to_exception(e)
    ValueError: in user code:

    C:\Python37\lib\site-packages\tensorflow\python\keras\engine\training.py:855 train_function  *
        return step_function(self, iterator)
    C:\Python37\lib\site-packages\tensorflow\python\keras\engine\training.py:845 step_function  **
        outputs = model.distribute_strategy.run(run_step, args=(data,))
    C:\Python37\lib\site-packages\tensorflow\python\distribute\distribute_lib.py:1285 run
        return self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs)
    C:\Python37\lib\site-packages\tensorflow\python\distribute\distribute_lib.py:2833 call_for_each_replica
        return self._call_for_each_replica(fn, args, kwargs)
    C:\Python37\lib\site-packages\tensorflow\python\distribute\distribute_lib.py:3608 _call_for_each_replica
        return fn(*args, **kwargs)
    C:\Python37\lib\site-packages\tensorflow\python\keras\engine\training.py:838 run_step  **
        outputs = model.train_step(data)
    C:\Python37\lib\site-packages\tensorflow\python\keras\engine\training.py:795 train_step
        y_pred = self(x, training=True)
    C:\Python37\lib\site-packages\tensorflow\python\keras\engine\base_layer.py:1013 __call__
        input_spec.assert_input_compatibility(self.input_spec, inputs, self.name)
    C:\Python37\lib\site-packages\tensorflow\python\keras\engine\input_spec.py:270 assert_input_compatibility
        ', found shape=' + display_shape(x.shape))

    ValueError: Input 0 is incompatible with layer model_1: expected shape=(None, 32, 32, 1), found shape=(1, 1, 32, 32)
</code>```

答:
I built model using 'channel last' input, also I was giving same type of input 'channel last'...
Problem was with 'train' which was converting 'channel last' into 'channel first' before feeding to model.

I corrected train method.

Body:
Please help me get out of this error while building a model for face comparison/similarity check.
I am getting
X_val.shape, y_val.shape, X_train.shape, y_train.shape
(2, 2, 32, 32, 1) (2,) (40, 2, 32, 32, 1) (40,)
which are as expected
still I am getting this error.
I got the code from this link
https://github.com/mrm202/facematch

https://github.com/aleju/face-comparer(python 2.7)

-----------------------
Loading validation dataset...
-----------------------

-----------------------
Loading training dataset...
-----------------------

-----------------------

Loading image contents from hard drive...
X_val.shape, y_val.shape, X_train.shape, y_train.shape
(2, 2, 32, 32, 1) (2,) (40, 2, 32, 32, 1) (40,)
Creating model...
    Compiling model...
    Training...
    Epoch 0
    Traceback (most recent call last):
      File "train.py", line 563, in <module>
        main()
      File "train.py", line 214, in main
        la_plotter, ia_train, ia_val, X_train, y_train, X_val, y_val)
      File "train.py", line 350, in train_loop
        loss, acc = model.train_on_batch(X_batch, Y_batch)
      File "C:\Python37\lib\site-packages\tensorflow\python\keras\engine\training.py", line 1825, in train_on_batch
        logs = self.train_function(iterator)
      File "C:\Python37\lib\site-packages\tensorflow\python\eager\def_function.py", line 889, in __call__
        result = self._call(*args, **kwds)
      File "C:\Python37\lib\site-packages\tensorflow\python\eager\def_function.py", line 933, in _call
        self._initialize(args, kwds, add_initializers_to=initializers)
      File "C:\Python37\lib\site-packages\tensorflow\python\eager\def_function.py", line 764, in _initialize
        *args, **kwds))
      File "C:\Python37\lib\site-packages\tensorflow\python\eager\function.py", line 3050, in _get_concrete_function_internal_garbage_collected
        graph_function, _ = self._maybe_define_function(args, kwargs)
      File "C:\Python37\lib\site-packages\tensorflow\python\eager\function.py", line 3444, in _maybe_define_function
        graph_function = self._create_graph_function(args, kwargs)
      File "C:\Python37\lib\site-packages\tensorflow\python\eager\function.py", line 3289, in _create_graph_function
        capture_by_value=self._capture_by_value),
      File "C:\Python37\lib\site-packages\tensorflow\python\framework\func_graph.py", line 999, in func_graph_from_py_func
        func_outputs = python_func(*func_args, **func_kwargs)
      File "C:\Python37\lib\site-packages\tensorflow\python\eager\def_function.py", line 672, in wrapped_fn
        out = weak_wrapped_fn().__wrapped__(*args, **kwds)
      File "C:\Python37\lib\site-packages\tensorflow\python\framework\func_graph.py", line 986, in wrapper
        raise e.ag_error_metadata.to_exception(e)
    ValueError: in user code:

    C:\Python37\lib\site-packages\tensorflow\python\keras\engine\training.py:855 train_function  *
        return step_function(self, iterator)
    C:\Python37\lib\site-packages\tensorflow\python\keras\engine\training.py:845 step_function  **
        outputs = model.distribute_strategy.run(run_step, args=(data,))
    C:\Python37\lib\site-packages\tensorflow\python\distribute\distribute_lib.py:1285 run
        return self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs)
    C:\Python37\lib\site-packages\tensorflow\python\distribute\distribute_lib.py:2833 call_for_each_replica
        return self._call_for_each_replica(fn, args, kwargs)
    C:\Python37\lib\site-packages\tensorflow\python\distribute\distribute_lib.py:3608 _call_for_each_replica
        return fn(*args, **kwargs)
    C:\Python37\lib\site-packages\tensorflow\python\keras\engine\training.py:838 run_step  **
        outputs = model.train_step(data)
    C:\Python37\lib\site-packages\tensorflow\python\keras\engine\training.py:795 train_step
        y_pred = self(x, training=True)
    C:\Python37\lib\site-packages\tensorflow\python\keras\engine\base_layer.py:1013 __call__
        input_spec.assert_input_compatibility(self.input_spec, inputs, self.name)
    C:\Python37\lib\site-packages\tensorflow\python\keras\engine\input_spec.py:270 assert_input_compatibility
        ', found shape=' + display_shape(x.shape))

    ValueError: Input 0 is incompatible with layer model_1: expected shape=(None, 32, 32, 1), found shape=(1, 1, 32, 32)


问:
Flutter keyboard not showing in ios
I'm running my app in ios simulator but why is my keyboard not showing all of the sudden when I click on the textfield? It works perfectly fine before I fix my app icon.

Tried deleting the app and re-install it again, but still won't work. When I run the app on android and click on the same textfield, the keyboard is showing.

Here is the code:

```<code>                       TextField(
                          keyboardType: TextInputType.multiline,
                          controller: inputTextController,
                          onChanged: (text) {
                              if (!_isWriting){
                                _isWriting = true;

                                  //update typing status when type messages
                                  var msg = {};
                                  msg["api_key"] = apiKey;
                                  msg["type"] = "status_typing";
                                  msg["id_sender"] = idUser;
                                  msg["id_receiver"] = idReceiver;
                                  msg["room_id"] = conversation!.roomId;
                                  String msgString = json.encode(msg);
                                  homes.channel.sink.add(msgString);

                                setState((){});
                                Future.delayed(Duration(seconds: 2)).whenComplete((){
                                  _isWriting = false;
                                  setState((){});
                                });
                              }
                            },
                          maxLines: null,
                          style: TextStyle(
                            color: Colors.black,
                          ),
                          decoration: InputDecoration(
                              contentPadding: EdgeInsets.only(top: 13, bottom: 13),
                              border: InputBorder.none,
                              hintText: 'Type a message',
                              hintStyle: TextStyle(
                                color: Color(0xff99999B),
                              )
                          ),
                        ),
</code>```

Any solutions?

答:
For show keyboard in simulator follow this command</p>
```<code>cmd + shift + k
</code>```

Title: Flutter keyboard not showing in ios

Body:
I'm running my app in ios simulator but why is my keyboard not showing all of the sudden when I click on the textfield? It works perfectly fine before I fix my app icon.

Tried deleting the app and re-install it again, but still won't work. When I run the app on android and click on the same textfield, the keyboard is showing.

Here is the code:

                       TextField(
                          keyboardType: TextInputType.multiline,
                          controller: inputTextController,
                          onChanged: (text) {
                              if (!_isWriting){
                                _isWriting = true;

                                  //update typing status when type messages
                                  var msg = {};
                                  msg["api_key"] = apiKey;
                                  msg["type"] = "status_typing";
                                  msg["id_sender"] = idUser;
                                  msg["id_receiver"] = idReceiver;
                                  msg["room_id"] = conversation!.roomId;
                                  String msgString = json.encode(msg);
                                  homes.channel.sink.add(msgString);

                                setState((){});
                                Future.delayed(Duration(seconds: 2)).whenComplete((){
                                  _isWriting = false;
                                  setState((){});
                                });
                              }
                            },
                          maxLines: null,
                          style: TextStyle(
                            color: Colors.black,
                          ),
                          decoration: InputDecoration(
                              contentPadding: EdgeInsets.only(top: 13, bottom: 13),
                              border: InputBorder.none,
                              hintText: 'Type a message',
                              hintStyle: TextStyle(
                                color: Color(0xff99999B),
                              )
                          ),
                        ),

Any solutions?

Body:
For show keyboard in simulator follow this command

cmd + shift + k


问:
sweet alert CSS styles not being applied in Vue app
I have installed vue-sweetalert2 in my Vue app (version 2.6). I included the following in the main.js:

```<code>import VueSweetalert2 from 'vue-sweetalert2';

Vue.use(VueSweetalert2);
</code>```

I have a simple button with a click handler:

```<code> <button v-on:click="alertDisplay">Click me</button>

     alertDisplay() {
      this.$swal('Heading', 'this is a Heading', 'OK');
     },
</code>```

This works as expected. When the button is clicked the sweetAlert modal shows but it appears in the very bottom left of the page without any styling. I have looked around but I can't find a clear reason or solution to this issue in the context of a Vue app.

Any ideas are very appreciated!

答:
When you are using vue-sweetalert2, you have to import the css file to get the result that you want.

In your main.js file use the following code line:

import 'sweetalert2/dist/sweetalert2.min.css';
```
<p>Additionally if you want to change the font-family use the following css code:</p>
```.swal2-title {
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif !important;
}
```

I hope it helps you ;)

Body:
I have installed vue-sweetalert2 in my Vue app (version 2.6). I included the following in the main.js:

import VueSweetalert2 from 'vue-sweetalert2';

Vue.use(VueSweetalert2);

I have a simple button with a click handler:

 <button v-on:click="alertDisplay">Click me</button>

     alertDisplay() {
      this.$swal('Heading', 'this is a Heading', 'OK');
     },

This works as expected. When the button is clicked the sweetAlert modal shows but it appears in the very bottom left of the page without any styling. I have looked around but I can't find a clear reason or solution to this issue in the context of a Vue app.

Any ideas are very appreciated!

Body:
When you are using vue-sweetalert2, you have to import the css file to get the result that you want.

In your main.js file use the following code line:

import 'sweetalert2/dist/sweetalert2.min.css';

Additionally if you want to change the font-family use the following css code:

.swal2-title {
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif !important;
}

I hope it helps you ;)


问:
How to add class to HTML element on marker click with Leaflet JS
So, I'm trying to show a modal when a marker is clicked as a part of my Leaflet app. I already have some of the click functionality set on my marker layer, but I seem to be failing in triggering the necessary class being added to the modal element.

Currently I have a modal div with the following HTML outside of my map div.:

```<code><div class="modal" id="infoBox">
<div class="modal-dialog">
<header class="modal-header"><button class="close-modal" aria-label="close modal" data-close> X</button></header>
<p>
<section class="modal-content">
Address: <span id="street"></span><br/>
Neighborhood: <span id="suburb"></span><br/>
City: <span id="city"></span><br/>
Piece Type: <span id="type"></span><br/>
Description: <span id="desc"></span><br/>
</p>
</section>
<footer class="modal-footer"></footer>
</div>
</div>
</code>```

I am trying to add the class with the following function:

```<code>function zoomToFeature(e) {
  var latLngs = [e.target.getLatLng()];
  var markerBounds = L.latLngBounds(latLngs);
  var street = e.target.feature.properties.str_addr;
  var city = e.target.feature.properties.city;
  var desc = e.target.feature.properties.desc;
  document.getElementById('street').textContent = street;
  document.getElementById('city').textContent = city;
  document.getElementById('desc').textContent = desc;
  mymap.fitBounds(markerBounds);
  mymap.fitBounds(e.target.getBounds());
  document.getElementById('infoBox').classList.add('is-visible');
}
</code>```

Which I add the click listener on the layer with the onEachFeature function like so:

```<code>function onEachFeature(feature, layer){
    layer.on({
        mouseover: highlightFeature,
        mouseout: resetHighlight,
        click: zoomToFeature,
    });
}
</code>```

When I manually add the .is-visible class the element I get the expected behaviour, but clicking the marker layer doesn't add the class. I'm basically trying to implement this Tutsplus Tutorial with some of the functionality in the Leaflet Chrolopleth tutorial. The click functionality works as far as pulling the feature info and zooming to the marker, but as above the modal stays hidden.

Running the classListAdd in a stand alone function in the dev console adds the class like so class="modal is-visible" but it doesn't trigger the functionality. As above manually changing the class to modal.is-visible does work, but I assume that's because it's an exact match for the css and it's not being re-interpreted.

Stripped down demo version can be seen here

答:
The culprit is the line: e.target.getBounds()

When you click on a (Circle)Marker, e.target is that Marker. But Point features do not have such getBounds() method (since they represent a single point, not an area).

So your script fails with an error like:

Uncaught TypeError: e.target.getBounds is not a function

...and the rest of the event listener is not executed, in particular the following line where you show your modal (document.getElementById('infoBox').classList.add('is-visible'))

Since you already set the view around that Marker just before (mymap.fitBounds(markerBounds)), there is no need to that repeated call (maybe just a leftover of previous attempts?)

Removing that line restores your modal behaviour.

Fixed Plunkr: https://plnkr.co/edit/DfCKrJaNzM48dzuZ

Note: your Plunkr was not working because you forgot the call to your initMap() function.

Body:
So, I'm trying to show a modal when a marker is clicked as a part of my Leaflet app. I already have some of the click functionality set on my marker layer, but I seem to be failing in triggering the necessary class being added to the modal element.

Currently I have a modal div with the following HTML outside of my map div.:

<button class="close-modal" aria-label="close modal" data-close> X</button>

Address:

Neighborhood:

City:

Piece Type:

Description:

I am trying to add the class with the following function:

function zoomToFeature(e) {
  var latLngs = [e.target.getLatLng()];
  var markerBounds = L.latLngBounds(latLngs);
  var street = e.target.feature.properties.str_addr;
  var city = e.target.feature.properties.city;
  var desc = e.target.feature.properties.desc;
  document.getElementById('street').textContent = street;
  document.getElementById('city').textContent = city;
  document.getElementById('desc').textContent = desc;
  mymap.fitBounds(markerBounds);
  mymap.fitBounds(e.target.getBounds());
  document.getElementById('infoBox').classList.add('is-visible');
}

Which I add the click listener on the layer with the onEachFeature function like so:

function onEachFeature(feature, layer){
    layer.on({
        mouseover: highlightFeature,
        mouseout: resetHighlight,
        click: zoomToFeature,
    });
}

When I manually add the .is-visible class the element I get the expected behaviour, but clicking the marker layer doesn't add the class. I'm basically trying to implement this Tutsplus Tutorial with some of the functionality in the Leaflet Chrolopleth tutorial. The click functionality works as far as pulling the feature info and zooming to the marker, but as above the modal stays hidden.

Running the classListAdd in a stand alone function in the dev console adds the class like so class="modal is-visible" but it doesn't trigger the functionality. As above manually changing the class to modal.is-visible does work, but I assume that's because it's an exact match for the css and it's not being re-interpreted.

Stripped down demo version can be seen here


问:
Yup: deep validation in array of objects
I have a data structure like this:

```<code>{
  "subject": "Ah yeah",
  "description": "Jeg siger...",
  "daysOfWeek": [
    {
      "dayOfWeek": "MONDAY",
      "checked": false
    },
    {
      "dayOfWeek": "TUESDAY",
      "checked": false
    },
    {
      "dayOfWeek": "WEDNESDAY",
      "checked": true
    },
    {
      "dayOfWeek": "THURSDAY",
      "checked": false
    },
    {
      "dayOfWeek": "FRIDAY",
      "checked": false
    },
    {
      "dayOfWeek": "SATURDAY",
      "checked": true
    },
    {
      "dayOfWeek": "SUNDAY",
      "checked": true
    }
  ],
  "uuid": "da8f56a2-625f-400d-800d-c975bead0cff",
  "taskSchedules": [],
  "isInitial": false,
  "hasChanged": false
}
</code>```

In daysOfWeek I want to ensure that at least one of the items has checked: true.

This is my validation schema so far (but not working):

```<code>const taskValidationSchema = Yup.object().shape({
  subject: Yup.string().required('Required'),
  description: Yup.string(),
  daysOfWeek: Yup.array()
    .of(
      Yup.object().shape({
        dayOfWeek: Yup.string(),
        checked: Yup.boolean(),
      })
    )
    .required('Required'),
  taskSchedules: Yup.array(),
})
</code>```

Is it possible to validate the values of daysOfWeek ensuring that at least one of them has checked: true?

答:
Base on @olefrank's answer. This code work with me.

const validationSchema = Yup.object().shape({
  subject: Yup.string().required(i18n.t('required-field')),
  description: Yup.string(),
  daysOfWeek: Yup.array()
    .of(
      Yup.object().shape({
        dayOfWeek: Yup.string(),
        checked: Yup.boolean(),
      })
    )
    .compact((v) => !v.checked)
    .min(1, i18n.t('required-field')), // <– `.min(1)` instead of `.required()`
  taskSchedules: Yup.array(),
});
```

Body:
I have a data structure like this:

{
  "subject": "Ah yeah",
  "description": "Jeg siger...",
  "daysOfWeek": [
    {
      "dayOfWeek": "MONDAY",
      "checked": false
    },
    {
      "dayOfWeek": "TUESDAY",
      "checked": false
    },
    {
      "dayOfWeek": "WEDNESDAY",
      "checked": true
    },
    {
      "dayOfWeek": "THURSDAY",
      "checked": false
    },
    {
      "dayOfWeek": "FRIDAY",
      "checked": false
    },
    {
      "dayOfWeek": "SATURDAY",
      "checked": true
    },
    {
      "dayOfWeek": "SUNDAY",
      "checked": true
    }
  ],
  "uuid": "da8f56a2-625f-400d-800d-c975bead0cff",
  "taskSchedules": [],
  "isInitial": false,
  "hasChanged": false
}

In daysOfWeek I want to ensure that at least one of the items has checked: true.

This is my validation schema so far (but not working):

const taskValidationSchema = Yup.object().shape({
  subject: Yup.string().required('Required'),
  description: Yup.string(),
  daysOfWeek: Yup.array()
    .of(
      Yup.object().shape({
        dayOfWeek: Yup.string(),
        checked: Yup.boolean(),
      })
    )
    .required('Required'),
  taskSchedules: Yup.array(),
})

Is it possible to validate the values of daysOfWeek ensuring that at least one of them has checked: true?


问:
I'm not sure how to delete a user using MongoDB
I'm trying to be able to delete a user if they choose to delete their account. I'm not sure how it's properly done. Here's the code for the delete function. I've looked at other StackOverflow solutions but I haven't been able to grasp the concept just yet. can anyone help?

```<code>const { validationResult } = require('express-validator')
const User = require('../modelSchema/User')
const mongo = require('mongodb')

const signUp = (req, res) => {

    const errors = validationResult(req)
    if(!errors.isEmpty()) return res.status(400).json({ errors: errors.array()})

    //new instance of user
   const user = new User({
    name: req.body.name,
    email: req.body.email,
    password: req.body.password })

    //save the user
  user.save()
  .then(data => {
      res.json(data)
      res.send('User added successfully!')
      console.log(data)
  })
  .catch(err => {
      res.status(400).json(err)
  })

}

const deleteUser = (req, res) => {

    let id = req.params.id;
    User.get().createCollection('user', function ( col) {
     col.deleteOne({_id: new mongo.ObjectId(id)});
    });
    res.json({ success: id })
    res.send('User Deleted Successfully!')
    .catch(err => {
        res.status(400).json(err)
    })
}

module.exports = { signUp, deleteUser }
</code>```

here are the routes that I'm using

```<code>const express = require('express');
const { check } = require('express-validator')
const { signUp, deleteUser } = require('../controllers/users');

const router = express.Router();

router.post('/signup', [
    check('name', 'Please Enter your Name').not().isEmpty(),
    check('email', 'Please Enter your Email').isEmail(),
    check('password', 'Please Enter your Password').isLength({ minLength: 6})
], signUp)

router.delete('/delete/:id', deleteUser)

module.exports = router;
</code>```

and here's my schema

```<code>const mongoose = require('mongoose');

let userSchema = new mongoose.Schema({
    name: { type: 'string', required: true},
    email: { type: 'string', required: true},
    password: { type: 'string', required: true},
    date: { type: Date, default: Date.now}
})

module.exports = mongoose.model('user', userSchema)
</code>```

答:
Update your delete function as below

```<code>const deleteUser = async (req, res) => {
  const { id } = req.params;
  const user = await User.findByIdAndDelete(id);
  if (!user) {
    return res.status(400).json("User not found");
  }
  res.status(200).json("User deleted successfully");
};
</code>```

findByIdAndDelete takes an ObjectId of a user to be deleted. If the user exist, it'll delete the user and return user document, else return null;

Body:
I'm trying to be able to delete a user if they choose to delete their account. I'm not sure how it's properly done. Here's the code for the delete function. I've looked at other StackOverflow solutions but I haven't been able to grasp the concept just yet. can anyone help?

const { validationResult } = require('express-validator')
const User = require('../modelSchema/User')
const mongo = require('mongodb')

const signUp = (req, res) => {

    const errors = validationResult(req)
    if(!errors.isEmpty()) return res.status(400).json({ errors: errors.array()})

    //new instance of user
   const user = new User({
    name: req.body.name,
    email: req.body.email,
    password: req.body.password })

    //save the user
  user.save()
  .then(data => {
      res.json(data)
      res.send('User added successfully!')
      console.log(data)
  })
  .catch(err => {
      res.status(400).json(err)
  })

}

const deleteUser = (req, res) => {

    let id = req.params.id;
    User.get().createCollection('user', function ( col) {
     col.deleteOne({_id: new mongo.ObjectId(id)});
    });
    res.json({ success: id })
    res.send('User Deleted Successfully!')
    .catch(err => {
        res.status(400).json(err)
    })
}

module.exports = { signUp, deleteUser }

here are the routes that I'm using

const express = require('express');
const { check } = require('express-validator')
const { signUp, deleteUser } = require('../controllers/users');

const router = express.Router();

router.post('/signup', [
    check('name', 'Please Enter your Name').not().isEmpty(),
    check('email', 'Please Enter your Email').isEmail(),
    check('password', 'Please Enter your Password').isLength({ minLength: 6})
], signUp)

router.delete('/delete/:id', deleteUser)

module.exports = router;

and here's my schema

const mongoose = require('mongoose');

let userSchema = new mongoose.Schema({
    name: { type: 'string', required: true},
    email: { type: 'string', required: true},
    password: { type: 'string', required: true},
    date: { type: Date, default: Date.now}
})

module.exports = mongoose.model('user', userSchema)

Body:
Update your delete function as below

const deleteUser = async (req, res) => {
  const { id } = req.params;
  const user = await User.findByIdAndDelete(id);
  if (!user) {
    return res.status(400).json("User not found");
  }
  res.status(200).json("User deleted successfully");
};

findByIdAndDelete takes an ObjectId of a user to be deleted. If the user exist, it'll delete the user and return user document, else return null;


答: goto I/O menu in Simulator window and inside keyboard unclick "connect hardware keyboard" or open simulator window and press cmd+shift+k

Title: Flutter keyboard not showing in ios