问:
Access reading Excel VBA date in US format
I am trying to run a query from within Excel VBA with variables from the Excel, but Access is turning my dates into US format:

```<code>Sub upload()
Last = ActiveSheet.UsedRange.Rows.Count
Dim LastOrderDate As Date
Dim LastOrderDateYear As Integer
Dim LastOrderDateMonth As Integer
Dim LastOrderDateDay As Integer

FirstOrderDate = Range("D" & Last)

FirstOrderDDate = DateSerial(Year(FirstOrderDate), Month(FirstOrderDate), Day(FirstOrderDate))

'Import Data to Benji's Ecommerce Database
ssheet = Application.ActiveWorkbook.FullName
Set acApp = CreateObject("Access.Application")
    acApp.OpenCurrentDatabase ("X:\ECommerce Database.accdb")
    acApp.Visible = True
    acApp.UserControl = True
    acApp.DoCmd.RunSQL "DELETE * FROM [OrdersDetailed] WHERE [OrderDate] >= #" & FirstOrderDDate & "#"
    acApp.CloseCurrentDatabase
    acApp.Quit
Set acApp = Nothing

End Sub
</code>```

So for instance, with the variable 01/03/2017, it uses 03/01/2017 and deletes everything past 3rd Jan 2017, instead of the desired 1st Mar 2017.

I have checked my date display settings on my computer, and as far as I can see my region is UK and date format is UKs, I have never seen US style dates ever on my comp!

What is going on here, and how can I solve it?

Thanks,

Benji

答:
Use DateSerial() in the query. Always use DateSerial(). It will never let you down. You want the SQL to look like this:

```<code>DELETE * FROM [OrdersDetailed] WHERE [OrderDate] >= DateSerial(2020, 01, 02)
</code>```

So your VBA should be:

```<code>"DELETE * FROM [OrdersDetailed] WHERE [OrderDate] >= DateSerial(" & Year(FirstOrderDDate) & ", " & Month(FirstOrderDDate) & ", " & Day(FirstOrderDDate) & ")"
</code>```

Body:
I am trying to run a query from within Excel VBA with variables from the Excel, but Access is turning my dates into US format:

Sub upload()
Last = ActiveSheet.UsedRange.Rows.Count
Dim LastOrderDate As Date
Dim LastOrderDateYear As Integer
Dim LastOrderDateMonth As Integer
Dim LastOrderDateDay As Integer

FirstOrderDate = Range("D" & Last)

FirstOrderDDate = DateSerial(Year(FirstOrderDate), Month(FirstOrderDate), Day(FirstOrderDate))

'Import Data to Benji's Ecommerce Database
ssheet = Application.ActiveWorkbook.FullName
Set acApp = CreateObject("Access.Application")
    acApp.OpenCurrentDatabase ("X:\ECommerce Database.accdb")
    acApp.Visible = True
    acApp.UserControl = True
    acApp.DoCmd.RunSQL "DELETE * FROM [OrdersDetailed] WHERE [OrderDate] >= #" & FirstOrderDDate & "#"
    acApp.CloseCurrentDatabase
    acApp.Quit
Set acApp = Nothing

End Sub

So for instance, with the variable 01/03/2017, it uses 03/01/2017 and deletes everything past 3rd Jan 2017, instead of the desired 1st Mar 2017.

I have checked my date display settings on my computer, and as far as I can see my region is UK and date format is UKs, I have never seen US style dates ever on my comp!

What is going on here, and how can I solve it?

Thanks,

Benji

Body:
Use DateSerial() in the query. Always use DateSerial(). It will never let you down. You want the SQL to look like this:

DELETE * FROM [OrdersDetailed] WHERE [OrderDate] >= DateSerial(2020, 01, 02)

So your VBA should be:

"DELETE * FROM [OrdersDetailed] WHERE [OrderDate] >= DateSerial(" & Year(FirstOrderDDate) & ", " & Month(FirstOrderDDate) & ", " & Day(FirstOrderDDate) & ")"


来源: stackexchange

问:
Get the first child from Firebase without knowing the name
I want to get the children of "games" but I have to know the names of the children.

```<code>public void getdata()
{
    FirebaseApp.DefaultInstance.SetEditorDatabaseUrl("url...");
    FirebaseDatabase.DefaultInstance.GetReference("games").GetValueAsync().ContinueWith(task => {
        if (task.IsFaulted)
        {
            Debug.Log(task.Exception);
        }
        else if (task.IsCompleted)
        {
            DataSnapshot snapshot = task.Result;
            //Get the children of "games" and Debug.log them
            snapshot.Child("path"); // Requires the path. What if I don't know the path ?
        }
    });
}
</code>```

Doesen't there exist something like:

```<code>snapshot.Child(0);
snapshot.Child(1);
</code>```

答:
As Doug said, the Firebase API doesn't allow index-based access to child nodes. You either need to know the key of the child node, or you can iterate over all child nodes.

```<code>DataSnapshot snapshot = task.Result;

foreach (DataSnapshot child in snapshot.Children) {
    Debug.Log("Received value for leader: "+child.Value);
}
</code>```

If you want to access a specific property of each child node, you'd do for example child.Child("Score").Value.

ContentLicense: CC BY-SA 4.0

Body:
I want to get the children of "games" but I have to know the names of the children.

public void getdata()
{
    FirebaseApp.DefaultInstance.SetEditorDatabaseUrl("url...");
    FirebaseDatabase.DefaultInstance.GetReference("games").GetValueAsync().ContinueWith(task => {
        if (task.IsFaulted)
        {
            Debug.Log(task.Exception);
        }
        else if (task.IsCompleted)
        {
            DataSnapshot snapshot = task.Result;
            //Get the children of "games" and Debug.log them
            snapshot.Child("path"); // Requires the path. What if I don't know the path ?
        }
    });
}

Doesen't there exist something like:

snapshot.Child(0);
snapshot.Child(1);

Body:
As Doug said, the Firebase API doesn't allow index-based access to child nodes. You either need to know the key of the child node, or you can iterate over all child nodes.

DataSnapshot snapshot = task.Result;

foreach (DataSnapshot child in snapshot.Children) {
    Debug.Log("Received value for leader: "+child.Value);
}

If you want to access a specific property of each child node, you'd do for example child.Child("Score").Value.


问:
How to search an item and get its index in Observable Collection

public struct PLU
{
    public int ID { get; set; }
    public string name { get; set; }
    public double price { get; set; }
    public int quantity {get;set;}
}

public static ObservableCollection<PLU> PLUList = new ObservableCollection<PLU>();
```

<p>I have the <code>ObservableCollection</code> as above. Now I want to search the <code>ID</code> in the <code>PLUList</code> and get its index like this:</p>

<pre class="lang-cs prettyprint-override"><code>int index = PLUList.indexOf();
if (index > -1)
{
    // Do something here
}
else
{
    // Do sth else here..
}
</code>```

What's the quick fix?

EDIT:

Let's assume that some items were added to PLUList and I want to add another new item. But before adding I want to check if the ID already exists in the list. If it does then I would like to add +1 to the quantity.

答:
Although this post is old and already answered, it can still be helpful to others so I here is my answer.

You can create extension methods similar to List<T>.FindIndex(...) methods:

public static class ObservableCollectionExtensions
{
    public static int FindIndex<T>(this ObservableCollection<T> ts, Predicate<T> match)
    {
        return ts.FindIndex(0, ts.Count, match);
    }

    public static int FindIndex<T>(this ObservableCollection<T> ts, int startIndex, Predicate<T> match)
    {
        return ts.FindIndex(startIndex, ts.Count, match);
    }

    public static int FindIndex<T>(this ObservableCollection<T> ts, int startIndex, int count, Predicate<T> match)
    {
        if (startIndex < 0) startIndex = 0;
        if (count > ts.Count) count = ts.Count;

        for (int i = startIndex; i < count; i++)
        {
            if (match(ts[i])) return i;
        }

        return -1;
    }
}
```

<p>Usage:</p>

```int index = PLUList.FindIndex(x => x.ID == 13);
if (index > -1)
{
    // Do something here...
}
else
{
    // Do something else here...
}
```

Body:
public struct PLU
{
    public int ID { get; set; }
    public string name { get; set; }
    public double price { get; set; }
    public int quantity {get;set;}
}

public static ObservableCollection<PLU> PLUList = new ObservableCollection<PLU>();

I have the ObservableCollection as above. Now I want to search the ID in the PLUList and get its index like this:

int index = PLUList.indexOf();
if (index > -1)
{
    // Do something here
}
else
{
    // Do sth else here..
}

What's the quick fix?

EDIT:

Let's assume that some items were added to PLUList and I want to add another new item. But before adding I want to check if the ID already exists in the list. If it does then I would like to add +1 to the quantity.

Body:
Although this post is old and already answered, it can still be helpful to others so I here is my answer.

You can create extension methods similar to List<T>.FindIndex(...) methods:

public static class ObservableCollectionExtensions
{
    public static int FindIndex<T>(this ObservableCollection<T> ts, Predicate<T> match)
    {
        return ts.FindIndex(0, ts.Count, match);
    }

    public static int FindIndex<T>(this ObservableCollection<T> ts, int startIndex, Predicate<T> match)
    {
        return ts.FindIndex(startIndex, ts.Count, match);
    }

    public static int FindIndex<T>(this ObservableCollection<T> ts, int startIndex, int count, Predicate<T> match)
    {
        if (startIndex < 0) startIndex = 0;
        if (count > ts.Count) count = ts.Count;

        for (int i = startIndex; i < count; i++)
        {
            if (match(ts[i])) return i;
        }

        return -1;
    }
}

Usage:

int index = PLUList.FindIndex(x => x.ID == 13);
if (index > -1)
{
    // Do something here...
}
else
{
    // Do something else here...
}


问:
How to find better algorithm for my prefix matcher algorithm
I was solving online problem and the task was something like this:

There are two arrays: numbers and prefixes.

Array numbers contains numbers: “+432112345”, “+9990”, “+4450505”

Array prefixes contains prefixes: “+4321”, “+43211”, “+7700”, “+4452”, “+4”

Find longest prefix for each number. If no prefix found for number, match with empty string.

For example:

“+432112345” matches with the longest prefix “+43211” (not +4321, cause 43211 is longer).

“+9990” doesn't match with anything, so empty string "".

“+4450505” matches with “+4”  (“+4452” doesn’t match because of the 2).

I came up with the most straight forward solution where I loop through each number with each prefix. So each time new number, I check prefixes, if some prefix is longer than last one, I will change.

Map<String, String> numsAndPrefixes = new HashMap<>();

for (String number : A) {
    for (String prefix : B) {
        if (number.contains(prefix)) {
            // if map already contains this number, check for prefixes.
            // if longer exists, switch longer one
            if (numsAndPrefixes.containsKey(number)) {
                int prefixLength = prefix.length();
                int currentLen = numsAndPrefixes.get(number).length();
                if (prefixLength > currentLen) {
                    numsAndPrefixes.put(number, prefix);
                }
            } else {
                numsAndPrefixes.put(number, prefix);
            }
        } else if (!number.contains(prefix) && !numsAndPrefixes.containsKey(number)){
            numsAndPrefixes.put(number, "");
        }
    }
}
```

So it will have two for loops. I see that each time I am doing the same job over and over, e.g checking for prefixes. It works, but it is slow.  The problem is that I can’t come up with anything better.

Could someone explain how they would approach to find better algorithm?

And more general, how do you proceed if you have somewhat working solution and trying to find better one? What knowledge am I still missing?

答:
You are using .contains(). You should use .startsWith(). It's a lot faster.

Then in your else if you are checking what you already checked in the if.

This is only one approach on how to improve the algorithm:

Sort the prefixes:

+43211 +4321 +4452 +4 +7700

What is good about this? Well, it will always find the longest prefix first. You can exit the loop and don't have to look for longer prefixes.

```<code>Arrays.sort(prefixes, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
    return o1.startsWith(o2) ? 1 : o1.compareTo(o2);
}
});

Map<String, String> numsAndPrefixes = new HashMap<>();

for (String number: numbers) {
    numsAndPrefixes.put(number, "");
    for (String prefix: prefixes) {
        if (number.startsWith(prefix, 1)) {
            numsAndPrefixes.put(number, prefix);
            break;
        }
    }
}
</code>```

But if your number starts with +1 and there is no prefix it will continue checking all the prefixes with +2 +3 +4 ... which are obviously not matching. (Issue 1)

Also if your number starts with +9 the prefix will be found very late. (Issue 2)

How to fix this? Well you can save the indices where +1 starts, +2 starts, ...:

In our prefix list:

```<code>0      1     2     3  4  5   (index)
+1233  +123  +2233 +2 +3 +4
</code>```

+2 starts at index [2] and +3 starts at index [4]. So when you want to know the prefix for a number starting with +2 you only have to check elements [2] and [3]. This will both fix issue 1 and 2.

It would also be possible to store the indices for more digits (for example where +13 starts).

Body:
I was solving online problem and the task was something like this:

There are two arrays: numbers and prefixes.

Array numbers contains numbers: “+432112345”, “+9990”, “+4450505”

Array prefixes contains prefixes: “+4321”, “+43211”, “+7700”, “+4452”, “+4”

Find longest prefix for each number. If no prefix found for number, match with empty string.

For example:

“+432112345” matches with the longest prefix “+43211” (not +4321, cause 43211 is longer).

“+9990” doesn't match with anything, so empty string "".

“+4450505” matches with “+4”  (“+4452” doesn’t match because of the 2).

I came up with the most straight forward solution where I loop through each number with each prefix. So each time new number, I check prefixes, if some prefix is longer than last one, I will change.

Map<String, String> numsAndPrefixes = new HashMap<>();

for (String number : A) {
    for (String prefix : B) {
        if (number.contains(prefix)) {
            // if map already contains this number, check for prefixes.
            // if longer exists, switch longer one
            if (numsAndPrefixes.containsKey(number)) {
                int prefixLength = prefix.length();
                int currentLen = numsAndPrefixes.get(number).length();
                if (prefixLength > currentLen) {
                    numsAndPrefixes.put(number, prefix);
                }
            } else {
                numsAndPrefixes.put(number, prefix);
            }
        } else if (!number.contains(prefix) && !numsAndPrefixes.containsKey(number)){
            numsAndPrefixes.put(number, "");
        }
    }
}

So it will have two for loops. I see that each time I am doing the same job over and over, e.g checking for prefixes. It works, but it is slow.  The problem is that I can’t come up with anything better.

Could someone explain how they would approach to find better algorithm?

And more general, how do you proceed if you have somewhat working solution and trying to find better one? What knowledge am I still missing?

Body:
You are using .contains(). You should use .startsWith(). It's a lot faster.

Then in your else if you are checking what you already checked in the if.

This is only one approach on how to improve the algorithm:

Sort the prefixes:

+43211 +4321 +4452 +4 +7700

What is good about this? Well, it will always find the longest prefix first. You can exit the loop and don't have to look for longer prefixes.

Arrays.sort(prefixes, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
    return o1.startsWith(o2) ? 1 : o1.compareTo(o2);
}
});

Map<String, String> numsAndPrefixes = new HashMap<>();

for (String number: numbers) {
    numsAndPrefixes.put(number, "");
    for (String prefix: prefixes) {
        if (number.startsWith(prefix, 1)) {
            numsAndPrefixes.put(number, prefix);
            break;
        }
    }
}

But if your number starts with +1 and there is no prefix it will continue checking all the prefixes with +2 +3 +4 ... which are obviously not matching. (Issue 1)

Also if your number starts with +9 the prefix will be found very late. (Issue 2)

How to fix this? Well you can save the indices where +1 starts, +2 starts, ...:

In our prefix list:

0      1     2     3  4  5   (index)
+1233  +123  +2233 +2 +3 +4

+2 starts at index [2] and +3 starts at index [4]. So when you want to know the prefix for a number starting with +2 you only have to check elements [2] and [3]. This will both fix issue 1 and 2.

It would also be possible to store the indices for more digits (for example where +13 starts).


问:
Convert for loop into numpy array

for timeprojection in range(100):
   for term in range(8):
       zerocouponbondprice[timeprojection,term] = zerocouponbondprice[timeprojection-1,term-1]*cashflow[timeprojection,term]
```

How can I convert something like this into numpy array form, so that I can reduce two for loop to increase the speed? (If timeprojection and term are dynamic numbers.)

答:
You can construct the numpy array from a nested list comprehension

import numpy as np

zerocouponbondprice = np.array([[k * l for k,l in zip(i,j)] for i,j in zip(zerocouponbondprice, cashflow[1:])])
```

Title: Convert for loop into numpy array

Body:
for timeprojection in range(100):
   for term in range(8):
       zerocouponbondprice[timeprojection,term] = zerocouponbondprice[timeprojection-1,term-1]*cashflow[timeprojection,term]

How can I convert something like this into numpy array form, so that I can reduce two for loop to increase the speed? (If timeprojection and term are dynamic numbers.)


问:
How to connect telegram bot with Amazon S3?
I have a telegram bot with a minimum number of functions. The task now is to upload files from users in telegram-chat and send to S3.

I use Heroku by server. But I need the fraa place, where I can store my files (S3)

Here is the bot.py code

```<code>import config
import telebot
import checking
import s3upload

bot = telebot.TeleBot(config.TOKEN)

@bot.message_handler(content_types=['photo'])
def download_photo(message):
    bot.send_message(message.chat.id, 'please wait')
    image_file_path = save_image_from_message(message)
    s3upload.image_upload(image_file_path)
    bot.send_message(message.chat_id, image_file_path)

def get_image_id_from_message(message):
    # there are multiple array of images, check the biggest
    return message.photo[len(message.photo) - 1].file_id

def get_image_path(message):
    image_id = get_image_id_from_message(message)
    file_path = bot.get_file(image_id).file_path
    print(file_path)
    return file_path;
</code>```

And so I use another python code, where connect to S3 (s3upload.py)

```<code>import boto3
import config
from botocore.client import Config

# S3 Connect
s3_bucket = boto3.resource(
    's3',
    aws_access_key_id=config.AWS_ACCESS_KEY_USER_2,
    aws_secret_access_key=config.AWS_SECRET_KEY_USER_2,
    config=Config(signature_version='s3v4')
)

def image_upload(my_file):
    data = open(my_file, 'rb')
    s3_bucket.Bucket(config.S3_BUCKET_NAME).put_object(Key=my_file, Body=data, ACL='public-read')
    print("done")
</code>```

The problem - python cant find the file (FileIsNotFound). Help me pleade understand:
1. How correctly connect to S3?
2. How I can use the files (images) from telegram-bot ?

答:
Edit: Sorry I misunderstood what was happening when I first read this.

Instead of using put_object I would use the upload_file, read the description. Also see a post about the difference.

Also regarding the function, you might try something like

```<code>def image_upload(my_file):
  file_key = s3_file_name
  s3_bucket.meta.client.upload_file(my_file, mybucket, file_key)
</code>```

To my original point, make sure your IAM user has adequate privileges. It sounds like if you're able to do it using aws s3 .. locally, then you should be good to go.

Body:
I have a telegram bot with a minimum number of functions. The task now is to upload files from users in telegram-chat and send to S3.

I use Heroku by server. But I need the fraa place, where I can store my files (S3)

Here is the bot.py code

import config
import telebot
import checking
import s3upload

bot = telebot.TeleBot(config.TOKEN)

@bot.message_handler(content_types=['photo'])
def download_photo(message):
    bot.send_message(message.chat.id, 'please wait')
    image_file_path = save_image_from_message(message)
    s3upload.image_upload(image_file_path)
    bot.send_message(message.chat_id, image_file_path)

def get_image_id_from_message(message):
    # there are multiple array of images, check the biggest
    return message.photo[len(message.photo) - 1].file_id

def get_image_path(message):
    image_id = get_image_id_from_message(message)
    file_path = bot.get_file(image_id).file_path
    print(file_path)
    return file_path;

And so I use another python code, where connect to S3 (s3upload.py)

import boto3
import config
from botocore.client import Config

# S3 Connect
s3_bucket = boto3.resource(
    's3',
    aws_access_key_id=config.AWS_ACCESS_KEY_USER_2,
    aws_secret_access_key=config.AWS_SECRET_KEY_USER_2,
    config=Config(signature_version='s3v4')
)

def image_upload(my_file):
    data = open(my_file, 'rb')
    s3_bucket.Bucket(config.S3_BUCKET_NAME).put_object(Key=my_file, Body=data, ACL='public-read')
    print("done")

The problem - python cant find the file (FileIsNotFound). Help me pleade understand:
1. How correctly connect to S3?
2. How I can use the files (images) from telegram-bot ?

Body:
Edit: Sorry I misunderstood what was happening when I first read this.

Instead of using put_object I would use the upload_file, read the description. Also see a post about the difference.

Also regarding the function, you might try something like

def image_upload(my_file):
  file_key = s3_file_name
  s3_bucket.meta.client.upload_file(my_file, mybucket, file_key)

To my original point, make sure your IAM user has adequate privileges. It sounds like if you're able to do it using aws s3 .. locally, then you should be good to go.


问:
jQuery variable scope within each
I am trying to build an array containing all the values of every form element. The alert works just find, but on console.log data is empty, am I failing to understand how scoping in javascript works?

```<code>  var data = new Array();
  $("#page2 input").each(function(index) {
      alert($(this).attr('id'));
      data[$(this).attr('id')] = $(this).val();
  });
</code>```

Many thanks for your time,

答:
The scope is correct. If the console is not displaying entires in the Array, then I'm guessing that your ID attributes are not numeric.

Doesn't meant that the data isn't there. Just means that the console chooses to only display the numeric indices.

Consider the following input into Chrome's console:

```<code>var arr = new Array();
arr['test'] = 'test';

arr;  // []
arr.test;  // 'test'
</code>```

While it is valid JavaScript to give a non numeric property to an Array, in most cases it is the wrong approach.

ContentLicense: CC BY-SA 3.0

Title: jQuery variable scope within each

Body:
I am trying to build an array containing all the values of every form element. The alert works just find, but on console.log data is empty, am I failing to understand how scoping in javascript works?

  var data = new Array();
  $("#page2 input").each(function(index) {
      alert($(this).attr('id'));
      data[$(this).attr('id')] = $(this).val();
  });

Many thanks for your time,

Body:
The scope is correct. If the console is not displaying entires in the Array, then I'm guessing that your ID attributes are not numeric.

Doesn't meant that the data isn't there. Just means that the console chooses to only display the numeric indices.

Consider the following input into Chrome's console:

var arr = new Array();
arr['test'] = 'test';

arr;  // []
arr.test;  // 'test'

While it is valid JavaScript to give a non numeric property to an Array, in most cases it is the wrong approach.


问:
EF Core - Pulling Data From Two Identical Tables
TLDR: I have a two tables with identical definitions, and I need to pull from one table or the other depending on some switch.

For example, assume a table with a bunch of "generic" FooItem and a table with "Fancy" FooItem... and the only difference between the two tables is the names, SIMPLE_FOO and FANCY_FOO

Depending on a boolean value, like GetFancy == true, I should read from FANCY_FOO, otherwise, SIMPLE_FOO.

This gets a complicated in the DbContext.  I can't have more than one DbSet<FooItem> in my context, and I can't dynamically "inject" the table name in the ModelBuilder.Entity<FooItem>(e => e.ToView("pickOne"))  ... and I don't want to duplicate an entire dbContext just to have a different table name in there.

I'm sure the solution is simple, but I'm just not seeing it.  Any assistance is appreciated.

EDIT:  I cannot change the database.  It's a dumb way to do it, but that's the way they did it and I have to live with it.

答:
The easiest thing to do, in my opinion, is to leverage the .FromSql() method and use that to choose which table:

var foos = GetFancy
  ? dbContext.FromSql(select * from FANCY_FOO)
  : dbContext.FromSql(select * from SIMPLE_FOO)

return foos.Where(/* etc /*)
```


问:
Show MDIChild Form from another MDIChild Form
Let’s I have MDIParentForm (Home), Child Form (Form1, Form2), Home has one Menu (Add) and Form1 has button (btnOk)

'''''Here is C# Code''''''

```<code> public partial class Home : DevExpress.XtraBars.Ribbon.RibbonForm
{
    public Home()
    {
        InitializeComponent();
    }
    public void  CreateForm(Form frm)
    {
        frm.MdiParent = this;
        frm.WindowState = FormWindowState.Maximized;
        frm.Show();
    }
    private void btnAddForm_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
    {
        Form1 frm = new Form1();
        CreateForm(frm);
    }
}
//Up to this 1st level my code works fine.
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void btnDone_Click(object sender, EventArgs e)
    {
//From Here I am not able show the Form2.
        Home MDIParentForm = new Home();
        Form2 frm = new Form2();
        MDIParentForm.CreateForm(childForm);
    }
}
</code>```

Action: On the click of Add Menu I used to open Form1 (It works fine) and on the click of btnOk I want to open Form2 (which is another MDIChild form).

Let me know how we can accomplish this task.

答:
What you do is you create yet another instance of your MDI parent and you set the Form2 as a child of this newly created MDI parent. This is clearly wrong, you want both to be children of the very same parent.

Either do this directly:

```<code>private void btnDone_Click(object sender, EventArgs e)
{
    Form2 frm = new Form2();
    // both have the same MDI parent
    frm.MDIParent = this.MDIParent;
    frm.Show();
}
</code>```

or, if you insist on reusing your CreateForm

```<code>private void btnDone_Click(object sender, EventArgs e)
{
    Form2 frm = new Form2();
    ((Home)this.MDIParent).CreateForm( frm );
}
</code>```

Both approaches depend on this.MDIParent set in form1 and make sure the same instance is used for newly created form2.

Body:
Let’s I have MDIParentForm (Home), Child Form (Form1, Form2), Home has one Menu (Add) and Form1 has button (btnOk)

'''''Here is C# Code''''''

 public partial class Home : DevExpress.XtraBars.Ribbon.RibbonForm
{
    public Home()
    {
        InitializeComponent();
    }
    public void  CreateForm(Form frm)
    {
        frm.MdiParent = this;
        frm.WindowState = FormWindowState.Maximized;
        frm.Show();
    }
    private void btnAddForm_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
    {
        Form1 frm = new Form1();
        CreateForm(frm);
    }
}
//Up to this 1st level my code works fine.
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void btnDone_Click(object sender, EventArgs e)
    {
//From Here I am not able show the Form2.
        Home MDIParentForm = new Home();
        Form2 frm = new Form2();
        MDIParentForm.CreateForm(childForm);
    }
}

Action: On the click of Add Menu I used to open Form1 (It works fine) and on the click of btnOk I want to open Form2 (which is another MDIChild form).

Let me know how we can accomplish this task.

Body:
What you do is you create yet another instance of your MDI parent and you set the Form2 as a child of this newly created MDI parent. This is clearly wrong, you want both to be children of the very same parent.

Either do this directly:

private void btnDone_Click(object sender, EventArgs e)
{
    Form2 frm = new Form2();
    // both have the same MDI parent
    frm.MDIParent = this.MDIParent;
    frm.Show();
}

or, if you insist on reusing your CreateForm

private void btnDone_Click(object sender, EventArgs e)
{
    Form2 frm = new Form2();
    ((Home)this.MDIParent).CreateForm( frm );
}

Both approaches depend on this.MDIParent set in form1 and make sure the same instance is used for newly created form2.


问:
Python Can't Find Correct Mysqlclient
I'm trying to get mysql up on a new Django project on MacOS. I used pip to intsall it. This is the output from my second attempt so that I could show the install here:

python3 -m pip install mysqlclient
Defaulting to user installation because normal site-packages is not writeable
Requirement already satisfied: mysqlclient in /Users/curt/Library/Python/3.7/lib/python/site-packages (1.4.6)

This is my init.py file: (the stack overflow editor has dropped the underscores)

```<code>import mysqlclient

mysqlclient.install_as_MySQLdb()
</code>```

PyCharm is indicating it can't find mysqlclient on line 1 and the message "Package requirement 'mysqlclient==1.4.6' is not satisfied" is displayed.

I tried adding the path shown in the pip install to $PYTONPATH to no effect. Is there somewhere else I should to be setting the location of mysqlclient?

Update

I opened the Pipenv environment settings and selected add package and selected mysqlclient. The version was 1.4.6. I clicked install package and got a repsonse that the install was successful.

3:28 PM   Packages installed successfully: Installed packages: 'mysqlclient'

When I closed the add package dialog. The package did not show in the environment settings dialog. When I closed it I got the same error message as above.

I checked the Pipfile.lock and saw that mysqlclient was in it so I did a sync to see if that would fix the problem. It didn't

When I ran pipenv --where, it pointed to an old django project. I created the current project with PyCharm new project option.

答: I fixed the problem by creating a new interpreter. IIRC, this also created a venv directory in the project. Now, "python3 -m pipenv --where" points to the right project. In addition, mysqlclient appeares as one of the packages. At this point it complained of not being able to run Django. I fixed this by copying the environment variable from the original interpreter.</p>

Title: Python Can't Find Correct Mysqlclient

Body:
I'm trying to get mysql up on a new Django project on MacOS. I used pip to intsall it. This is the output from my second attempt so that I could show the install here:

python3 -m pip install mysqlclient
Defaulting to user installation because normal site-packages is not writeable
Requirement already satisfied: mysqlclient in /Users/curt/Library/Python/3.7/lib/python/site-packages (1.4.6)

This is my init.py file: (the stack overflow editor has dropped the underscores)

import mysqlclient

mysqlclient.install_as_MySQLdb()

PyCharm is indicating it can't find mysqlclient on line 1 and the message "Package requirement 'mysqlclient==1.4.6' is not satisfied" is displayed.

I tried adding the path shown in the pip install to $PYTONPATH to no effect. Is there somewhere else I should to be setting the location of mysqlclient?

Update

I opened the Pipenv environment settings and selected add package and selected mysqlclient. The version was 1.4.6. I clicked install package and got a repsonse that the install was successful.

3:28 PM   Packages installed successfully: Installed packages: 'mysqlclient'

When I closed the add package dialog. The package did not show in the environment settings dialog. When I closed it I got the same error message as above.

I checked the Pipfile.lock and saw that mysqlclient was in it so I did a sync to see if that would fix the problem. It didn't

When I ran pipenv --where, it pointed to an old django project. I created the current project with PyCharm new project option.


问:
how to auto select value in dropdown in jsp using javascript for view filled data
I made one form in html, if user submit form then value stored in form will stored in database.
and i put one option Edit if user click on edit then open that filled form in model, but how to fill the dropdown in html.

this is my form code

```<code><!-- Large Modal -->
<div id="additem" class="modal fade">
    <div class="modal-dialog modal-lg" role="document">

        <div class="modal-content ">
            <div class="modal-header pd-x-20">
                <h6 class="modal-title">Message Preview</h6>
                <button type="button" class="close" data-dismiss="modal"
                    aria-label="Close">
                    <span aria-hidden="true">×</span>
                </button>
            </div>
            <form method="post" action="additem" enctype="multipart/form-data">
                <div class="modal-body pd-20">
                    <div class="form-group row">
                        <label class="col-md-3 col-form-label">Item Name</label>
                        <div class="col-md-9">
                            <input type="hidden" value="${shopkeeper.sk_id}" name="sk_id">
                            <input type="text" class="form-control"
                                placeholder="Enter item name here..." name="name">
                        </div>
                    </div>
                    <div class="form-group row">
                        <label class="col-md-3 col-form-label">Item Type</label>
                        <div class="col-md-9">
                            <select class="btn btn-primary m-b-5 m-t-5" name="itemtype">
                                <option value="" disabled selected>Item Type</option>
                                <option value="Grocery">Grocery</option>
                                <option value="Bread and Dairy">Bread and Dairy</option>
                                <option value="Fruits">Fruits</option>
                                <option value="Beverages">Beverages</option>
                                <option value="Sweets">Sweets</option>
                                <option value="Packed Snack">Packed Snack</option>
                            </select>
                        </div>
                    </div>
                    <div class="form-group row">
                        <label class="col-md-3 col-form-label">Item Brand</label>
                        <div class="col-md-9">
                            <input type="text" class="form-control"
                                placeholder="Enter item brand here..." name="brand">
                        </div>
                    </div>
                    <div class="form-group row">
                        <label class="col-md-3 col-form-label">Item Price</label>
                        <div class="col-md-9">
                            <input type="text" class="form-control"
                                placeholder="Enter item price here..." name="price">
                        </div>
                    </div>
                    <div class="form-group row">
                        <label class="col-md-3 col-form-label">Price with
                            Discount</label>
                        <div class="col-md-9">
                            <input type="text" class="form-control"
                                placeholder="Enter item price here..." name="offerprice">
                        </div>
                    </div>
                    <div class="form-group row">
                        <label class="col-md-3 col-form-label">Item Image</label>
                        <div class="col-md-9">
                            <div class="form-group files color  mb-lg-0">
                                <input type="file" class="file" class="form-control1"
                                    name="image" accept="image/*">
                            </div>
                        </div>
                    </div>
                    <div class="form-group row">
                        <label class="col-md-3 col-form-label">Product
                            Availability</label>
                        <div class="col-md-9">
                            <select class="btn btn-primary m-b-5 m-t-5" name="availability">
                                <option value="" disabled selected>Product
                                    Availability</option>
                                <option value="In Stock">In Stock</option>
                                <option value="Out of Stock">Out of Stock</option>
                            </select>
                        </div>
                    </div>
                    <div class="form-group row">
                        <label class="col-md-3 col-form-label">Item Description</label>
                        <div class="col-md-9">
                            <textarea class="form-control" rows="3"
                                placeholder="Enter item description here..." name="description"></textarea>
                        </div>
                    </div>
                </div>
                <button type="submit"
                    class="btn btn-primary btn-right m-b-5 m-t-20" id="Button">Submit</button>
            </form>
            <!-- modal-body -->
            <div class="modal-footer">
                <button type="button" class="btn btn-primary">Add Item</button>
                <button type="button" class="btn btn-success" data-dismiss="modal">Close</button>
            </div>
        </div>

    </div>
    <!-- modal-dialog -->
</div>
<!-- modal -->
</code>```

this is my button code for load data when click on edit this code will execute

```<code><button class="adtocart"
                                                        onclick="loaddata(${listitem.item_id},'${listitem.name}','${listitem.brand}','${listitem.price}','${listitem.description}','${listitem.availability}','${listitem.itemtype}',${listitem.offerprice});"
                                                        data-toggle="modal" data-target="#edititem">
                                                        <i class="fa fa-edit"></i>
                                                    </button>
</code>```

this is my javascript function for handel data send by button. this how i fill the value of text box

```<code>function loaddata(item_id,name,brand,price,description,availability,itemtype,offerprice)
   {
       alert("Hello! I am an alert box!");
       document.f1.item_id.value=item_id;
       document.f1.name.value=name;
       document.f1.brand.value=brand;
       document.f1.price.value=price;
       document.f1.description.value=description;

   }
</code>```

below code is for display filled form for edit data

```<code><!-- Edit Item Model Start -->
<!-- Large Modal -->
<div id="edititem" class="modal fade">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content ">
            <div class="modal-header pd-x-20">
                <h6 class="modal-title">Edit Item</h6>
                <button type="button" class="close" data-dismiss="modal"
                    aria-label="Close">
                    <span aria-hidden="true">×</span>
                </button>
            </div>
            <form method="post" action="edititem" enctype="multipart/form-data"
                name="f1">
                <div class="modal-body pd-20">
                    <div class="form-group row">
                        <label class="col-md-3 col-form-label">Item Name</label>
                        <div class="col-md-9">
                            <input type="hidden" value="${shopkeeper.sk_id}" name="sk_id">
                            <input type="hidden" id="item_id" name="item_id"> <input
                                type="text" class="form-control"
                                placeholder="Enter item name here..." name="name">
                        </div>
                    </div>
                    <div class="form-group row">
                        <label class="col-md-3 col-form-label">Item Type</label>
                        <div class="col-md-9">
                            <select class="btn btn-primary m-b-5 m-t-5" name="itemtype">
                                <option value="" disabled selected>Item Type</option>
                                <option value="Grocery">Grocery</option>
                                <option value="Bread and Dairy">Bread and Dairy</option>
                                <option value="Fruits">Fruits</option>
                                <option value="Beverages">Beverages</option>
                                <option value="Sweets">Sweets</option>
                                <option value="Packed Snack">Packed Snack</option>
                            </select>
                        </div>
                    </div>
                    <div class="form-group row">
                        <label class="col-md-3 col-form-label">Item Brand</label>
                        <div class="col-md-9">
                            <input type="text" class="form-control"
                                placeholder="Enter item brand here..." name="brand">
                        </div>
                    </div>
                    <div class="form-group row">
                        <label class="col-md-3 col-form-label">Item Price</label>
                        <div class="col-md-9">
                            <input type="text" class="form-control"
                                placeholder="Enter item price here..." name="price">
                        </div>
                    </div>
                    <div class="form-group row">
                        <label class="col-md-3 col-form-label">Item Image</label>
                        <div class="col-md-9">
                            <div class="form-group files color  mb-lg-0">
                                <input type="file" class="file" class="form-control1"
                                    name="image" accept="image/*">
                            </div>
                        </div>
                    </div>
                    <div class="form-group row">
                        <label class="col-md-3 col-form-label">Item Description</label>
                        <div class="col-md-9">
                            <textarea class="form-control" rows="3"
                                placeholder="Enter item description here..." name="description"
                                id="description"></textarea>
                        </div>
                    </div>
                </div>
                <button type="submit"
                    class="btn btn-primary btn-right m-b-5 m-t-20" id="Button">Submit</button>
            </form>
            <!-- modal-body -->
            <div class="modal-footer">
                <button type="button" class="btn btn-primary">Add Item</button>
                <button type="button" class="btn btn-success" data-dismiss="modal">Close</button>
            </div>
        </div>

    </div>
    <!-- modal-dialog -->
</div>
<!-- modal -->
<!-- Edit Item Model End -->
</code>```

答:
Actually, I don't really know what you are looking for. But maybe this piece of code would be helpful.

function selectOption(value)
{
  // get the select
  const selectTest = document.f1.itemtype;

  // the loop runs over all options
  for (let i = 0; i < selectTest.options.length; i++)
  {

   if( value === selectTest.options[i].value)
    {
     // if the "value" is an possible option
      // this option is selected and the loop is aborted.

     selectTest.options[i].selected = true;
      break;
    }

  }

}

// call the function with the value of the second option
selectOption('test2');```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form name="f1">
  <select name="itemtype" >
    <option value="test1">TEST 1</option>
    <option value="test2">TEST 2</option>
    <option value="test3">TEST 3</option>
    <option value="test4">TEST 4</option>
    <option value="test5">TEST 5</option>
    <option value="test6">TEST 6</option>
  </select>
</form></code>```

Body:
I made one form in html, if user submit form then value stored in form will stored in database.
and i put one option Edit if user click on edit then open that filled form in model, but how to fill the dropdown in html.

this is my form code

Message Preview

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

            <form method="post" action="additem" enctype="multipart/form-data">

                        Item Name

                            <input type="hidden" value="${shopkeeper.sk_id}" name="sk_id">
                            <input type="text" class="form-control"
                                placeholder="Enter item name here..." name="name">

                        Item Type

                            <select class="btn btn-primary m-b-5 m-t-5" name="itemtype">
                                <option value="" disabled selected>Item Type</option>
                                <option value="Grocery">Grocery</option>
                                <option value="Bread and Dairy">Bread and Dairy</option>
                                <option value="Fruits">Fruits</option>
                                <option value="Beverages">Beverages</option>
                                <option value="Sweets">Sweets</option>
                                <option value="Packed Snack">Packed Snack</option>
                            </select>

                        Item Brand

                            <input type="text" class="form-control"
                                placeholder="Enter item brand here..." name="brand">

                        Item Price

                            <input type="text" class="form-control"
                                placeholder="Enter item price here..." name="price">

                        Price with
                            Discount

                            <input type="text" class="form-control"
                                placeholder="Enter item price here..." name="offerprice">

                        Item Image

                                <input type="file" class="file" class="form-control1"
                                    name="image" accept="image/*">

                        Product
                            Availability

                            <select class="btn btn-primary m-b-5 m-t-5" name="availability">
                                <option value="" disabled selected>Product
                                    Availability</option>
                                <option value="In Stock">In Stock</option>
                                <option value="Out of Stock">Out of Stock</option>
                            </select>

                        Item Description

                            <textarea class="form-control" rows="3"
                                placeholder="Enter item description here..." name="description"></textarea>

                <button type="submit"
                    class="btn btn-primary btn-right m-b-5 m-t-20" id="Button">Submit</button>
            </form>

                <button type="button" class="btn btn-primary">Add Item</button>
                <button type="button" class="btn btn-success" data-dismiss="modal">Close</button>

this is my button code for load data when click on edit this code will execute

<button class="adtocart"
                                                        onclick="loaddata(${listitem.item_id},'${listitem.name}','${listitem.brand}','${listitem.price}','${listitem.description}','${listitem.availability}','${listitem.itemtype}',${listitem.offerprice});"
                                                        data-toggle="modal" data-target="#edititem">

                                                    </button>

this is my javascript function for handel data send by button. this how i fill the value of text box

function loaddata(item_id,name,brand,price,description,availability,itemtype,offerprice)
   {
       alert("Hello! I am an alert box!");
       document.f1.item_id.value=item_id;
       document.f1.name.value=name;
       document.f1.brand.value=brand;
       document.f1.price.value=price;
       document.f1.description.value=description;

   }

below code is for display filled form for edit data

Edit Item

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

            <form method="post" action="edititem" enctype="multipart/form-data"
                name="f1">

                        Item Name

                            <input type="hidden" value="${shopkeeper.sk_id}" name="sk_id">
                            <input type="hidden" id="item_id" name="item_id"> <input
                                type="text" class="form-control"
                                placeholder="Enter item name here..." name="name">

                        Item Type

                            <select class="btn btn-primary m-b-5 m-t-5" name="itemtype">
                                <option value="" disabled selected>Item Type</option>
                                <option value="Grocery">Grocery</option>
                                <option value="Bread and Dairy">Bread and Dairy</option>
                                <option value="Fruits">Fruits</option>
                                <option value="Beverages">Beverages</option>
                                <option value="Sweets">Sweets</option>
                                <option value="Packed Snack">Packed Snack</option>
                            </select>

                        Item Brand

                            <input type="text" class="form-control"
                                placeholder="Enter item brand here..." name="brand">

                        Item Price

                            <input type="text" class="form-control"
                                placeholder="Enter item price here..." name="price">

                        Item Image

                                <input type="file" class="file" class="form-control1"
                                    name="image" accept="image/*">

                        Item Description

                            <textarea class="form-control" rows="3"
                                placeholder="Enter item description here..." name="description"
                                id="description"></textarea>

                <button type="submit"
                    class="btn btn-primary btn-right m-b-5 m-t-20" id="Button">Submit</button>
            </form>

                <button type="button" class="btn btn-primary">Add Item</button>
                <button type="button" class="btn btn-success" data-dismiss="modal">Close</button>

Body:
Actually, I don't really know what you are looking for. But maybe this piece of code would be helpful.

function selectOption(value)
{
  // get the select
  const selectTest = document.f1.itemtype;

  // the loop runs over all options
  for (let i = 0; i < selectTest.options.length; i++)
  {

   if( value === selectTest.options[i].value)
    {
     // if the "value" is an possible option
      // this option is selected and the loop is aborted.

     selectTest.options[i].selected = true;
      break;
    }

  }

}

// call the function with the value of the second option
selectOption('test2');

<form name="f1">
  <select name="itemtype" >
    <option value="test1">TEST 1</option>
    <option value="test2">TEST 2</option>
    <option value="test3">TEST 3</option>
    <option value="test4">TEST 4</option>
    <option value="test5">TEST 5</option>
    <option value="test6">TEST 6</option>
  </select>
</form>


问:
Get response from php script with curl after posting response
I have a form which uses curl to submit the apiKey to my server and then the script on my server verify the key and returns true and false. but instead of response. I'm getting Trying to access array offset on value of type null. I want to know How to get response from my server after curl submission.

Curl Submit

```<code>    $post['apiKey'] = $apiKey;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_URL,"https://www.pawnhost.com/phevapi/verify_api.php");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

     $json = curl_exec($ch);
     $response = json_decode($json, true);
</code>```

Server Script

```<code><?php

define("ERROR_HEADER_URL", "Location: " . $_SERVER['HTTP_REFERER'] . "?error=");

require("includes/initialize.php");

if ($_SERVER['REQUEST_METHOD'] != 'POST') header(ERROR_HEADER_URL . "invalidRequest");

$postParams = allowedPOSTParams($allowed_params=['apiKey']);

if (!isset($postParams['apiKey'])) header(ERROR_HEADER_URL . "verficationFailed");

$apiKey = escape($postParams['apiKey']);

if (isInputEmpty($apiKey)) {
    header(ERROR_HEADER_URL . "emptyFields");

} elseif (!$apiKey == 25) {
    header(ERROR_HEADER_URL . urlencode("invalidKey"));

} else {

    $response = [];

    if (getApiKeyUserDetails($apiKey, $connection)) {

        if (getApiKeyUserDetails($apiKey, $connection)['apiKeyUsed'] > 0) {
            $response['success'] = false;
            $response['error'] = 'apiKeyUsed';
        } else {
            makeApiKeyUsed($apiKey, $connection);
            $response['success'] = true;
        }

    } else {
        $response['success'] = false;
        $response['error'] = 'invalidApiKey';
    }

    return json_encode($response);

}
</code>```

Allowed Post Params Function:

```<code>function allowedPOSTParams($allowed_params=[]) {
    $allowed_array = [];
    foreach ($allowed_params as $param) {
        if (isset($_POST[$param])) {
            $allowed_array[$param] = $_POST[$param];
        } else {
            $allowed_array[$param] = NULL;
        }
    }
    return $allowed_array;
}
</code>```

答:
Replace

```<code>curl_setopt($ch, CURLOPT_POSTFIELDS, $apiKey);
</code>```

with

```<code>curl_setopt($ch, CURLOPT_POSTFIELDS, array('apiKey'=>$apiKey));
</code>```

Then, you will able to find apiKey as POST parameter.

Body:
I have a form which uses curl to submit the apiKey to my server and then the script on my server verify the key and returns true and false. but instead of response. I'm getting Trying to access array offset on value of type null. I want to know How to get response from my server after curl submission.

Curl Submit

    $post['apiKey'] = $apiKey;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_URL,"https://www.pawnhost.com/phevapi/verify_api.php");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

     $json = curl_exec($ch);
     $response = json_decode($json, true);

Server Script

<?php

define("ERROR_HEADER_URL", "Location: " . $_SERVER['HTTP_REFERER'] . "?error=");

require("includes/initialize.php");

if ($_SERVER['REQUEST_METHOD'] != 'POST') header(ERROR_HEADER_URL . "invalidRequest");

$postParams = allowedPOSTParams($allowed_params=['apiKey']);

if (!isset($postParams['apiKey'])) header(ERROR_HEADER_URL . "verficationFailed");

$apiKey = escape($postParams['apiKey']);

if (isInputEmpty($apiKey)) {
    header(ERROR_HEADER_URL . "emptyFields");

} elseif (!$apiKey == 25) {
    header(ERROR_HEADER_URL . urlencode("invalidKey"));

} else {

    $response = [];

    if (getApiKeyUserDetails($apiKey, $connection)) {

        if (getApiKeyUserDetails($apiKey, $connection)['apiKeyUsed'] > 0) {
            $response['success'] = false;
            $response['error'] = 'apiKeyUsed';
        } else {
            makeApiKeyUsed($apiKey, $connection);
            $response['success'] = true;
        }

    } else {
        $response['success'] = false;
        $response['error'] = 'invalidApiKey';
    }

    return json_encode($response);

}

Allowed Post Params Function:

function allowedPOSTParams($allowed_params=[]) {
    $allowed_array = [];
    foreach ($allowed_params as $param) {
        if (isset($_POST[$param])) {
            $allowed_array[$param] = $_POST[$param];
        } else {
            $allowed_array[$param] = NULL;
        }
    }
    return $allowed_array;
}

Body:
Replace

curl_setopt($ch, CURLOPT_POSTFIELDS, $apiKey);

with

curl_setopt($ch, CURLOPT_POSTFIELDS, array('apiKey'=>$apiKey));

Then, you will able to find apiKey as POST parameter.


问:
Reverse for '' not found '' is not a valid view function or pattern name
I'm getting the above message when trying to view the cart page in my Ecommerce site. I can see that this is a fairly common question but after trawling through multiple other threads here, none of the solutions are working.

In the current iteration of my code I have added an app_name to the cart app and then referenced this in my html, but no joy.

Traceback:

```<code>Environment:

Request Method: GET
Request URL: http://127.0.0.1:8000/cart/

Django Version: 2.2.5
Python Version: 3.8.1
Installed Applications:
['pages.apps.PagesConfig',
 'accounts.apps.AccountsConfig',
 'products.apps.ProductsConfig',
 'cart.apps.CartConfig',
 'search.apps.SearchConfig',
 'crispy_forms',
 'storages',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles']
Installed Middleware:
('whitenoise.middleware.WhiteNoiseMiddleware',
 'django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware')

Template error:
In template C:\Users\Vegeta\OneDrive\Visual Studio Code\milestone-project-four\pages\templates\base.html, error at line 0
   Reverse for '' not found. '' is not a valid view function or pattern name.
   1 : {% load static %}
   2 :
   3 : <!DOCTYPE html>
   4 : <html lang="en">
   5 :
   6 : <head>
   7 :     <meta charset="utf-8" />
   8 :     <!-- Set the viewport to allow responsiveness -->
   9 :     <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
   10 :     <!-- Bootstrap CSS -->

Traceback:

File "C:\Users\Vegeta\OneDrive\Visual Studio Code\milestone-project-four\env\lib\site-packages\django\core\handlers\exception.py" in inner
  34.             response = get_response(request)

File "C:\Users\Vegeta\OneDrive\Visual Studio Code\milestone-project-four\env\lib\site-packages\django\core\handlers\base.py" in _get_response
  115.                 response = self.process_exception_by_middleware(e, request)

File "C:\Users\Vegeta\OneDrive\Visual Studio Code\milestone-project-four\env\lib\site-packages\django\core\handlers\base.py" in _get_response
  113.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\Vegeta\OneDrive\Visual Studio Code\milestone-project-four\cart\views.py" in view_cart
  7.     return render(request, 'cart.html')

File "C:\Users\Vegeta\OneDrive\Visual Studio Code\milestone-project-four\env\lib\site-packages\django\shortcuts.py" in render
  36.     content = loader.render_to_string(template_name, context, request, using=using)

File "C:\Users\Vegeta\OneDrive\Visual Studio Code\milestone-project-four\env\lib\site-packages\django\template\loader.py" in render_to_string
  62.     return template.render(context, request)

File "C:\Users\Vegeta\OneDrive\Visual Studio Code\milestone-project-four\env\lib\site-packages\django\template\backends\django.py" in render
  61.             return self.template.render(context)

File "C:\Users\Vegeta\OneDrive\Visual Studio Code\milestone-project-four\env\lib\site-packages\django\template\base.py" in render
  171.                     return self._render(context)

File "C:\Users\Vegeta\OneDrive\Visual Studio Code\milestone-project-four\env\lib\site-packages\django\template\base.py" in _render
  163.         return self.nodelist.render(context)

File "C:\Users\Vegeta\OneDrive\Visual Studio Code\milestone-project-four\env\lib\site-packages\django\template\base.py" in render
  937.                 bit = node.render_annotated(context)

File "C:\Users\Vegeta\OneDrive\Visual Studio Code\milestone-project-four\env\lib\site-packages\django\template\base.py" in render_annotated
  904.             return self.render(context)

File "C:\Users\Vegeta\OneDrive\Visual Studio Code\milestone-project-four\env\lib\site-packages\django\template\loader_tags.py" in render
  150.             return compiled_parent._render(context)

File "C:\Users\Vegeta\OneDrive\Visual Studio Code\milestone-project-four\env\lib\site-packages\django\template\base.py" in _render
  163.         return self.nodelist.render(context)

File "C:\Users\Vegeta\OneDrive\Visual Studio Code\milestone-project-four\env\lib\site-packages\django\template\base.py" in render
  937.                 bit = node.render_annotated(context)

File "C:\Users\Vegeta\OneDrive\Visual Studio Code\milestone-project-four\env\lib\site-packages\django\template\base.py" in render_annotated
  904.             return self.render(context)

File "C:\Users\Vegeta\OneDrive\Visual Studio Code\milestone-project-four\env\lib\site-packages\django\template\loader_tags.py" in render
  62.                 result = block.nodelist.render(context)

File "C:\Users\Vegeta\OneDrive\Visual Studio Code\milestone-project-four\env\lib\site-packages\django\template\base.py" in render
  937.                 bit = node.render_annotated(context)

File "C:\Users\Vegeta\OneDrive\Visual Studio Code\milestone-project-four\env\lib\site-packages\django\template\base.py" in render_annotated
  904.             return self.render(context)

File "C:\Users\Vegeta\OneDrive\Visual Studio Code\milestone-project-four\env\lib\site-packages\django\template\defaulttags.py" in render
  443.             url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)

File "C:\Users\Vegeta\OneDrive\Visual Studio Code\milestone-project-four\env\lib\site-packages\django\urls\base.py" in reverse
  90.     return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))

File "C:\Users\Vegeta\OneDrive\Visual Studio Code\milestone-project-four\env\lib\site-packages\django\urls\resolvers.py" in _reverse_with_prefix
  673.         raise NoReverseMatch(msg)

Exception Type: NoReverseMatch at /cart/
Exception Value: Reverse for '' not found. '' is not a valid view function or pattern name.
</code>```

project urls.py

```<code>from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('accounts/', include('accounts.urls')),
    path('accounts/', include('django.contrib.auth.urls')),
    path('', include('pages.urls')),
    path('products/', include('products.urls')),
    path('cart/', include('cart.urls')),
    path('search/', include('search.urls')),
]
</code>```

cart app urls.py

```<code>from django.urls import path
from .views import view_cart, add_to_cart

app_name = 'cart'

urlpatterns = [
    path('',  view_cart, name='view_cart'),
    path('add/<slug:pk>', add_to_cart, name='add_to_cart'),
]
</code>```

cart app views.py

```<code>from django.shortcuts import render, redirect, reverse
from products.models import Product

def view_cart(request):
    """A View that renders the cart contents page"""
    return render(request, 'cart.html')

def add_to_cart(request, item_id):
    """
    Add an item to the cart
    """
    cart = request.session.get('cart', {})
    if item_id in cart:
        cart[item_id] = int(cart[item_id])
    else:
        cart[item_id] = cart.get(item_id)

    request.session['cart'] = cart
    return redirect(reverse('home'))
</code>```

base.html nav link to view cart

```<code><li class="nav-item" id="nav-item-cart">
     <a class="nav-link" href="{% url 'cart:view_cart' %}"><i class="fa fa-shopping-cart fa-1.5x">/i>Cart
         {% if product_count > 0 %}
         <label class="badge badge-warning">{{ product_count }}</label>
         {% endif %}
     </a>
</li>

</code>```

artifact.html form to add an item to the cart

```<code><form method="POST" action="{% url 'cart:add_to_cart' artifact.id %}">
     {% csrf_token %}
     <label for="buy" id="buy-header"><strong>Buy lot</strong></label>
     <input name="disabled" type="text" class="input-field" value="£100,000.00" size="8" disabled>
     <a class="btn btn-sm artifact-btn" type="submit">Add to cart</a>
</form>
</code>```

cart.html

```<code>    {% extends 'base.html' %}

    {% block content %}
    <section class="cart-section">
        <div class="container">
            <h1 id="cart-header">Your Cart</h1>

            {% for item in cart_items %}

            <div class="row lot-wrapper">
                <div class="col-5 col-md-6 image-wrapper">
                    <img src="{{ MEDIA_URL }}{{ item.product.image }}" class="lot-image" alt="Picture of {{ product.name }}">
                </div>
                <div class="col-7 col-md-6 cart-content-wrapper">
                    <h2 class="cart-lot-header">{{ item.name }}</h2>
                    <div class="cart-lot-text">
                        <p><strong>Price</strong> <span class="bid-value"> {{ item.buyout }}</span></p>
                    </div>
                    <a href="#"><i class="fa fa-trash" aria-hidden="true"></i></a>
                </div>
            </div>
            <div class="row">
                <p>Grand Total: £{{ total }}</p>
            </div>
            {% endfor %}
        </div>

        <div class="container">
            <div class="row cart-options">
                <div class="col">
                    <a href="{% url for 'products' %}" class="btn btn-sm" id="continue-btn">Continue shopping</a>
                </div>
                <div class="col">
                    <a href="checkout.html" class="btn btn-sm" id="checkout-btn">Checkout</a>
                </div>
            </div>
        </div>
    </section>
    {% endblock content %}

</code>```

Any help would be greatly appreciated.

答:
Answer is as per Robin Zigmond's comment:

{% url for 'products' %} is wrong syntax - I think you mean {% url 'products' %}

Body:
I'm getting the above message when trying to view the cart page in my Ecommerce site. I can see that this is a fairly common question but after trawling through multiple other threads here, none of the solutions are working.

In the current iteration of my code I have added an app_name to the cart app and then referenced this in my html, but no joy.

Traceback:

Environment:

Request Method: GET
Request URL: http://127.0.0.1:8000/cart/

Django Version: 2.2.5
Python Version: 3.8.1
Installed Applications:
['pages.apps.PagesConfig',
 'accounts.apps.AccountsConfig',
 'products.apps.ProductsConfig',
 'cart.apps.CartConfig',
 'search.apps.SearchConfig',
 'crispy_forms',
 'storages',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles']
Installed Middleware:
('whitenoise.middleware.WhiteNoiseMiddleware',
 'django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware')

Template error:
In template C:\Users\Vegeta\OneDrive\Visual Studio Code\milestone-project-four\pages\templates\base.html, error at line 0
   Reverse for '' not found. '' is not a valid view function or pattern name.
   1 : {% load static %}
   2 :
   3 : <!DOCTYPE html>
   4 :
   5 :
   6 :
   7 :     <meta charset="utf-8" />
   8 :
   9 :     <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
   10 :

Traceback:

File "C:\Users\Vegeta\OneDrive\Visual Studio Code\milestone-project-four\env\lib\site-packages\django\core\handlers\exception.py" in inner
  34.             response = get_response(request)

File "C:\Users\Vegeta\OneDrive\Visual Studio Code\milestone-project-four\env\lib\site-packages\django\core\handlers\base.py" in _get_response
  115.                 response = self.process_exception_by_middleware(e, request)

File "C:\Users\Vegeta\OneDrive\Visual Studio Code\milestone-project-four\env\lib\site-packages\django\core\handlers\base.py" in _get_response
  113.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\Vegeta\OneDrive\Visual Studio Code\milestone-project-four\cart\views.py" in view_cart
  7.     return render(request, 'cart.html')

File "C:\Users\Vegeta\OneDrive\Visual Studio Code\milestone-project-four\env\lib\site-packages\django\shortcuts.py" in render
  36.     content = loader.render_to_string(template_name, context, request, using=using)

File "C:\Users\Vegeta\OneDrive\Visual Studio Code\milestone-project-four\env\lib\site-packages\django\template\loader.py" in render_to_string
  62.     return template.render(context, request)

File "C:\Users\Vegeta\OneDrive\Visual Studio Code\milestone-project-four\env\lib\site-packages\django\template\backends\django.py" in render
  61.             return self.template.render(context)

File "C:\Users\Vegeta\OneDrive\Visual Studio Code\milestone-project-four\env\lib\site-packages\django\template\base.py" in render
  171.                     return self._render(context)

File "C:\Users\Vegeta\OneDrive\Visual Studio Code\milestone-project-four\env\lib\site-packages\django\template\base.py" in _render
  163.         return self.nodelist.render(context)

File "C:\Users\Vegeta\OneDrive\Visual Studio Code\milestone-project-four\env\lib\site-packages\django\template\base.py" in render
  937.                 bit = node.render_annotated(context)

File "C:\Users\Vegeta\OneDrive\Visual Studio Code\milestone-project-four\env\lib\site-packages\django\template\base.py" in render_annotated
  904.             return self.render(context)

File "C:\Users\Vegeta\OneDrive\Visual Studio Code\milestone-project-four\env\lib\site-packages\django\template\loader_tags.py" in render
  150.             return compiled_parent._render(context)

File "C:\Users\Vegeta\OneDrive\Visual Studio Code\milestone-project-four\env\lib\site-packages\django\template\base.py" in _render
  163.         return self.nodelist.render(context)

File "C:\Users\Vegeta\OneDrive\Visual Studio Code\milestone-project-four\env\lib\site-packages\django\template\base.py" in render
  937.                 bit = node.render_annotated(context)

File "C:\Users\Vegeta\OneDrive\Visual Studio Code\milestone-project-four\env\lib\site-packages\django\template\base.py" in render_annotated
  904.             return self.render(context)

File "C:\Users\Vegeta\OneDrive\Visual Studio Code\milestone-project-four\env\lib\site-packages\django\template\loader_tags.py" in render
  62.                 result = block.nodelist.render(context)

File "C:\Users\Vegeta\OneDrive\Visual Studio Code\milestone-project-four\env\lib\site-packages\django\template\base.py" in render
  937.                 bit = node.render_annotated(context)

File "C:\Users\Vegeta\OneDrive\Visual Studio Code\milestone-project-four\env\lib\site-packages\django\template\base.py" in render_annotated
  904.             return self.render(context)

File "C:\Users\Vegeta\OneDrive\Visual Studio Code\milestone-project-four\env\lib\site-packages\django\template\defaulttags.py" in render
  443.             url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)

File "C:\Users\Vegeta\OneDrive\Visual Studio Code\milestone-project-four\env\lib\site-packages\django\urls\base.py" in reverse
  90.     return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))

File "C:\Users\Vegeta\OneDrive\Visual Studio Code\milestone-project-four\env\lib\site-packages\django\urls\resolvers.py" in _reverse_with_prefix
  673.         raise NoReverseMatch(msg)

Exception Type: NoReverseMatch at /cart/
Exception Value: Reverse for '' not found. '' is not a valid view function or pattern name.

project urls.py

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('accounts/', include('accounts.urls')),
    path('accounts/', include('django.contrib.auth.urls')),
    path('', include('pages.urls')),
    path('products/', include('products.urls')),
    path('cart/', include('cart.urls')),
    path('search/', include('search.urls')),
]

cart app urls.py

from django.urls import path
from .views import view_cart, add_to_cart

app_name = 'cart'

urlpatterns = [
    path('',  view_cart, name='view_cart'),
    path('add/<slug:pk>', add_to_cart, name='add_to_cart'),
]

cart app views.py

from django.shortcuts import render, redirect, reverse
from products.models import Product

def view_cart(request):
    """A View that renders the cart contents page"""
    return render(request, 'cart.html')

def add_to_cart(request, item_id):
    """
    Add an item to the cart
    """
    cart = request.session.get('cart', {})
    if item_id in cart:
        cart[item_id] = int(cart[item_id])
    else:
        cart[item_id] = cart.get(item_id)

    request.session['cart'] = cart
    return redirect(reverse('home'))

base.html nav link to view cart

     /i>Cart
         {% if product_count > 0 %}
         {{ product_count }}
         {% endif %}

artifact.html form to add an item to the cart

<form method="POST" action="{% url 'cart:add_to_cart' artifact.id %}">
     {% csrf_token %}
     Buy lot
     <input name="disabled" type="text" class="input-field" value="£100,000.00" size="8" disabled>
     Add to cart
</form>

cart.html

    {% extends 'base.html' %}

    {% block content %}

Your Cart

            {% for item in cart_items %}

{{ item.name }}

Price  {{ item.buyout }}

Grand Total: £{{ total }}

            {% endfor %}

                    Continue shopping

                    Checkout

    {% endblock content %}

Any help would be greatly appreciated.


问:
PyQT - modifying main window widgets from other functions
A PyQT beginner question.  I'm wondering how to do something like the following - modify widgets in the main window from outside the main window class.  Like so:

```<code>class MainWindow(QtGui.QMainWindow):

    def __init__(self, parent=None):

        super(MainWindow,self).__init__(parent)

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.progressBar.setMaximum(100)
        self.ui.progressBar.setMinimum(0)
        self.ui.progressBar.setValue(0)

        self.connect(self.ui.pushButton, QtCore.SIGNAL('clicked()'), self.slotDoStuff)

    def slotDoStuff(self):
        AnotherFunction()

def AnotherFunction():
    modify progress bar here...
</code>```

Is there a way to do something like this? I'd like to subclass the event handlers for various main window actions and not have them all in the MainWindow class.  Thanks!

答:
First, there's a much better way to connect signals to slots on PyQt:

```<code>self.button.clicked.connect(self.method)
</code>```

You can use lambda functions to pass extra arguments to methods.

```<code>def do_stuff(arg)
     #do stuff with arg
</code>```

Then you call

```<code>self.button1.clicked.connect(lambda : do_stuff('btn one'))
self.button2.clicked.connect(lambda : do_stuff('btn two'))
</code>```

You can pass whatever you want, including your MainWindow instance to be modified

Body:
A PyQT beginner question.  I'm wondering how to do something like the following - modify widgets in the main window from outside the main window class.  Like so:

class MainWindow(QtGui.QMainWindow):

    def __init__(self, parent=None):

        super(MainWindow,self).__init__(parent)

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.progressBar.setMaximum(100)
        self.ui.progressBar.setMinimum(0)
        self.ui.progressBar.setValue(0)

        self.connect(self.ui.pushButton, QtCore.SIGNAL('clicked()'), self.slotDoStuff)

    def slotDoStuff(self):
        AnotherFunction()

def AnotherFunction():
    modify progress bar here...

Is there a way to do something like this? I'd like to subclass the event handlers for various main window actions and not have them all in the MainWindow class.  Thanks!

Body:
First, there's a much better way to connect signals to slots on PyQt:

self.button.clicked.connect(self.method)

You can use lambda functions to pass extra arguments to methods.

def do_stuff(arg)
     #do stuff with arg

Then you call

self.button1.clicked.connect(lambda : do_stuff('btn one'))
self.button2.clicked.connect(lambda : do_stuff('btn two'))

You can pass whatever you want, including your MainWindow instance to be modified


问:
How do you set the absolute position of figure windows with matplotlib?
I'm writing a simple Python application that uses matplotlib to display a few figures on screen. The number of figures generated is based on user input and changes throughout the application's life. The user has the ability to issue a "plot" command to generate a new figure window with the selected data series. In order to improve the user experience, I would like to provide another command that would programmatically arrange all open figure windows in some convenient arrangement (e.g. tile them across the available screen space).

I believe to have found APIs that allow me to adjust the size of the figure window (in pixels), but haven't had any success in finding a way to set their absolute position on screen. Is there a way to do this without delving into the details of whatever backend is in use? I would like to do this in a backend-agnostic way so I can avoid relying upon implementation details that might change in the future.

答:
```<code>def show_img(img, title=""):
    plt.imshow(img)
    plt.title(title)
    thismanager = plt.get_current_fig_manager()
    thismanager.window.wm_geometry("+100+100")
    plt.show()
</code>```


问:
What is the problem with my first android app?
i am learning android development and i was testing something:
i was testing and everything went successful but my text didn't appear on my app. What's the problem ?</p>

```<code>public class MainActivity extends AppCompatActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        TextView monTexte=new TextView(this);

        monTexte.setText("A salamu aleykoum");
        monTexte.setTextSize(50);
        monTexte.setTextColor(0x0000FF);

        setContentView(monTexte);
    }
}
</code>```

答:
You can just do them in your xml by adding these to your TextView

```<code>        android:text="A salamu aleykoum"
        android:textSize="50sp"
        android:textColor="#0000FF"

</code>```

To do it programatically, you need to give your TextView an ID in your xml. In my case (activity_main.xml)

```<code>    <TextView
        android:id="@+id/monTexte"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</code>```

Then bring your TextView and find it using findViewById

```<code>package com.example.stackoverflow;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private TextView monTexte;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        monTexte = findViewById(R.id.monTexte);
    }

}

</code>```

Now you can

```<code>
    monTexte.setText("A salamu aleykoum");
    monTexte.setTextSize(50);
    monTexte.setTextColor(0x0000FF);

</code>```

Altogether:

```<code>
package com.example.stackoverflow;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private TextView monte;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        monTexte = findViewById(R.id.monTexte);
        monTexte.setText("A salamu aleykoum");
        monTexte.setTextSize(50);
        monTexte.setTextColor(0x0000FF);
    }

}

</code>```

I really hope it helps!

Body:
i am learning android development and i was testing something:
i was testing and everything went successful but my text didn't appear on my app. What's the problem ?

public class MainActivity extends AppCompatActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        TextView monTexte=new TextView(this);

        monTexte.setText("A salamu aleykoum");
        monTexte.setTextSize(50);
        monTexte.setTextColor(0x0000FF);

        setContentView(monTexte);
    }
}

Body:
You can just do them in your xml by adding these to your TextView

        android:text="A salamu aleykoum"
        android:textSize="50sp"
        android:textColor="#0000FF"

To do it programatically, you need to give your TextView an ID in your xml. In my case (activity_main.xml)

    <TextView
        android:id="@+id/monTexte"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

Then bring your TextView and find it using findViewById

package com.example.stackoverflow;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private TextView monTexte;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        monTexte = findViewById(R.id.monTexte);
    }

}

Now you can

    monTexte.setText("A salamu aleykoum");
    monTexte.setTextSize(50);
    monTexte.setTextColor(0x0000FF);

Altogether:

package com.example.stackoverflow;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private TextView monte;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        monTexte = findViewById(R.id.monTexte);
        monTexte.setText("A salamu aleykoum");
        monTexte.setTextSize(50);
        monTexte.setTextColor(0x0000FF);
    }

}

I really hope it helps!


问:
Please I keep getting this error when I try to run my flutter app

What went wrong:  Could not determine the dependencies of task
  ':app:compileDebugJavaWithJavac'. > Could not resolve all task
  dependencies for configuration ':app:debugCompileClasspath'. > Could
  not find
  io.flutter:flutter_embedding_debug:1.0.0-e1e6ced81d029258d449bdec2ba3cddca9c2ca0c.
  Required by: project :app > Could not find
  io.flutter:x86_debug:1.0.0-e1e6ced81d029258d449bdec2ba3cddca9c2ca0c.
  Required by: project :app > Could not find
  io.flutter:x86_64_debug:1.0.0-e1e6ced81d029258d449bdec2ba3cddca9c2ca0c.
  Required by: project :ap

答:
Make sure you're on master branch and your flutter upgraded to last version.
then if the error remain delete the .gradle cache folder in youre home and applying ./gradlew cleanBuildCache in the project's android sub directory.</p>


问:
no matches for kind "Deployment" in version "apps/v1"
I have minikube v0.26.0 version and kubectl v1.10.1 version and localKube v1.8.0

i get the following error when i try to deploy the kubeless ui

```<code>$ kubectl create -f https://raw.githubusercontent.com/kubeless/kubeless-ui/master/k8s.yaml
</code>```

ERROR:

unable to recognize "https://raw.githubusercontent.com/kubeless/kubeless-ui/master/k8s.yaml": no matches for kind "Deployment" in version "apps/v1"

答:
As the comment says, you're using a version of Kubernetes that's very old. Deployment wasn't available under apps/v1 until Kubernetes 1.9, and you appear to be using 1.8.

If you want to solve this problem without upgrading your cluster, you'll need to replace the apiVersion value in all of your Deployment objects with one of the older paths:

```<code>apiVersion: apps/v1beta1
kind: Deployment
</code>```

Note that while this will fix the immediate problem, you will still likely run into other compatibility issues, and should upgrade your cluster.

Body:
I have minikube v0.26.0 version and kubectl v1.10.1 version and localKube v1.8.0

i get the following error when i try to deploy the kubeless ui

$ kubectl create -f https://raw.githubusercontent.com/kubeless/kubeless-ui/master/k8s.yaml

ERROR:

unable to recognize "https://raw.githubusercontent.com/kubeless/kubeless-ui/master/k8s.yaml": no matches for kind "Deployment" in version "apps/v1"

Body:
As the comment says, you're using a version of Kubernetes that's very old. Deployment wasn't available under apps/v1 until Kubernetes 1.9, and you appear to be using 1.8.

If you want to solve this problem without upgrading your cluster, you'll need to replace the apiVersion value in all of your Deployment objects with one of the older paths:

apiVersion: apps/v1beta1
kind: Deployment

Note that while this will fix the immediate problem, you will still likely run into other compatibility issues, and should upgrade your cluster.


问:
checking the existence of input with a given class in the table by javascript
Desc:

I have a table, x:rows, y:colums

in mostly rows are the same structure inputs (class/type etc.), but not in everyone.

I calculate by javascipt entire tables by class.

in those which I do not have when entering fields with values (those given by the user)

if there is no field in the line and the field is declared in javascript (by class), [that the result should be entered there]

for exp.:

VM36:473 Uncaught TypeError: Cannot set property 'value' of undefined
      at updateRowX (:473:35)
      at HTMLTableElement. (:491:9)

because in this row I dont have input with class for exp. "additional_free" (such as the example below)

```<code> function updateRowX(row) {
        let inputs = {}
        for (let input of row.querySelectorAll("input")) inputs[input.className] = new TimeInput(input);
        let { start, end, normative, actual, overtime, additional_work, additional_free, nulladditionalnull_work_null, additional_night } = inputs;
        if (!start) return; // Not a data row

        let diff = actual - normative;

        if (overtime == 0) {
            additional_free.value = Math.min(0, 1);   <---- here
            nulladditionalnull_work_null.value = Math.min(0, 1);
        }
        if (overtime < eightHours && overtime != 0) {
            additional_free.value = Math.max(0, overtime); <---- here
            nulladditionalnull_work_null.value = Math.min(0, 1);
        }

        if (overtime > eightHours) {
            additional_free.value = eightHours; <---- here
            nulladditionalnull_work_null.value = Math.max(0, overtime - eightHours);
        }
    }

</code>```

My question:

is it possible for the program to check in these places if this variable exists?

Did I describe the problem well?

答:
1. if there is no input with class overtime, overtime will not equal to 0, but will be undefined

2. in your code, if there is more then one input with same class, the last one will override the previous

3. In the case overtime is defined, it will be of type TimeInput. not a number. so how you compare it as a number?

anyway, if you want to set value of additional_free only if it is not undefined, you can do:

```<code>additional_free && (additional_free.value = Math.min(0, 1));
</code>```

Body:
Desc:

I have a table, x:rows, y:colums

in mostly rows are the same structure inputs (class/type etc.), but not in everyone.

I calculate by javascipt entire tables by class.

in those which I do not have when entering fields with values (those given by the user)

if there is no field in the line and the field is declared in javascript (by class), [that the result should be entered there]

for exp.:

VM36:473 Uncaught TypeError: Cannot set property 'value' of undefined
      at updateRowX (:473:35)
      at HTMLTableElement. (:491:9)

because in this row I dont have input with class for exp. "additional_free" (such as the example below)

 function updateRowX(row) {
        let inputs = {}
        for (let input of row.querySelectorAll("input")) inputs[input.className] = new TimeInput(input);
        let { start, end, normative, actual, overtime, additional_work, additional_free, nulladditionalnull_work_null, additional_night } = inputs;
        if (!start) return; // Not a data row

        let diff = actual - normative;

        if (overtime == 0) {
            additional_free.value = Math.min(0, 1);   <---- here
            nulladditionalnull_work_null.value = Math.min(0, 1);
        }
        if (overtime < eightHours && overtime != 0) {
            additional_free.value = Math.max(0, overtime); <---- here
            nulladditionalnull_work_null.value = Math.min(0, 1);
        }

        if (overtime > eightHours) {
            additional_free.value = eightHours; <---- here
            nulladditionalnull_work_null.value = Math.max(0, overtime - eightHours);
        }
    }

My question:

is it possible for the program to check in these places if this variable exists?

Did I describe the problem well?

Body:
1. if there is no input with class overtime, overtime will not equal to 0, but will be undefined

2. in your code, if there is more then one input with same class, the last one will override the previous

3. In the case overtime is defined, it will be of type TimeInput. not a number. so how you compare it as a number?

anyway, if you want to set value of additional_free only if it is not undefined, you can do:

additional_free && (additional_free.value = Math.min(0, 1));


问:
Powershell regex group regex matches but doesn't have my group. What's missing?
I have some code that I am porting from a jenkins script and I need it as a shell command. So I know the regex works - What's blowing my mind is how it can match but then not have my capture group. What I need is just the root level directory names as such:

```<code>foo
baz
</code>```

How can it "match" but then not have my group? BTW: If there is a simpler way to achieve this, I am all ears.

PS E:\SysData\Jenkins\workspace\chb0_chb0mb_example> git diff --name-only origin/master  feature/foo |  %{ Resolve-Path -Relative $_ } | sls  '.\\.*\\.*'  | sls '\\.\\(.+?)\\.*|.*' | %{$_.matches}

Groups   : {0}
Success  : True
Name     : 0
Captures : {0}
Index    : 0
Length   : 48
Value    : .\foo\Nuget\deleteme.txt

Groups   : {0}
Success  : True
Name     : 0
Captures : {0}
Index    : 0
Length   : 55
Value    : .\baz\QC_OH_DARKESol\deleteme.txt

```

答:
Assuming I have the question right.  For one thing, a literal period has to be backslashed.  But it works without backslashing it anyway.  There's no backslash at the beginning.  Not everyone has the git command.  This pattern could be shorter, but it works.  I'm expanding the groups property, which you didn't show.

```<code>'.\foo\Nuget\deleteme.txt' | sls '.\\(.+?)\\.*|.*' | % matches | % groups

Groups   : {0, 1}
Success  : True
Name     : 0
Captures : {0}
Index    : 0
Length   : 6
Value    : .\foo\

Success  : True
Name     : 1
Captures : {1}
Index    : 2
Length   : 3
Value    : foo
</code>```

Piping the object from the first sls to the second sls messes something up with the group capture.  It seems like a bug.  Submitted:  piping select-string to itself and the strange effect on matches  The value property isn't even right here.

```<code>'abc' | select-string a | select-string '(b)' | % matches | % groups

Groups   : {0}
Success  : True
Name     : 0
Captures : {0}
Index    : 0
Length   : 1
Value    : a   # should be b
</code>```

Compare with sending a plain string to the second select-string, which gives the right output:

```<code>'abc' | select-string a | % line | select-string '(b)' | % matches | % groups

Groups   : {0, 1}
Success  : True
Name     : 0
Captures : {0}
Index    : 1
Length   : 1
Value    : b

Success  : True
Name     : 1
Captures : {1}
Index    : 1
Length   : 1
Value    : b
</code>```

Body:
I have some code that I am porting from a jenkins script and I need it as a shell command. So I know the regex works - What's blowing my mind is how it can match but then not have my capture group. What I need is just the root level directory names as such:

foo
baz

How can it "match" but then not have my group? BTW: If there is a simpler way to achieve this, I am all ears.

PS E:\SysData\Jenkins\workspace\chb0_chb0mb_example> git diff --name-only origin/master  feature/foo |  %{ Resolve-Path -Relative $_ } | sls  '.\\.*\\.*'  | sls '\\.\\(.+?)\\.*|.*' | %{$_.matches}

Groups   : {0}
Success  : True
Name     : 0
Captures : {0}
Index    : 0
Length   : 48
Value    : .\foo\Nuget\deleteme.txt

Groups   : {0}
Success  : True
Name     : 0
Captures : {0}
Index    : 0
Length   : 55
Value    : .\baz\QC_OH_DARKESol\deleteme.txt

Body:
Assuming I have the question right.  For one thing, a literal period has to be backslashed.  But it works without backslashing it anyway.  There's no backslash at the beginning.  Not everyone has the git command.  This pattern could be shorter, but it works.  I'm expanding the groups property, which you didn't show.

'.\foo\Nuget\deleteme.txt' | sls '.\\(.+?)\\.*|.*' | % matches | % groups

Groups   : {0, 1}
Success  : True
Name     : 0
Captures : {0}
Index    : 0
Length   : 6
Value    : .\foo\

Success  : True
Name     : 1
Captures : {1}
Index    : 2
Length   : 3
Value    : foo

Piping the object from the first sls to the second sls messes something up with the group capture.  It seems like a bug.  Submitted:  piping select-string to itself and the strange effect on matches  The value property isn't even right here.

'abc' | select-string a | select-string '(b)' | % matches | % groups

Groups   : {0}
Success  : True
Name     : 0
Captures : {0}
Index    : 0
Length   : 1
Value    : a   # should be b

Compare with sending a plain string to the second select-string, which gives the right output:

'abc' | select-string a | % line | select-string '(b)' | % matches | % groups

Groups   : {0, 1}
Success  : True
Name     : 0
Captures : {0}
Index    : 1
Length   : 1
Value    : b

Success  : True
Name     : 1
Captures : {1}
Index    : 1
Length   : 1
Value    : b