问:
Question about file reading and comparing
First Off I have a File That Looks Like This:

```<code>//Manager Ids

ManagerName: FirstName_LastName
ManagerLoginId: 12345
</code>```

And a Text Box That has a five digit code(ex. 12345) That gets entered. When the Enter Key Is pressed it is assigned to a String called: "EnteredEmployeeId", Then What I need is to search the Entire file above for "EnteredEmployeeId" and if it matches then it will open another page, if it doesn't find that number then display a message(That tells you no employee Id found).

So essentially Im trying to open a file search the entire document for the Id then return true or false to allow it too either display an error or open a new page, and reset the EnteredEmployeeId to nothing.

My Code So Far:

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Rent_a_Car
{
    public partial class Employee_Login_Page : Form
    {
        public Employee_Login_Page()
        {
            InitializeComponent();
        }
        string ManagersPath = @"C:\Users\Name\Visual Studios Project Custom Files\Rent A Car Employee Id's\Managers\Manager_Ids.txt"; //Path To Manager Logins
        string EnteredEmployeeId;

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void Employee_Id_TextBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) &&           //Checks Characters entered are Numbers Only and allows them
                (e.KeyChar != '0'))
            {
                e.Handled = true;
            }
            else if (e.KeyChar == (char)13)                                         //Checks if The "Enter" Key is pressed
            {
                EnteredEmployeeId = Employee_Id_TextBox.Text;                         //Assigns EnteredEmployeeId To the Entered Numbes In Text Box

                bool result = ***IsNumberInFile***(EnteredEmployeeId, "ManagerLoginId:", ManagersPath);
                if (result)
                {
                             //open new window
                }
                else
                {
                    MessageBox.Show("User Not Found");
                }
            }
        }
    }
}
</code>```

答:
Short answer

Is your question about how to read your file?

```<code>private bool ManagerExists(int managerId)
{
    return this.ReadManagers().Where(manager => manager.Id == managerId).Any();
}

private IEnumerable<Manager> ReadManagers()
{
    using (var reader = System.IO.File.OpenText(managersFileName))
    {
        while (!reader.EndOfStream)
        {
            string lineManagerName = reader.ReadLine();
            string lineMangerId = reader.ReadLine();

            string managerName = ExtractValue(lineManagerName);
            int managerId = Int32.Parse(ExtractValue(lineManagerId));

            yield return new Manager
            {
                Id = managerId,
                Name = managerName,
            }
    }
}

private string ExtractValue(string text)
{
    // the value of the read text starts after the space:
    const char separator = ' ';
    int indexSeparator = text.IndexOf(separator);
    return text.SubString(indexSeparator + 1);
}
</code>```

Long Answer

I see several problems in your design.

The most important thing is that you intertwine your manager handling with your form.
You should separate your concerns.

Apparently you have the notion of a sequence of Managers, each Manager has a Name (first name, last name) and a ManagerId, and in future maybe other properties.

This sequence is persistable: it is saved somewhere, and if you load it again, you have the same sequence of Managers.

In this version you want to be able to see if a Manager with a given ManagerId exists. Maybe in future you might want more functionality, like fetching information of a Manager with a certain Id, or Fetch All managers, or let's go crazy: Add / Remove / Change managers!

You see in this description I didn't mention your Forms at all. Because I separated it from your Forms, you can use it in other forms, or even in a class that has nothing to do with a Form, for instance you can use it in a unit test.

I described what I needed in such a general from, that in future I might even change it. Users of my persistable manager collection wouldn't even notice it: I can put it in a JSON file, or XML; I can save the data in a Dictionary, a database, or maybe even fetch it from the internet.

All that users need to know, is that they have to create an instance of the class, using some parameters, and bingo, you can fetch Managers.

You also give users the freedom to decide how the data is to be saved: if they want to save it in a JSON file, changes in your form class will be minimal.

An object that stores sequences of objects is quite often called a Repository.

Let's create some classes:

```<code>interface IManager
{
    public int Id {get;}
    public string Name {get; set;}
}

interface IManagerRepository
{
    bool ManagerExists(int managerId);

    // possible future extensions: Add / Retrieve / Update / Delete (CRUD)
    IManager Add(IManager manager);
    IManager Find(int managerId);
    void Update(IManager manager);
    void Delete(int ManagerId);
}

class Manager : IManager
{
    public Id {get; set;}
    public string Name {get; set;}
}

class ManagerFileRepository : IManagerRepository,
{
    public ManagerFileRepository(string fileName)
    {
         // TODO implement
    }

    // TODO: implement.
}
</code>```

The ManagerFileRepository saves the managers in a file. It hides for the outside world how the file is internally structured. It could be your file format, it could be a CSV-file, or JSON / XML.

I also separated an interface, so if you later decide to save the data somewhere else, for instance in a Dictionary (for unit tests), or in a database, users of your Repository class won't see the difference.

Let's first see if you can use this class.

```<code>class MyForm : Form
{
    const string managerFileName = ...
    private IManagerRepository ManagerRepository {get;}

    public MyForm()
    {
        InitializeComponent();

        this.ManagerRepository = new ManagerFileRepository(managerFileName);
    }

    public bool ManagerExists(int managerId)
    {
        return this.ManagerRepository.ManagerExists(managerId);
    }
</code>```

Now let's handle your keyPress:

```<code>private void Employee_Id_TextBox_KeyPress(object sender, KeyPressEventArgs e)
{
    TextBox textBox = (TextBox)sender;
    ... // code about numbers and enter key

    int enteredManagerId = Int32.Parse(textBox.Text);
    bool managerExists = this.ManagerExists(enteredManagerId);

    if (managerExists) { ... }
</code>```

}

This code seems to do what you want in an easy way. It looks transparent. The managerRepository is testable, reusable, simple to extend or change, because users won't notice this. So the class looks good. Let's implement

Implement ManagerFileRepository

There are several ways to implement reading the file:

(1) Read everything at construction time

and keep the read data in memory. If you add Managers they are not saved until you say so. Advantages: after initial startup it is fast. You can make changes and later decide not to save them anyway, so it is just like editing any other file. Disadvantage: if your program crashes, you have lost your changes.

(2) Read the file every time you need information

Advantage: data is always up-to-date, even if others edited the file while your program runs. If you change the manager collection it is immediately saved, so other can use it.

Which solution you choose depends on the size of the file and the importance of never losing data. If you file contains millions of records, then maybe it wasn't very wise to save the data in a file. Consider SQLite to save it in a small fairly fast database.

```<code>class ManagerFileRepository : IManagerRepository, IEnumerable<IManager>
{
    private readonly IDictionary<int, IManager> managers;

    public ManagerFileRepository(string FileName)
    {
        this.managers = ReadManagers(fileName);
    }

    public bool ManagerExists(int managerId)
    {
        return this.Managers.HasKey(managerId);
    }

    private static IEnumerable<IManager> ReadManagers(string fileName)
    {
         // See the short answer above
    }
}
</code>```

Room for improvement

If you will be using your manager repository for more things, consider to let the repository implement ICollection<IManager> and IReadOnlyCollection<IManager>. This is quite simple:

```<code>public IEnumerable<IManager> GetEnumerator()
{
    return this.managers.Values.GetEnumerator();
}
public void Add(IManager manager)
{
    this.managers.Add(manager.Id, manager);
}
// etc.
</code>```

If you add functions to change the manager collection you'll also need a Save method:

```<code>public void Save()
{
    using (var writer = File.CreateText(FullFileName))
    {
        const string namePrefix = "ManagerName: ";
        const string idPrefix = "ManagerLoginId: ";
        foreach (var manager in managers.Values)
        {
            string managerLine = namePrefix + manager.Name;
            writer.WriteLine(managerLine);

            string idLine = idPrefix + manager.Id.ToString();
            writer.WriteLine(idLine);
        }
    }
}
</code>```

Another method of improvement: your file structure. Consider using a more standard file structure: CSV, JSON, XML. There are numerous NUGET packages (CSVHelper, NewtonSoft.Json) that makes reading and writing Managers much more robust.

Summary

Because you separated the concerns of persisting your managers from your form, you can reuse the manager repository, especially if you need functionality to Add / Retrieve / Update / Delete managers.

Because of the separation it is much easier to unit test your functions. And future changes won't hinder users of the repository, because they won't notice that the data has changed.

Body:
First Off I have a File That Looks Like This:

//Manager Ids

ManagerName: FirstName_LastName
ManagerLoginId: 12345

And a Text Box That has a five digit code(ex. 12345) That gets entered. When the Enter Key Is pressed it is assigned to a String called: "EnteredEmployeeId", Then What I need is to search the Entire file above for "EnteredEmployeeId" and if it matches then it will open another page, if it doesn't find that number then display a message(That tells you no employee Id found).

So essentially Im trying to open a file search the entire document for the Id then return true or false to allow it too either display an error or open a new page, and reset the EnteredEmployeeId to nothing.

My Code So Far:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Rent_a_Car
{
    public partial class Employee_Login_Page : Form
    {
        public Employee_Login_Page()
        {
            InitializeComponent();
        }
        string ManagersPath = @"C:\Users\Name\Visual Studios Project Custom Files\Rent A Car Employee Id's\Managers\Manager_Ids.txt"; //Path To Manager Logins
        string EnteredEmployeeId;

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void Employee_Id_TextBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) &&           //Checks Characters entered are Numbers Only and allows them
                (e.KeyChar != '0'))
            {
                e.Handled = true;
            }
            else if (e.KeyChar == (char)13)                                         //Checks if The "Enter" Key is pressed
            {
                EnteredEmployeeId = Employee_Id_TextBox.Text;                         //Assigns EnteredEmployeeId To the Entered Numbes In Text Box

                bool result = ***IsNumberInFile***(EnteredEmployeeId, "ManagerLoginId:", ManagersPath);
                if (result)
                {
                             //open new window
                }
                else
                {
                    MessageBox.Show("User Not Found");
                }
            }
        }
    }
}

Body:
Short answer

Is your question about how to read your file?

private bool ManagerExists(int managerId)
{
    return this.ReadManagers().Where(manager => manager.Id == managerId).Any();
}

private IEnumerable<Manager> ReadManagers()
{
    using (var reader = System.IO.File.OpenText(managersFileName))
    {
        while (!reader.EndOfStream)
        {
            string lineManagerName = reader.ReadLine();
            string lineMangerId = reader.ReadLine();

            string managerName = ExtractValue(lineManagerName);
            int managerId = Int32.Parse(ExtractValue(lineManagerId));

            yield return new Manager
            {
                Id = managerId,
                Name = managerName,
            }
    }
}

private string ExtractValue(string text)
{
    // the value of the read text starts after the space:
    const char separator = ' ';
    int indexSeparator = text.IndexOf(separator);
    return text.SubString(indexSeparator + 1);
}

Long Answer

I see several problems in your design.

The most important thing is that you intertwine your manager handling with your form.
You should separate your concerns.

Apparently you have the notion of a sequence of Managers, each Manager has a Name (first name, last name) and a ManagerId, and in future maybe other properties.

This sequence is persistable: it is saved somewhere, and if you load it again, you have the same sequence of Managers.

In this version you want to be able to see if a Manager with a given ManagerId exists. Maybe in future you might want more functionality, like fetching information of a Manager with a certain Id, or Fetch All managers, or let's go crazy: Add / Remove / Change managers!

You see in this description I didn't mention your Forms at all. Because I separated it from your Forms, you can use it in other forms, or even in a class that has nothing to do with a Form, for instance you can use it in a unit test.

I described what I needed in such a general from, that in future I might even change it. Users of my persistable manager collection wouldn't even notice it: I can put it in a JSON file, or XML; I can save the data in a Dictionary, a database, or maybe even fetch it from the internet.

All that users need to know, is that they have to create an instance of the class, using some parameters, and bingo, you can fetch Managers.

You also give users the freedom to decide how the data is to be saved: if they want to save it in a JSON file, changes in your form class will be minimal.

An object that stores sequences of objects is quite often called a Repository.

Let's create some classes:

interface IManager
{
    public int Id {get;}
    public string Name {get; set;}
}

interface IManagerRepository
{
    bool ManagerExists(int managerId);

    // possible future extensions: Add / Retrieve / Update / Delete (CRUD)
    IManager Add(IManager manager);
    IManager Find(int managerId);
    void Update(IManager manager);
    void Delete(int ManagerId);
}

class Manager : IManager
{
    public Id {get; set;}
    public string Name {get; set;}
}

class ManagerFileRepository : IManagerRepository,
{
    public ManagerFileRepository(string fileName)
    {
         // TODO implement
    }

    // TODO: implement.
}

The ManagerFileRepository saves the managers in a file. It hides for the outside world how the file is internally structured. It could be your file format, it could be a CSV-file, or JSON / XML.

I also separated an interface, so if you later decide to save the data somewhere else, for instance in a Dictionary (for unit tests), or in a database, users of your Repository class won't see the difference.

Let's first see if you can use this class.

class MyForm : Form
{
    const string managerFileName = ...
    private IManagerRepository ManagerRepository {get;}

    public MyForm()
    {
        InitializeComponent();

        this.ManagerRepository = new ManagerFileRepository(managerFileName);
    }

    public bool ManagerExists(int managerId)
    {
        return this.ManagerRepository.ManagerExists(managerId);
    }

Now let's handle your keyPress:

private void Employee_Id_TextBox_KeyPress(object sender, KeyPressEventArgs e)
{
    TextBox textBox = (TextBox)sender;
    ... // code about numbers and enter key

    int enteredManagerId = Int32.Parse(textBox.Text);
    bool managerExists = this.ManagerExists(enteredManagerId);

    if (managerExists) { ... }

}

This code seems to do what you want in an easy way. It looks transparent. The managerRepository is testable, reusable, simple to extend or change, because users won't notice this. So the class looks good. Let's implement

Implement ManagerFileRepository

There are several ways to implement reading the file:

(1) Read everything at construction time

and keep the read data in memory. If you add Managers they are not saved until you say so. Advantages: after initial startup it is fast. You can make changes and later decide not to save them anyway, so it is just like editing any other file. Disadvantage: if your program crashes, you have lost your changes.

(2) Read the file every time you need information

Advantage: data is always up-to-date, even if others edited the file while your program runs. If you change the manager collection it is immediately saved, so other can use it.

Which solution you choose depends on the size of the file and the importance of never losing data. If you file contains millions of records, then maybe it wasn't very wise to save the data in a file. Consider SQLite to save it in a small fairly fast database.

class ManagerFileRepository : IManagerRepository, IEnumerable<IManager>
{
    private readonly IDictionary<int, IManager> managers;

    public ManagerFileRepository(string FileName)
    {
        this.managers = ReadManagers(fileName);
    }

    public bool ManagerExists(int managerId)
    {
        return this.Managers.HasKey(managerId);
    }

    private static IEnumerable<IManager> ReadManagers(string fileName)
    {
         // See the short answer above
    }
}

Room for improvement

If you will be using your manager repository for more things, consider to let the repository implement ICollection<IManager> and IReadOnlyCollection<IManager>. This is quite simple:

public IEnumerable<IManager> GetEnumerator()
{
    return this.managers.Values.GetEnumerator();
}
public void Add(IManager manager)
{
    this.managers.Add(manager.Id, manager);
}
// etc.

If you add functions to change the manager collection you'll also need a Save method:

public void Save()
{
    using (var writer = File.CreateText(FullFileName))
    {
        const string namePrefix = "ManagerName: ";
        const string idPrefix = "ManagerLoginId: ";
        foreach (var manager in managers.Values)
        {
            string managerLine = namePrefix + manager.Name;
            writer.WriteLine(managerLine);

            string idLine = idPrefix + manager.Id.ToString();
            writer.WriteLine(idLine);
        }
    }
}

Another method of improvement: your file structure. Consider using a more standard file structure: CSV, JSON, XML. There are numerous NUGET packages (CSVHelper, NewtonSoft.Json) that makes reading and writing Managers much more robust.

Summary

Because you separated the concerns of persisting your managers from your form, you can reuse the manager repository, especially if you need functionality to Add / Retrieve / Update / Delete managers.

Because of the separation it is much easier to unit test your functions. And future changes won't hinder users of the repository, because they won't notice that the data has changed.


来源: stackexchange

问:
mysql query magento consecutive left join problem
I have this query that doesn't give me the expected results from the magento 1.9 database:

```<code>SELECT
customer.email AS email,
company.value as comp

FROM customer_entity AS customer

JOIN customer_address_entity AS addressentity
    ON customer.entity_id=addressentity.parent_id

LEFT JOIN customer_address_entity_varchar AS company
    ON  company.entity_id=addressentity.entity_id
WHERE
    customer.store_id = 1 AND

    company.attribute_id=24 AND

    customer.email="this@mail.com"
</code>```

It should give me the email and the company value as null if it doesn't exist but it give me nothing if there is no company name.

答:
Please use left outer join for customer_address_entity table as well,</p>

```<code>SELECT
customer.email AS email,
company.value as comp

FROM customer_entity AS customer

FULL OUTER JOIN customer_address_entity AS addressentity
    ON customer.entity_id=addressentity.parent_id

FULL OUTER JOIN customer_address_entity_varchar AS company
    ON  company.entity_id=addressentity.entity_id;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have this query that doesn't give me the expected results from the magento 1.9 database:

SELECT
customer.email AS email,
company.value as comp

FROM customer_entity AS customer

JOIN customer_address_entity AS addressentity
    ON customer.entity_id=addressentity.parent_id

LEFT JOIN customer_address_entity_varchar AS company
    ON  company.entity_id=addressentity.entity_id
WHERE
    customer.store_id = 1 AND

    company.attribute_id=24 AND

    customer.email="this@mail.com"

It should give me the email and the company value as null if it doesn't exist but it give me nothing if there is no company name.

Body:
Please use left outer join for customer_address_entity table as well,

SELECT
customer.email AS email,
company.value as comp

FROM customer_entity AS customer

FULL OUTER JOIN customer_address_entity AS addressentity
    ON customer.entity_id=addressentity.parent_id

FULL OUTER JOIN customer_address_entity_varchar AS company
    ON  company.entity_id=addressentity.entity_id;


问:
Large amount of unit tests cause freezes with Failed Binder Transaction
I have about 400 unit tests that I have written for my Android application. If I run the tests package by package, everything works fine and all my tests pass. However, if I try to run them all at once, eventually (about 360 tests in), Android starts spitting out !!! Failed Binder Transaction Errors !!!. After about 10-20 of these errors, the process for the application I am testing gets killed and the unit tests never even complete.

I should note that during this time Eclipse reports Collecting test information in the Console. I think that is odd because it shows that it is running tests even though the JUnit UI doesn't reflect that. When everything works properly, during the Collecting test information phase I see the tests run, the JUnit UI then comes up, and then all the tests are run again (I know this by reading logcat). That is (I think) a separate issue, but I felt I would mention it if anybody knew what that was about.

Edit as of June 6th 2011

As per Christopher's answer below, I have verified that this only happens when attempting to run this through Eclipse. If i run my test suite using ANT, all the tests finally execute.

When I attempt to run my test suite now, Eclipse essentially hangs on "collecting test information". I haven't let it run for an extended period of time, but I will give that a try as soon as I can to see if it ever completes.

答:
I investigated this again and, as far as I can tell, this is purely an issue with the Android Eclipse plugin.  An issue that seems to be fixed, but still can occur sometimes (possibly it's machine-dependent).

As you mention, the Eclipse plugin appears to run all the tests twice.  What it's actually doing the first time is gathering the test suite and test names, so that it can show all the test names in that nice hierarchical JUnit UI.

However, "running" the tests like this seems to cause a problem.  As part of Android SDK Tools v8, a "workaround" was added which places a 15ms delay between checking each test.  This is done to prevent "Binder transaction failures ... for large test suites".

Indeed, I went back to my project that was having the "FAILED BINDER TRANSACTION" errors, and I could not reproduce it on the command line.  We also tried in Eclipse and it couldn't be reproduced any more (even although I'm sure we had SDK Tools r8+ when we originally saw this).

However, I can still generally reproduce it in Eclipse.  Try running your tests again from Eclipse with the latest Android tools, or try out this minimal GitHub repository I created and see if you can reproduce it:

https://github.com/orrc/android-large-test-failures#readme

ContentLicense: CC BY-SA 3.0


问:
how to get first and last day of each month for past 4 years from current date in IBM DB2?
I have written the following code to get past 4 years every first and end of month dates from current date in db2.</p>

```<code>WITH tempdateseries (StartDate,EndDate) AS (
SELECT
    DATE(1) + (YEAR(CURRENT DATE)-5) YEARS AS StartDate,
    LAST_DAY(CURRENT DATE - 4 YEARS) AS EndDate
FROM
    sysibm.sysdummy1
UNION ALL
SELECT
    StartDate + 1 MONTH,
    EndDate
FROM
    tempdateseries
WHERE
    StartDate < LAST_DAY(CURRENT DATE - 1 MONTHS)
    AND EndDate < LAST_DAY(CURRENT DATE - 1 MONTHS))
    SELECT
    *
FROM
    tempdateseries

</code>```

答:
Try this:

```<code>WITH T (STARTDATE) AS
(
VALUES CURRENT DATE - (DAY(CURRENT DATE) - 1) DAY
  UNION ALL
SELECT STARTDATE - 1 MONTH
FROM T
WHERE CURRENT DATE < STARTDATE - 1 MONTH + 4 YEAR
)
SELECT STARTDATE, STARTDATE + 1 MONTH - 1 DAY ENDDATE
FROM T
ORDER BY STARTDATE DESC
FETCH FIRST 5 ROWS ONLY;
</code>```

The result is:

```<code>|STARTDATE |ENDDATE   |
|----------|----------|
|2020-05-01|2020-05-31|
|2020-04-01|2020-04-30|
|2020-03-01|2020-03-31|
|2020-02-01|2020-02-29|
|2020-01-01|2020-01-31|
</code>```

Body:
I have written the following code to get past 4 years every first and end of month dates from current date in db2.

WITH tempdateseries (StartDate,EndDate) AS (
SELECT
    DATE(1) + (YEAR(CURRENT DATE)-5) YEARS AS StartDate,
    LAST_DAY(CURRENT DATE - 4 YEARS) AS EndDate
FROM
    sysibm.sysdummy1
UNION ALL
SELECT
    StartDate + 1 MONTH,
    EndDate
FROM
    tempdateseries
WHERE
    StartDate < LAST_DAY(CURRENT DATE - 1 MONTHS)
    AND EndDate < LAST_DAY(CURRENT DATE - 1 MONTHS))
    SELECT
    *
FROM
    tempdateseries

Body:
Try this:

WITH T (STARTDATE) AS
(
VALUES CURRENT DATE - (DAY(CURRENT DATE) - 1) DAY
  UNION ALL
SELECT STARTDATE - 1 MONTH
FROM T
WHERE CURRENT DATE < STARTDATE - 1 MONTH + 4 YEAR
)
SELECT STARTDATE, STARTDATE + 1 MONTH - 1 DAY ENDDATE
FROM T
ORDER BY STARTDATE DESC
FETCH FIRST 5 ROWS ONLY;

The result is:

|STARTDATE |ENDDATE   |
|----------|----------|
|2020-05-01|2020-05-31|
|2020-04-01|2020-04-30|
|2020-03-01|2020-03-31|
|2020-02-01|2020-02-29|
|2020-01-01|2020-01-31|


问:
Error storing a hdf5 file with a list of strings
```<code>def storeFlagsFile(FLAGS_F, file_name, t0, text, ID):
    if not FLAGS_F:  # this flag doesnt work for mulitple users
        f = h5py.File(file_name, "r+")
        data_content = np.array([np.round(time.time() - t0, 3), text])
        asciiList = np.array([str(n).encode("utf-8", "ignore") for n in data_content]).reshape(1, 2)
        dt = h5py.string_dtype(encoding='utf-8')
        dset = f[str(ID)].create_dataset('AcqFlags', data=asciiList, compression="gzip", chunks=True, maxshape=(None, 2), dtype=dt)
        FLAGS_F = 1
    else:
        f = h5py.File(file_name, "r+")
        data_content = np.array([np.round(time.time() - t0, 3), text])
        asciiList = np.array([str(n).encode("utf-8", "ignore") for n in data_content]).reshape(1, 2)
        f[str(ID)+'/AcqFlags'].resize((f[str(ID)+'/AcqFlags'].shape[0] + 1), axis = 0)
        f[str(ID)+'/AcqFlags'][-1:] = asciiList
</code>```

I want to save a data format like this in the format (None, 2) since I am continually updating the data row per row by calling the storeFlagsFile function.

```<code>['4.412' 'a']
['5.412' 'b']
['6.412' 'c']
['8.226' 'd']
</code>```

in which t0 the first column and text = the second column of the data, which I give as input row per row to storeFlagsFile(FLAGS_F, file_name, t0, text, ID). FLAGS_F is initially 0 and ID = "122".

but I am observing the hdf5 file like this:

Can anyone point me out what I am doing wrong please? Thank you!

答:
It's not clear (to me) why you aren't getting 2 fields in your AcqFlags dataset. I was able to get your code segment to work with a small modification. (I am using h5py 2.9.0. A new dtype was added to h5py 2.10.0 for variable length strings. That change is noted with comments in the dt= declarations. This is not an error in your code.) See below.

```<code>import h5py, numpy as np
import time

def storeFlagsFile(FLAGS_F, file_name, t0, text, ID):
    if not FLAGS_F:  # this flag doesnt work for mulitple users
        with h5py.File(file_name, "r+") as f:
            data_content = np.array([np.round(time.time() - t0, 3), text])
            asciiList = np.array([str(n).encode("utf-8", "ignore") for n in data_content]).reshape(1, 2)
            #dt = h5py.string_dtype(encoding='utf-8') # for h5py 2.10.0
            dt = h5py.special_dtype(vlen=str)   # for h5py 2.9.0
            dset = f[str(ID)].create_dataset('AcqFlags', data=asciiList, compression="gzip", chunks=True, maxshape=(None, 2), dtype=dt)
            FLAGS_F = 1
    else:
        with h5py.File(file_name, "r+") as f:
            data_content = np.array([np.round(time.time() - t0, 3), text])
            asciiList = np.array([str(n).encode("utf-8", "ignore") for n in data_content]).reshape(1, 2)
            f[str(ID)+'/AcqFlags'].resize((f[str(ID)+'/AcqFlags'].shape[0] + 1), axis = 0)
            f[str(ID)+'/AcqFlags'][-1:] = asciiList

file_name = 'SO_62064344.h5'
ID = 122
with h5py.File(file_name, 'w') as f:
    f.create_group(str(ID))

storeFlagsFile(False, file_name, 4.412, 'a', ID)
storeFlagsFile(True, file_name, 5.412, 'b', ID)
storeFlagsFile(True, file_name, 6.412, 'c', ID)
storeFlagsFile(True, file_name, 8.226, 'd', ID)
storeFlagsFile(True, file_name, 9.773, 'e', ID)
</code>```

Additional thoughts/observations:

I noticed you are storing the time value as a string. Is that what you want? HDF5 and h5py can store different datatypes in each field/column, so you can mix floats and and strings if you want. It requires a different dtype (like a record array).

You use FLAGS_F as a flag to create the AcqFlags dataset. You can simplify this to test for existence, or use require_dataset.

You are adding 1 row at a time to a resizable dataset. This is OK for "smallish" datasets, but could be a performance problem if you create 10e6 rows 1 row at a time.

If you are interested, I answered other questions that shows how to do #2 and #3 above. You might find one of these answers helpful:

How to configure maxshape argument for H5 and append to file?

Resizing and storing dataset in .h5 format

Body:
def storeFlagsFile(FLAGS_F, file_name, t0, text, ID):
    if not FLAGS_F:  # this flag doesnt work for mulitple users
        f = h5py.File(file_name, "r+")
        data_content = np.array([np.round(time.time() - t0, 3), text])
        asciiList = np.array([str(n).encode("utf-8", "ignore") for n in data_content]).reshape(1, 2)
        dt = h5py.string_dtype(encoding='utf-8')
        dset = f[str(ID)].create_dataset('AcqFlags', data=asciiList, compression="gzip", chunks=True, maxshape=(None, 2), dtype=dt)
        FLAGS_F = 1
    else:
        f = h5py.File(file_name, "r+")
        data_content = np.array([np.round(time.time() - t0, 3), text])
        asciiList = np.array([str(n).encode("utf-8", "ignore") for n in data_content]).reshape(1, 2)
        f[str(ID)+'/AcqFlags'].resize((f[str(ID)+'/AcqFlags'].shape[0] + 1), axis = 0)
        f[str(ID)+'/AcqFlags'][-1:] = asciiList

I want to save a data format like this in the format (None, 2) since I am continually updating the data row per row by calling the storeFlagsFile function.

['4.412' 'a']
['5.412' 'b']
['6.412' 'c']
['8.226' 'd']

in which t0 the first column and text = the second column of the data, which I give as input row per row to storeFlagsFile(FLAGS_F, file_name, t0, text, ID). FLAGS_F is initially 0 and ID = "122".

but I am observing the hdf5 file like this:

Can anyone point me out what I am doing wrong please? Thank you!

Body:
It's not clear (to me) why you aren't getting 2 fields in your AcqFlags dataset. I was able to get your code segment to work with a small modification. (I am using h5py 2.9.0. A new dtype was added to h5py 2.10.0 for variable length strings. That change is noted with comments in the dt= declarations. This is not an error in your code.) See below.

import h5py, numpy as np
import time

def storeFlagsFile(FLAGS_F, file_name, t0, text, ID):
    if not FLAGS_F:  # this flag doesnt work for mulitple users
        with h5py.File(file_name, "r+") as f:
            data_content = np.array([np.round(time.time() - t0, 3), text])
            asciiList = np.array([str(n).encode("utf-8", "ignore") for n in data_content]).reshape(1, 2)
            #dt = h5py.string_dtype(encoding='utf-8') # for h5py 2.10.0
            dt = h5py.special_dtype(vlen=str)   # for h5py 2.9.0
            dset = f[str(ID)].create_dataset('AcqFlags', data=asciiList, compression="gzip", chunks=True, maxshape=(None, 2), dtype=dt)
            FLAGS_F = 1
    else:
        with h5py.File(file_name, "r+") as f:
            data_content = np.array([np.round(time.time() - t0, 3), text])
            asciiList = np.array([str(n).encode("utf-8", "ignore") for n in data_content]).reshape(1, 2)
            f[str(ID)+'/AcqFlags'].resize((f[str(ID)+'/AcqFlags'].shape[0] + 1), axis = 0)
            f[str(ID)+'/AcqFlags'][-1:] = asciiList

file_name = 'SO_62064344.h5'
ID = 122
with h5py.File(file_name, 'w') as f:
    f.create_group(str(ID))

storeFlagsFile(False, file_name, 4.412, 'a', ID)
storeFlagsFile(True, file_name, 5.412, 'b', ID)
storeFlagsFile(True, file_name, 6.412, 'c', ID)
storeFlagsFile(True, file_name, 8.226, 'd', ID)
storeFlagsFile(True, file_name, 9.773, 'e', ID)

Additional thoughts/observations:

I noticed you are storing the time value as a string. Is that what you want? HDF5 and h5py can store different datatypes in each field/column, so you can mix floats and and strings if you want. It requires a different dtype (like a record array).

You use FLAGS_F as a flag to create the AcqFlags dataset. You can simplify this to test for existence, or use require_dataset.

You are adding 1 row at a time to a resizable dataset. This is OK for "smallish" datasets, but could be a performance problem if you create 10e6 rows 1 row at a time.

If you are interested, I answered other questions that shows how to do #2 and #3 above. You might find one of these answers helpful:

How to configure maxshape argument for H5 and append to file?

Resizing and storing dataset in .h5 format


问:
Replacing strings with values from dictionary using random.sample
Suppose I'm creating a madLib and i want to replace each word from a string that has the word 'plural noun'. Basically, the user gets a prompt that states to input plural nouns and those inputs the go to a dictionary (pluralnoDict).

I've been using random.choice, and it's been working out, however, the repeats is obviously the issue. I tried random.sample, however, instead of choosing one word from a given sample, the code replaces the words with the whole sample.

Is there a way I can replace each string using random.sample from a dictionary list? For example:

Original: The 'plural noun' have 'plural noun' and 'plural noun'.
Expected: The 'birds' have 'wings' and 'feet'.

Below is the for loop i use to replace the plural noun strings.

```<code>for key in pluralnoDict:
        target_word = "({0})".format(key)
        while target_word in madString:
            madString = madString.replace(target_word, random.choice(pluralnoDict[key]), 1)
</code>```

答:
If you want to use all of the nouns, but in a random order, you could use random.shuffle and do something like:

from random import shuffle

target_word = "plural noun"
mad_str = "The 'plural noun' have 'plural noun' and 'plural noun'"
plural_nouns = ["birds", "feet", "wings"]
shuffle(plural_nouns)
for noun in plural_nouns:
    mad_str = mad_str.replace(target_word, noun, 1)
print(mad_str)
```

Body:
Suppose I'm creating a madLib and i want to replace each word from a string that has the word 'plural noun'. Basically, the user gets a prompt that states to input plural nouns and those inputs the go to a dictionary (pluralnoDict).

I've been using random.choice, and it's been working out, however, the repeats is obviously the issue. I tried random.sample, however, instead of choosing one word from a given sample, the code replaces the words with the whole sample.

Is there a way I can replace each string using random.sample from a dictionary list? For example:

Original: The 'plural noun' have 'plural noun' and 'plural noun'.
Expected: The 'birds' have 'wings' and 'feet'.

Below is the for loop i use to replace the plural noun strings.

for key in pluralnoDict:
        target_word = "({0})".format(key)
        while target_word in madString:
            madString = madString.replace(target_word, random.choice(pluralnoDict[key]), 1)


问:
Onclick function is Not Working on my AMP Site
HTML code:

```<code><span class="button-text" style="font-size: 12pt;">
    <a onclick="AboNewsletterFunction()" id="clickButton">
        <span class="label" style="font-size: 10pt;"> Abonnieren sie unseren Newsletter </span>
    </a>
</span>
</code>```

and than in the

答:
Inline Scripts are also not allowed in amp you can check for 'Actions and Events' of amp.

https://amp.dev/documentation/guides-and-tutorials/learn/amp-actions-and-events/?format=websites.

OR else you can use amp-scripts where you can add add addEventListener for a click event.

Body:
HTML code:

         Abonnieren sie unseren Newsletter

and than in the


问:
How to group elements inside select element inside React JS?
Here is a codesandbox url for the working demo of the grouping of elements with react.

So my requirement is that once the user clicks on the drop down, the user can see the list of items which are grouped.

In this list is only one Group 1, so the list Group 1 is
coming but also one group is coming as undefined How can I
remove the undefined as group inside the drop down list and
whatever items are inside the undefined should be give some
padding-right.

I have already given the style mycustomselect inside
style.css but it still takes the default style. I want to remove the color green which is coming as the default.

Thanks and Regards.

答:
If you want to remove that undefined you can put a condition on the name and you can choose a name that will be displayed instead of undefined</p>

```<code>startDatePurchaseBehavior.forEach(option => {
          let val = option.optgroup
          if(!val){
            val = "No Group"
          }
          if (!groupedOptions[val]) groupedOptions[val] = [];
          groupedOptions[val].push({
            value: option.value,
            text: option.text
          });
        });
</code>```

Body:
If you want to remove that undefined you can put a condition on the name and you can choose a name that will be displayed instead of undefined

startDatePurchaseBehavior.forEach(option => {
          let val = option.optgroup
          if(!val){
            val = "No Group"
          }
          if (!groupedOptions[val]) groupedOptions[val] = [];
          groupedOptions[val].push({
            value: option.value,
            text: option.text
          });
        });


问:
How to get json response from inside the page from Webview(I get a response with user-agent)?
Json i want to get is here, I want to keep this json

```<code>private void logData(WebView view, final String url) {
    view.evaluateJavascript("document.documentElement.outerHTML.toString()", new ValueCallback<String>() {
        @Override
        public void onReceiveValue(String value) {

            Ion.with(context).load(url).asString().setCallback(new FutureCallback<String>() {
                @Override
                public void onCompleted(Exception e, String result) {

                    if (result != null && result.length() > 0) {

                        int maxLogSize = 1000;
                        for (int i = 0; i <= result.length() / maxLogSize; i++) {
                            int start = i * maxLogSize;
                            int end = (i + 1) * maxLogSize;
                            end = Math.min(end, result.length());
                            Log.v("LoggedHTML", result.substring(start, end));
                        }

                    }
                }
            });

        }
    })
}
</code>```

this code gives me the html document of the page, i want to print json

答:
```<code>WebViewClient yourWebClient = new WebViewClient() {

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        return false;
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        wb.loadUrl("javascript:HtmlViewer.showHTML" +
                "('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>');");
    }
};
wb = (WebView) findViewById(R.id.webview);
wb.getSettings().setJavaScriptEnabled(true);
wb.getSettings().setSupportZoom(true);
wb.getSettings().setBuiltInZoomControls(true);
wb.setWebViewClient(yourWebClient);
wb.loadUrl("http://pqrs.abcde.com/facebook");
wb.addJavascriptInterface(new MyJavaScriptInterface(this), "HtmlViewer");
</code>```

Body:
Json i want to get is here, I want to keep this json

private void logData(WebView view, final String url) {
    view.evaluateJavascript("document.documentElement.outerHTML.toString()", new ValueCallback<String>() {
        @Override
        public void onReceiveValue(String value) {

            Ion.with(context).load(url).asString().setCallback(new FutureCallback<String>() {
                @Override
                public void onCompleted(Exception e, String result) {

                    if (result != null && result.length() > 0) {

                        int maxLogSize = 1000;
                        for (int i = 0; i <= result.length() / maxLogSize; i++) {
                            int start = i * maxLogSize;
                            int end = (i + 1) * maxLogSize;
                            end = Math.min(end, result.length());
                            Log.v("LoggedHTML", result.substring(start, end));
                        }

                    }
                }
            });

        }
    })
}

this code gives me the html document of the page, i want to print json


问:
unindent does not match any outer indentation level error when compiling the Python code
Error:

```<code>unindent does not match any outer indentation level
</code>```

Code:

```<code>def confirmation(self):
    if WebDriverWait(self.driver, 1000).until(
EC.visibility_of_element_located((By.CLASS_NAME, 'failed'))):
        print("Checkout Failed!")

     if WebDriverWait(self.driver, 1000).until(
EC.visibility_of_element_located((By.CLASS_NAME, 'succesful'))):
        print("Checkout Succesful!")
</code>```

How can I address the error?

答:
This error message...

```<code>unindent does not match any outer indentation level
</code>```

...implies that there is a problem with the indentation in your code block.

This error is mostly observed when there is a mixup of Tab and Space characters while indenting Python code.

Analysis

When I copied you code block and executed:

I got the same error:

```<code>C:\Users\username\Desktop\directory\PyPrograms>class_in_python.py
  File "C:\Users\Soma Bhattacharjee\Desktop\Debanjan\PyPrograms\class_in_python.py", line 26
    def confirmation(self):
              ^
IndentationError: unindent does not match any outer indentation level
</code>```

Once, I removed all the white paces and the new line character and break up the line again for the following line of code, the default indentation seems to be different:

```<code>     if WebDriverWait(self.driver, 1000).until(
        EC.visibility_of_element_located((By.CLASS_NAME, 'succesful'))):
        print("Checkout Succesful!")
</code>```

Solution

You need to fix up the indentation of the following lines:

EC.visibility_of_element_located((By.CLASS_NAME, 'failed'))):

EC.visibility_of_element_located((By.CLASS_NAME, 'succesful'))):

You can find a relevant detailed discussion in Is there something issue in indentation, while using Anaconda's Spyder

Body:
Error:

unindent does not match any outer indentation level

Code:

def confirmation(self):
    if WebDriverWait(self.driver, 1000).until(
EC.visibility_of_element_located((By.CLASS_NAME, 'failed'))):
        print("Checkout Failed!")

     if WebDriverWait(self.driver, 1000).until(
EC.visibility_of_element_located((By.CLASS_NAME, 'succesful'))):
        print("Checkout Succesful!")

How can I address the error?

Body:
This error message...

unindent does not match any outer indentation level

...implies that there is a problem with the indentation in your code block.

This error is mostly observed when there is a mixup of Tab and Space characters while indenting Python code.

Analysis

When I copied you code block and executed:

I got the same error:

C:\Users\username\Desktop\directory\PyPrograms>class_in_python.py
  File "C:\Users\Soma Bhattacharjee\Desktop\Debanjan\PyPrograms\class_in_python.py", line 26
    def confirmation(self):
              ^
IndentationError: unindent does not match any outer indentation level

Once, I removed all the white paces and the new line character and break up the line again for the following line of code, the default indentation seems to be different:

     if WebDriverWait(self.driver, 1000).until(
        EC.visibility_of_element_located((By.CLASS_NAME, 'succesful'))):
        print("Checkout Succesful!")

Solution

You need to fix up the indentation of the following lines:

EC.visibility_of_element_located((By.CLASS_NAME, 'failed'))):

EC.visibility_of_element_located((By.CLASS_NAME, 'succesful'))):

You can find a relevant detailed discussion in Is there something issue in indentation, while using Anaconda's Spyder


问:
edit pvc from ReadWriteOnce to ReadWriteMany
We have pvc with access policy

```<code>     accessModes:
      - ReadWriteOnce
</code>```

we want to change it to ReadWriteMany does it possible to edit pvc without deleting it?

I know I can create it with deleting it but I dont want to delete it.

I checked this answer but it didn't helped me. This is oppsite of my use case.

答:
I tried editing it using kubectl edit pvc <pvc_name> and this is the output of the error when submititng changes:

```<code>persistentvolumeclaims "task-pv-claim" was not valid:
spec: Forbidden: is immutable after creation except resources.requests for bound claims
</code>```

This means you cannot edit claim after it has been created, either using kubectl edit nor kubectl patch.

Body:
We have pvc with access policy

     accessModes:
      - ReadWriteOnce

we want to change it to ReadWriteMany does it possible to edit pvc without deleting it?

I know I can create it with deleting it but I dont want to delete it.

I checked this answer but it didn't helped me. This is oppsite of my use case.

Body:
I tried editing it using kubectl edit pvc <pvc_name> and this is the output of the error when submititng changes:

persistentvolumeclaims "task-pv-claim" was not valid:
spec: Forbidden: is immutable after creation except resources.requests for bound claims

This means you cannot edit claim after it has been created, either using kubectl edit nor kubectl patch.


问:
Android 10 permission denied
When I try to send an image to the server I get an error. On a device with Android 6 and Android 9, everything works well. But when I use a device with Android 10 or BlueStacks 4 emulator I get an error. My Manifesto looks like this:

```<code><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
</code>```

I also tried adding the following tag to the manifest: android:requestLegacyExternalStorage="true"
but my problem remains. In the logs I get an error that the Compressor library gets null

My Activity:

```<code>override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)

        when (requestCode) {
            PermUtil.REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS -> {
                if (grantResults.isEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Pix.start(this, Options.init().setRequestCode(100));
                } else {
                    ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL)
                    Toast.makeText(
                        this, "Approve permissions to open Pix ImagePicker",
                        Toast.LENGTH_LONG).show();
                }
            }
        }
    }
</code>```

// Function that causes an error

```<code>override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {

            Constants.ACTION_REQUEST_CAMERA ->{
                if (resultCode == Activity.RESULT_OK){

                    returnValue = data!!.getStringArrayListExtra(Pix.IMAGE_RESULTS)!!

                        val f = File(returnValue[0])
                        photoFile = Compressor(this).compressToFile(f)

                    Toast.makeText(this, f.toString(), Toast.LENGTH_LONG).show()
                }
            }
        }
    }
</code>```

Logcat:

```<code>java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { (has extras) }} to activity {com.example.foodstationapp/com.example.foodstationapp.activities.RegisterActivity}: java.io.FileNotFoundException: /storage/emulated/0/WhatsApp/Media/WhatsApp Images/IMG-20200527-WA0000.jpg: open failed: EACCES (Permission denied)
    at android.app.ActivityThread.deliverResults(ActivityThread.java:4905)
    at android.app.ActivityThread.handleSendResult(ActivityThread.java:4946)
    at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51)
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2040)
    at android.os.Handler.dispatchMessage(Handler.java:107)
    at android.os.Looper.loop(Looper.java:224)
    at android.app.ActivityThread.main(ActivityThread.java:7520)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
Caused by: java.io.FileNotFoundException: /storage/emulated/0/WhatsApp/Media/WhatsApp Images/IMG-20200527-WA0000.jpg: open failed: EACCES (Permission denied)
    at libcore.io.IoBridge.open(IoBridge.java:496)
    at java.io.FileInputStream.<init>(FileInputStream.java:159)
    at java.io.FileInputStream.<init>(FileInputStream.java:115)
    at android.media.ExifInterface.initForFilename(ExifInterface.java:2297)
    at android.media.ExifInterface.<init>(ExifInterface.java:1386)
    at id.zelory.compressor.ImageUtil.decodeSampledBitmapFromFile(ImageUtil.java:60)
    at id.zelory.compressor.ImageUtil.compressImage(ImageUtil.java:33)
    at id.zelory.compressor.Compressor.compressToFile(Compressor.java:60)
    at id.zelory.compressor.Compressor.compressToFile(Compressor.java:56)
    at com.example.foodstationapp.activities.RegisterActivity.onActivityResult(RegisterActivity.kt:268)
    at android.app.Activity.dispatchActivityResult(Activity.java:8249)
    at android.app.ActivityThread.deliverResults(ActivityThread.java:4898)
    ... 11 more
Caused by: android.system.ErrnoException: open failed: EACCES (Permission denied)
    at libcore.io.Linux.open(Native Method)
    at libcore.io.ForwardingOs.open(ForwardingOs.java:167)
    at libcore.io.BlockGuardOs.open(BlockGuardOs.java:252)
    at libcore.io.ForwardingOs.open(ForwardingOs.java:167)
    at android.app.ActivityThread$AndroidOs.open(ActivityThread.java:7419)
    at libcore.io.IoBridge.open(IoBridge.java:482)
    ... 22 more
</code>```

答:
With every new Android version Google makes it harder/impossible to use java- File class. Google wants you to use contentprovider with InputStream or OutputStream instead.

If you get the photo of your crash-stacktrace "/storage/emulated/0/WhatsApp/Media/WhatsApp Images/IMG-20200527-WA0000.jpg" from a gallery or image picker use the original "content:...." uri and load the image through

context.getContentResolver().openInputStream(contentUri);

update:

library 'com.fxn769:pix' = https://github.com/akshay2211/PixImagePicker. It is currently not working any more on android-10: See https://github.com/akshay2211/PixImagePicker/issues/103

The android way (since android-4.4) to pick an image is

```<code>Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"),
       PICK_IMAGE);
</code>```

where you get a "content:"-uri in onActivityResult that you can open through  contentresolver

Title: Android 10 permission denied

Body:
When I try to send an image to the server I get an error. On a device with Android 6 and Android 9, everything works well. But when I use a device with Android 10 or BlueStacks 4 emulator I get an error. My Manifesto looks like this:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

I also tried adding the following tag to the manifest: android:requestLegacyExternalStorage="true"
but my problem remains. In the logs I get an error that the Compressor library gets null

My Activity:

override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)

        when (requestCode) {
            PermUtil.REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS -> {
                if (grantResults.isEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Pix.start(this, Options.init().setRequestCode(100));
                } else {
                    ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL)
                    Toast.makeText(
                        this, "Approve permissions to open Pix ImagePicker",
                        Toast.LENGTH_LONG).show();
                }
            }
        }
    }

// Function that causes an error

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {

            Constants.ACTION_REQUEST_CAMERA ->{
                if (resultCode == Activity.RESULT_OK){

                    returnValue = data!!.getStringArrayListExtra(Pix.IMAGE_RESULTS)!!

                        val f = File(returnValue[0])
                        photoFile = Compressor(this).compressToFile(f)

                    Toast.makeText(this, f.toString(), Toast.LENGTH_LONG).show()
                }
            }
        }
    }

Logcat:

java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { (has extras) }} to activity {com.example.foodstationapp/com.example.foodstationapp.activities.RegisterActivity}: java.io.FileNotFoundException: /storage/emulated/0/WhatsApp/Media/WhatsApp Images/IMG-20200527-WA0000.jpg: open failed: EACCES (Permission denied)
    at android.app.ActivityThread.deliverResults(ActivityThread.java:4905)
    at android.app.ActivityThread.handleSendResult(ActivityThread.java:4946)
    at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51)
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2040)
    at android.os.Handler.dispatchMessage(Handler.java:107)
    at android.os.Looper.loop(Looper.java:224)
    at android.app.ActivityThread.main(ActivityThread.java:7520)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
Caused by: java.io.FileNotFoundException: /storage/emulated/0/WhatsApp/Media/WhatsApp Images/IMG-20200527-WA0000.jpg: open failed: EACCES (Permission denied)
    at libcore.io.IoBridge.open(IoBridge.java:496)
    at java.io.FileInputStream.<init>(FileInputStream.java:159)
    at java.io.FileInputStream.<init>(FileInputStream.java:115)
    at android.media.ExifInterface.initForFilename(ExifInterface.java:2297)
    at android.media.ExifInterface.<init>(ExifInterface.java:1386)
    at id.zelory.compressor.ImageUtil.decodeSampledBitmapFromFile(ImageUtil.java:60)
    at id.zelory.compressor.ImageUtil.compressImage(ImageUtil.java:33)
    at id.zelory.compressor.Compressor.compressToFile(Compressor.java:60)
    at id.zelory.compressor.Compressor.compressToFile(Compressor.java:56)
    at com.example.foodstationapp.activities.RegisterActivity.onActivityResult(RegisterActivity.kt:268)
    at android.app.Activity.dispatchActivityResult(Activity.java:8249)
    at android.app.ActivityThread.deliverResults(ActivityThread.java:4898)
    ... 11 more
Caused by: android.system.ErrnoException: open failed: EACCES (Permission denied)
    at libcore.io.Linux.open(Native Method)
    at libcore.io.ForwardingOs.open(ForwardingOs.java:167)
    at libcore.io.BlockGuardOs.open(BlockGuardOs.java:252)
    at libcore.io.ForwardingOs.open(ForwardingOs.java:167)
    at android.app.ActivityThread$AndroidOs.open(ActivityThread.java:7419)
    at libcore.io.IoBridge.open(IoBridge.java:482)
    ... 22 more

Body:
With every new Android version Google makes it harder/impossible to use java- File class. Google wants you to use contentprovider with InputStream or OutputStream instead.

If you get the photo of your crash-stacktrace "/storage/emulated/0/WhatsApp/Media/WhatsApp Images/IMG-20200527-WA0000.jpg" from a gallery or image picker use the original "content:...." uri and load the image through

context.getContentResolver().openInputStream(contentUri);

update:

library 'com.fxn769:pix' = https://github.com/akshay2211/PixImagePicker. It is currently not working any more on android-10: See https://github.com/akshay2211/PixImagePicker/issues/103

The android way (since android-4.4) to pick an image is

Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"),
       PICK_IMAGE);

where you get a "content:"-uri in onActivityResult that you can open through  contentresolver


问:
Flutter: Minimum height on horizontal list view
I'm trying to create a horizontal scrolling list of items in Flutter, and I want that list to only take up the necessary height based on its children. By design “ListView tries to expand to fit the space available in its cross-direction” (from the Flutter docs), which I also notice in that it takes up the whole height of the viewport, but is there a way to make it not do this? Ideally something similar to this (which obviously doesn't work):

new ListView(
  scrollDirection: Axis.horizontal,
  crossAxisSize: CrossAxisSize.min,
  children: <Widget>[
    new ListItem(),
    new ListItem(),
    // ...
  ],
);
```

<hr>

<p>I realize that one way to do this is by wrapping the <code>ListView</code> in a <code>Container</code> with a fixed height. However, I don't necessarily know the height of the items:</p>

<pre class="lang-dart prettyprint-override"><code>new Container(
  height: 97.0,
  child: new ListView(
    scrollDirection: Axis.horizontal,
    children: <Widget>[
      new ListItem(),
      new ListItem(),
      // ...
    ],
  ),
);
</code>```

I was able to hack together a “solution” by nesting a Row in a SingleChildScrollView in a Column with a mainAxisSize: MainAxisSize.min. However, this doesn't feel like a solution, to me:

new Column(
  mainAxisSize: MainAxisSize.min,
  children: <Widget>[
    new SingleChildScrollView(
      scrollDirection: Axis.horizontal,
      child: new Row(
        children: <Widget>[
          new ListItem(),
          new ListItem(),
          // ...
        ],
      ),
    ),
  ],
);
```

答:
Wrapping the widget by Column with mainAxisSize: MainAxisSize.min worked for me. You can try to change the height here.

var data = [
      {'name': 'Shopping', 'icon': Icons.local_shipping},
      {'name': 'Service', 'icon': Icons.room_service},
      {'name': 'Hotel', 'icon': Icons.hotel},
      {'name': 'More', 'icon': Icons.more}
];

new Container(
        constraints: new BoxConstraints(
          minHeight: 40.0,
          maxHeight: 60.0,
        ),
        color: Colors.transparent,
        child: new ListView(
          scrollDirection: Axis.horizontal,
          children: data
              .map<Widget>((e) => Column(
                    mainAxisSize: MainAxisSize.min,
                    children: <Widget>[
                      new Container(
                        width: 40,
                        height: 50, // try to change this.
                        color: Colors.transparent,
                        margin: EdgeInsets.only(right: 20, left: 4),
                        child: ClipOval(
                          child: Container(
                            padding: EdgeInsets.all(4),
                            color: Colors.white,
                            child: Icon(
                              e["icon"],
                              color: Colors.grey,
                              size: 30,
                            ),
                          ),
                        ),
                      ),
                    ],
                  ))
              .toList(),
        ));
```

Body:
I'm trying to create a horizontal scrolling list of items in Flutter, and I want that list to only take up the necessary height based on its children. By design “ListView tries to expand to fit the space available in its cross-direction” (from the Flutter docs), which I also notice in that it takes up the whole height of the viewport, but is there a way to make it not do this? Ideally something similar to this (which obviously doesn't work):

new ListView(
  scrollDirection: Axis.horizontal,
  crossAxisSize: CrossAxisSize.min,
  children: <Widget>[
    new ListItem(),
    new ListItem(),
    // ...
  ],
);

I realize that one way to do this is by wrapping the ListView in a Container with a fixed height. However, I don't necessarily know the height of the items:

new Container(
  height: 97.0,
  child: new ListView(
    scrollDirection: Axis.horizontal,
    children: <Widget>[
      new ListItem(),
      new ListItem(),
      // ...
    ],
  ),
);

I was able to hack together a “solution” by nesting a Row in a SingleChildScrollView in a Column with a mainAxisSize: MainAxisSize.min. However, this doesn't feel like a solution, to me:

new Column(
  mainAxisSize: MainAxisSize.min,
  children: <Widget>[
    new SingleChildScrollView(
      scrollDirection: Axis.horizontal,
      child: new Row(
        children: <Widget>[
          new ListItem(),
          new ListItem(),
          // ...
        ],
      ),
    ),
  ],
);


问:
Expression based on class of an object in Scala
I am trying to write an expression based on the class of an object.

```<code>case class Fork(left: CodeTree, right: CodeTree, chars: List[Char], weight: Int) extends CodeTree
case class Leaf(char: Char, weight: Int) extends CodeTree

val l1 = new Leaf('A', 1)
val l2 = new Leaf('B', 1)

val f1 = new Fork(l1, l2, List(l1.char, l2.char), l1.weight + l2.weight)
</code>```

I have tried two methods, but those of them have issues.

Method 1:

```<code>val w: Int = f1 match {

  case Fork(_, _, _, w) => println("I am a fork")
  case Leaf(_, w) => println("I am a Leaf")
}
</code>```

Error received:

```<code>Error:(15, 8) constructor cannot be instantiated to expected type;
found   : Leaf
required: Fork
case Leaf(_, w) => {w}
</code>```

Method 2:

if (l1.isInstanceOf[Fork]) println("I am a fork") else println("I am a leaf")

Warning received:

```<code>Warning:(10, 20) fruitless type test: a value of type Leaf cannot also be a Fork
if (l1.isInstanceOf[Fork]) println("I am a fork") else println("I am a leaf")
</code>```

答:
It is just a warning because the compiler knows that f1 is always fork and is telling you, that you are basically doing if (true)

Code that would work for you is:

val f1: CodeTree = new Fork(l1, l2, List(l1.char, l2.char), l1.weight + l2.weight)

val w = f1 match {
   case f: Fork => println("I am a fork")
   case l: Leaf => println("I am a Leaf")
}
```

<ul>
<li>I have annotated the f1 to <code>CodeTree</code> type</li>
<li>I have removed the annotation of <code>w</code></li>
</ul>

<p>then you can modify to whatever:</p>

<pre class="lang-scala prettyprint-override"><code>val w = f1 match {
   case f: Fork => f.weight
   case l: Leaf => l.weight
}
</code>```

Body:
I am trying to write an expression based on the class of an object.

case class Fork(left: CodeTree, right: CodeTree, chars: List[Char], weight: Int) extends CodeTree
case class Leaf(char: Char, weight: Int) extends CodeTree

val l1 = new Leaf('A', 1)
val l2 = new Leaf('B', 1)

val f1 = new Fork(l1, l2, List(l1.char, l2.char), l1.weight + l2.weight)

I have tried two methods, but those of them have issues.

Method 1:

val w: Int = f1 match {

  case Fork(_, _, _, w) => println("I am a fork")
  case Leaf(_, w) => println("I am a Leaf")
}

Error received:

Error:(15, 8) constructor cannot be instantiated to expected type;
found   : Leaf
required: Fork
case Leaf(_, w) => {w}

Method 2:

if (l1.isInstanceOf[Fork]) println("I am a fork") else println("I am a leaf")

Warning received:

Warning:(10, 20) fruitless type test: a value of type Leaf cannot also be a Fork
if (l1.isInstanceOf[Fork]) println("I am a fork") else println("I am a leaf")

Body:
It is just a warning because the compiler knows that f1 is always fork and is telling you, that you are basically doing if (true)

Code that would work for you is:

val f1: CodeTree = new Fork(l1, l2, List(l1.char, l2.char), l1.weight + l2.weight)

val w = f1 match {
   case f: Fork => println("I am a fork")
   case l: Leaf => println("I am a Leaf")
}

I have annotated the f1 to CodeTree type

I have removed the annotation of w

then you can modify to whatever:

val w = f1 match {
   case f: Fork => f.weight
   case l: Leaf => l.weight
}


问:
How to pass multiple template files to user_Data variable in terraform
assign multiple templates files to user_Data variable.
we dont want to merge this template in single file due to some architectural pattern . </p>

<p>I'm new to terraform so struggling on this. </p>

```<code>data "template_file" "userdata_lin1" {
  template = <<EOF
#!/bin/bash
crontab cronjobfileremote
EOF
}

data "template_file" "userdata_lin2" {
  template = <<EOF
#!/bin/bash
echo "hello"
EOF
}

 user_data  = "${data.template_file.user_data1.rendered}"
</code>```

答:
What I've done in the past is to combine two template files in one.

Like this:

```<code>data "template_file" "userdata" {
  template = "${format("%s%s", file("${path.module}/../common.sh"), file("${path.module}/fo.sh"))}"

  vars {
    efs_url     = "${var.efs_url}"
    hostname    = "${data.template_file.hostname.rendered}"
    api_key     = "${var.api_key}"
  }
}
</code>```

As you can see I'm combining two template files:

../common.sh

fo.sh

In my case, this was part of a project with multiple terraform modules common.sh was in the parent folder and contained everything that was needed for all the child modules, then each module added it's own specific requirements.

You can also see that one of the variables for interpolation is also a template_file:

hostname    = "${data.template_file.hostname.rendered}"

That is perfectly fine and helps nesting templates. Just in case if you need it...

Body:
assign multiple templates files to user_Data variable.
we dont want to merge this template in single file due to some architectural pattern .

I'm new to terraform so struggling on this.

data "template_file" "userdata_lin1" {
  template = <<EOF
#!/bin/bash
crontab cronjobfileremote
EOF
}

data "template_file" "userdata_lin2" {
  template = <<EOF
#!/bin/bash
echo "hello"
EOF
}

 user_data  = "${data.template_file.user_data1.rendered}"

Body:
What I've done in the past is to combine two template files in one.

Like this:

data "template_file" "userdata" {
  template = "${format("%s%s", file("${path.module}/../common.sh"), file("${path.module}/fo.sh"))}"

  vars {
    efs_url     = "${var.efs_url}"
    hostname    = "${data.template_file.hostname.rendered}"
    api_key     = "${var.api_key}"
  }
}

As you can see I'm combining two template files:

../common.sh

fo.sh

In my case, this was part of a project with multiple terraform modules common.sh was in the parent folder and contained everything that was needed for all the child modules, then each module added it's own specific requirements.

You can also see that one of the variables for interpolation is also a template_file:

hostname    = "${data.template_file.hostname.rendered}"

That is perfectly fine and helps nesting templates. Just in case if you need it...


问:
Get the full size icons of the Trash can
I am trying to display the icons of the Trash can in my app, both empty and full. I've tried several methods to get the icons, but each time the size is 32x32. Do you know a way to get a full size image?</p>

答:
I assume that you’re getting the trash icon through NSWorkspace, using the kTrashIcon constant from IconsCore.h (if you’re not, this is :

```<code>NSImage* image = [[NSWorkspace sharedWorkspace] iconForFileType:NSFileTypeForHFSTypeCode(kTrashIcon)];
</code>```

…this NSImage contains representations in a number of different sizes. If you want the biggest one, just iterate through the available representations to find it:

```<code>NSEnumerator* representationEnumerator = [[image representations] objectEnumerator];
NSSize biggestSize = NSMakeSize(0, 0);
NSSize size;
while ((size = [(NSImageRep*)[representationEnumerator nextObject] size]).width) {
    if (size.width > biggestSize.width) {
        biggestSize = size;
    }
}
[image setSize:biggestSize];
</code>```

…On my computer, this results in an NSImage set to 512x512.

Body:
I assume that you’re getting the trash icon through NSWorkspace, using the kTrashIcon constant from IconsCore.h (if you’re not, this is :

NSImage* image = [[NSWorkspace sharedWorkspace] iconForFileType:NSFileTypeForHFSTypeCode(kTrashIcon)];

…this NSImage contains representations in a number of different sizes. If you want the biggest one, just iterate through the available representations to find it:

NSEnumerator* representationEnumerator = [[image representations] objectEnumerator];
NSSize biggestSize = NSMakeSize(0, 0);
NSSize size;
while ((size = [(NSImageRep*)[representationEnumerator nextObject] size]).width) {
    if (size.width > biggestSize.width) {
        biggestSize = size;
    }
}
[image setSize:biggestSize];

…On my computer, this results in an NSImage set to 512x512.


问:
Format a text box to display user input on runtime in form of thousand separator number with decimals
i am still new to c# , i am trying to build a simple calculator with c# windows form.
i did all the coding but i am stuck in formating my calculator screen(text box in this case) to display numbers with thousand separator comma and decimal point.

for example: if the user input 1000 i want it to display 1,000 of if the user input 1000.0123 i want it to display 1,000.0123 on the fly(just like the windows 10 calculator)

i really appreciate the any help , i have been searching all around the internet for some solution and came to nothing

答:
use string format, in the textbox where you show the numbers :

```<code>txtNumber.text = string.Format("{0:n}",12521452.646521); // 12,521,452.64
</code>```

or :

```<code>txtNumber.text = string.Format("{0:#,0.#########}", 12521452.646521))   // 12,521,452.646521
</code>```

see more :
C# String Format Method

Body:
use string format, in the textbox where you show the numbers :

txtNumber.text = string.Format("{0:n}",12521452.646521); // 12,521,452.64

or :

txtNumber.text = string.Format("{0:#,0.#########}", 12521452.646521))   // 12,521,452.646521

see more :
C# String Format Method


问:
Sort XML sections using XSLT
I would like to sort the dependent_information sections in below xml based on date_of_birth field.
Tried below script but it skips other sections like personal_information/employment_information etc

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()" />
        </xsl:copy>
    </xsl:template>
    <xsl:template match="//CompoundEmployee/person">
        <xsl:copy>
            <xsl:apply-templates select="dependent_information">
                <xsl:sort select="date_of_birth" data-type="text" order="ascending"/>
            </xsl:apply-templates>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>
</code>```

Below is the structure of my xml

```<code><?xml version='1.0' encoding='UTF-8'?>
<queryCompoundEmployeeResponse>
    <CompoundEmployee>
        <id>22201</id>
        <person>
            <person_id_external>560706</person_id_external>
            <personal_information>
                <first_name>James</first_name>
                <last_name>Tester</last_name>
            </personal_information>
            <employment_information>
                <employment_id>21960</employment_id>
                <start_date>2020-05-01</start_date>
            </employment_information>
            <dependent_information>
                <date_of_birth>2009-05-04</date_of_birth>
                <person_id_external>560706_d0</person_id_external>
            </dependent_information>
            <dependent_information>
                <date_of_birth>2004-01-31</date_of_birth>
                <person_id_external>560706_d0</person_id_external>
            </dependent_information>
            <dependent_information>
                <date_of_birth>2019-06-02</date_of_birth>
                <person_id_external>560706_d0</person_id_external>
            </dependent_information>
        </person>
        <execution_timestamp>2020-05-28T09:44:10.000Z</execution_timestamp>
        <version_id>1911P0</version_id>
    </CompoundEmployee>
</queryCompoundEmployeeResponse>
</code>```

答:
Use</p>

```<code><xsl:template match="CompoundEmployee/person">
    <xsl:copy>
        <xsl:apply-templates select="*[not(self::dependent_information)]"/>
        <xsl:apply-templates select="dependent_information">
            <xsl:sort select="date_of_birth" data-type="text" order="ascending"/>
        </xsl:apply-templates>
    </xsl:copy>
</xsl:template>
</code>```

Title: Sort XML sections using XSLT

Body:
I would like to sort the dependent_information sections in below xml based on date_of_birth field.
Tried below script but it skips other sections like personal_information/employment_information etc

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()" />
        </xsl:copy>
    </xsl:template>
    <xsl:template match="//CompoundEmployee/person">
        <xsl:copy>
            <xsl:apply-templates select="dependent_information">
                <xsl:sort select="date_of_birth" data-type="text" order="ascending"/>
            </xsl:apply-templates>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

Below is the structure of my xml

<?xml version='1.0' encoding='UTF-8'?>
<queryCompoundEmployeeResponse>
    <CompoundEmployee>
        <id>22201</id>
        <person>
            <person_id_external>560706</person_id_external>
            <personal_information>
                <first_name>James</first_name>
                <last_name>Tester</last_name>
            </personal_information>
            <employment_information>
                <employment_id>21960</employment_id>
                <start_date>2020-05-01</start_date>
            </employment_information>
            <dependent_information>
                <date_of_birth>2009-05-04</date_of_birth>
                <person_id_external>560706_d0</person_id_external>
            </dependent_information>
            <dependent_information>
                <date_of_birth>2004-01-31</date_of_birth>
                <person_id_external>560706_d0</person_id_external>
            </dependent_information>
            <dependent_information>
                <date_of_birth>2019-06-02</date_of_birth>
                <person_id_external>560706_d0</person_id_external>
            </dependent_information>
        </person>
        <execution_timestamp>2020-05-28T09:44:10.000Z</execution_timestamp>
        <version_id>1911P0</version_id>
    </CompoundEmployee>
</queryCompoundEmployeeResponse>

Body:
Use

<xsl:template match="CompoundEmployee/person">
    <xsl:copy>
        <xsl:apply-templates select="*[not(self::dependent_information)]"/>
        <xsl:apply-templates select="dependent_information">
            <xsl:sort select="date_of_birth" data-type="text" order="ascending"/>
        </xsl:apply-templates>
    </xsl:copy>
</xsl:template>


问:
How do I query between two time range when time was divided as start and end time using MySQL?
How do I query between two time range using MySQL?

it is similar to this question provided in the above link but the match_time was divided into two columns, i.e. match_start_time and match_end_time,

```<code>match_start_time <= CAST('10:00:00' AS time) AND match_end_time >= (CAST('12:00:00' AS time))
</code>```

This was the query through which i tried but was not getting the correct result.

example

consider match start and end time being:-

```<code>01:30 - 03:30, 05:00 - 06:30, 03:00 - 21:30, 14:00 - 09:00
</code>```

then if i pass 00:00 - 10:00 as min and max, then i get

```<code>01:30 - 03:30, 05:00 - 06:30, 14:00 - 09:00
</code>```

but not sure whether 14:00 - 09:00 should be included.

Also if they pass 18:00 - 09:00

Then how to get the result if user provided min time is greater than max time
Sorry for bad English, please help

答:
The question is bit ambiguous. You can convert the times to datetime and determine into which date the times belong to:

```<code>select time_range, cast(time_to_match as time)
from (
  select
    concat(m.match_start_time,'-',m.match_end_time) as 'time_range',
    addtime(cast(concat('2020-01-', if(m.match_start_time<=m.match_end_time or m.match_start_time<t.match_time, '01', '02')) as datetime),t.match_time) as 'time_to_match',
    addtime(cast('2020-01-01' as datetime), m.match_start_time) as 'start_time',
    addtime(cast(concat('2020-01-', if(m.match_start_time<=m.match_end_time, '01', '02')) as datetime), m.match_end_time) as 'end_time'
  from times t
    join match_times m on 1=1
) as q
where time_to_match between start_time and end_time
order by 1,2;
</code>```

See db-fiddle.

Body:
How do I query between two time range using MySQL?

it is similar to this question provided in the above link but the match_time was divided into two columns, i.e. match_start_time and match_end_time,

match_start_time <= CAST('10:00:00' AS time) AND match_end_time >= (CAST('12:00:00' AS time))

This was the query through which i tried but was not getting the correct result.

example

consider match start and end time being:-

01:30 - 03:30, 05:00 - 06:30, 03:00 - 21:30, 14:00 - 09:00

then if i pass 00:00 - 10:00 as min and max, then i get

01:30 - 03:30, 05:00 - 06:30, 14:00 - 09:00

but not sure whether 14:00 - 09:00 should be included.

Also if they pass 18:00 - 09:00

Then how to get the result if user provided min time is greater than max time
Sorry for bad English, please help

Body:
The question is bit ambiguous. You can convert the times to datetime and determine into which date the times belong to:

select time_range, cast(time_to_match as time)
from (
  select
    concat(m.match_start_time,'-',m.match_end_time) as 'time_range',
    addtime(cast(concat('2020-01-', if(m.match_start_time<=m.match_end_time or m.match_start_time<t.match_time, '01', '02')) as datetime),t.match_time) as 'time_to_match',
    addtime(cast('2020-01-01' as datetime), m.match_start_time) as 'start_time',
    addtime(cast(concat('2020-01-', if(m.match_start_time<=m.match_end_time, '01', '02')) as datetime), m.match_end_time) as 'end_time'
  from times t
    join match_times m on 1=1
) as q
where time_to_match between start_time and end_time
order by 1,2;

See db-fiddle.


问:
Wait for Updates to Text File Before Reading - Javascript/NodeJS
I've created a Discord trivia bot using Node JS, and I'm having trouble getting it to read a text file correctly.

I would like to have it read the file AFTER it has been updated with the points, but it always reads as blank (due to the async/sync nature of JS, I assume).

Here is the code for declaring the trivia game winner:

```<code>    finalScores = readFullText('triviaresults.txt')
    receivedMessage.channel.send("The winner is " + triviaWinner + " with 5 points. Congratulations!")
                                                 //"Final scores: \n" + finalScores)
</code>```

Here is the code for reading the triviaresults.txt file:

```<code>    function readFullText(filename){
         var data = fs.readFileSync(filename, 'utf8')
         return data
    }
</code>```

Here is the code for updating the triviaresults.txt file with points:

```<code>function writeToResults(user){
const fs = require('fs')
var foundName = "false"
var newText = ""

try {
    //read the file into lines variable, split at new lines
    var lines = require('fs').readFileSync('triviaresults.txt', 'utf-8')
    .split('\n')
    .filter(Boolean);

    //loop through each line, checking if the user was found
    lines.forEach((line) => {
        if (user == line.split(':')[0]) {
            //gets users current score
            var oldScore = line.split(': ')[1]
            //converts current score to integer for adding purposes
            oldScore = parseInt(oldScore, 10)
            //adds 1 to their score
            var newScore = oldScore + 1
            //replaces old line with new line/score
            var newLine = line.replace(/.$/,newScore)
            //sets foundName to true so it knows not to add the name at the bottom
            foundName = "true"
            newText = newText + newLine + "\n"
            scoreCheck = newScore
        } else {
            if (newText == "") {
                newText = line + "\n"
            } else {
                newText = newText + line + "\n"
            }
        }
    })

    if (foundName == "false") {
        if (newText == "") {
            newText = user + ": 1"
        } else {
            newText = newText + user + ": 1"
        }
    }

    fs.writeFile('triviaresults.txt', newText, (err) => {
        if (err) throw err;
    })
} catch(e) {
    console.log('Error:', e.stack);
}}
</code>```

I'm sure there is a simple solution and I'm not able to see to it due to my limited experience with js.

答:
You would need to use callback function which you call after you write the file. And you don't even need to read the file afterwards since you already have the content as a newText so just return it.

```<code>function writeToResults(user, callback){ // <------ callback

   ...

   fs.writeFile('triviaresults.txt', newText, (err) => {
       if (err) throw err;
       callback(newText); // <------- callback
   })
};
</code>```

Then write the file and you get the data back:

```<code>writeToResults(user, function(finalScores){
    // no need for finalScores = readFullText('triviaresults.txt')
    // the function returned the data already
    finalScores;

    // if you didn't use callback(newText); then you would need to read the file here
    fs.readFile('triviaresults.txt', 'utf8', function(err, data){

    });
});
</code>```

Note: Don't use synchronous versions of readFile/writeFile unless you need to. It's blocking the whole application until the file is read into memory/written to disk.

Body:
I've created a Discord trivia bot using Node JS, and I'm having trouble getting it to read a text file correctly.

I would like to have it read the file AFTER it has been updated with the points, but it always reads as blank (due to the async/sync nature of JS, I assume).

Here is the code for declaring the trivia game winner:

    finalScores = readFullText('triviaresults.txt')
    receivedMessage.channel.send("The winner is " + triviaWinner + " with 5 points. Congratulations!")
                                                 //"Final scores: \n" + finalScores)

Here is the code for reading the triviaresults.txt file:

    function readFullText(filename){
         var data = fs.readFileSync(filename, 'utf8')
         return data
    }

Here is the code for updating the triviaresults.txt file with points:

function writeToResults(user){
const fs = require('fs')
var foundName = "false"
var newText = ""

try {
    //read the file into lines variable, split at new lines
    var lines = require('fs').readFileSync('triviaresults.txt', 'utf-8')
    .split('\n')
    .filter(Boolean);

    //loop through each line, checking if the user was found
    lines.forEach((line) => {
        if (user == line.split(':')[0]) {
            //gets users current score
            var oldScore = line.split(': ')[1]
            //converts current score to integer for adding purposes
            oldScore = parseInt(oldScore, 10)
            //adds 1 to their score
            var newScore = oldScore + 1
            //replaces old line with new line/score
            var newLine = line.replace(/.$/,newScore)
            //sets foundName to true so it knows not to add the name at the bottom
            foundName = "true"
            newText = newText + newLine + "\n"
            scoreCheck = newScore
        } else {
            if (newText == "") {
                newText = line + "\n"
            } else {
                newText = newText + line + "\n"
            }
        }
    })

    if (foundName == "false") {
        if (newText == "") {
            newText = user + ": 1"
        } else {
            newText = newText + user + ": 1"
        }
    }

    fs.writeFile('triviaresults.txt', newText, (err) => {
        if (err) throw err;
    })
} catch(e) {
    console.log('Error:', e.stack);
}}

I'm sure there is a simple solution and I'm not able to see to it due to my limited experience with js.

Body:
You would need to use callback function which you call after you write the file. And you don't even need to read the file afterwards since you already have the content as a newText so just return it.

function writeToResults(user, callback){ // <------ callback

   ...

   fs.writeFile('triviaresults.txt', newText, (err) => {
       if (err) throw err;
       callback(newText); // <------- callback
   })
};

Then write the file and you get the data back:

writeToResults(user, function(finalScores){
    // no need for finalScores = readFullText('triviaresults.txt')
    // the function returned the data already
    finalScores;

    // if you didn't use callback(newText); then you would need to read the file here
    fs.readFile('triviaresults.txt', 'utf8', function(err, data){

    });
});

Note: Don't use synchronous versions of readFile/writeFile unless you need to. It's blocking the whole application until the file is read into memory/written to disk.


问:
How to convert class component table to functional component
I am pretty new at React Hooks and Functional Components. If anyone would be so kind as to help I would so appreciate it. I have been working at this for hours now. </p>

<p>How do I turn the following table that uses class components into a table that uses functional components </p>

```<code>
class Table extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      status: [
        { title: "Clients", view: 1, total: 20 },
        { title: "Returning Players", view: 3, total: 18 },
        { title: "New Players", view: 3, total: 20 },
        { title: "Pending Players", view: 4, total: 10 },
        { title: "Players who left", view: 3, total: 11 },
        { title: "Total Players", view: 15, total: 79 }
      ]
    };
  }

  PlayersTableHeader() {
    let header = Object.keys(this.state.status[0]);
    return header.map((key, index) => {
      return <th key={index}>{key.toUpperCase()}</th>;
    });
  }

  PlayersTableData() {
    return this.state.status.map((status, index) => {
      const { title, view, total } = status;
      return (
        <tr key={index}>
          <td>{title}</td>
          <td>{view}</td>
          <td>{total}</td>
        </tr>
      );
    });
  }

  render() {
    return (
      <div>
        <table id="status">
          <tbody>
            <tr>{this.PlayersTableHeader()}</tr>
            {this.PlayersTableData()}
          </tbody>
        </table>
      </div>
    );
  }
}

export default Table;
</code>```

答:
I would separate the functional components for readability into three different files: Your mainfile.js that imitates your class Table component above, a playerstabledata.js file that brings in the PlayersTableData() component and a playerstableheader.js file that brings in PlayersTableHeader(); Now, inside of mainfile.js:

```<code>import React, { useState } from "react";
import PlayersTableHeader from "./playerstableheader.js";
import PlayersTableData from "./playerstabledata.js";
const Table = (props) => {
   const [status, setStatus] = useState([
        { title: "Clients", view: 1, total: 20 },
        { title: "Returning Players", view: 3, total: 18 },
        { title: "New Players", view: 3, total: 20 },
        { title: "Pending Players", view: 4, total: 10 },
        { title: "Players who left", view: 3, total: 11 },
        { title: "Total Players", view: 15, total: 79 }
      ]);

    return (
    <div>
        <table id="status">
          <tbody>
            <tr><PlayersTableHeader status={status} /></tr>
            <PlayersTableData status={status} />
          </tbody>
        </table>
      </div>
);
};
export default Table;
</code>```

In playerstableheader.js file:

```<code>const PlayersTableHeader = ({status}) =>{
 let header = Object.keys(status[0]);
    return header.map((key, index) => {
       <th key={index}>{key.toUpperCase()}</th>;
    });

};
export default PlayersTableHeader;
</code>```

In playerstabledata.js :

```<code>const PlayersTableData = ({status}) => {
 return status.map(({title, view, total}, index) => {
        <tr key={index}>
          <td>{title}</td>
          <td>{view}</td>
          <td>{total}</td>
        </tr>
    });

};
export default PlayersTableData;
</code>```

Note how you I am passing down status state to each component. Hope this helps!

Body:
I am pretty new at React Hooks and Functional Components. If anyone would be so kind as to help I would so appreciate it. I have been working at this for hours now.

How do I turn the following table that uses class components into a table that uses functional components

class Table extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      status: [
        { title: "Clients", view: 1, total: 20 },
        { title: "Returning Players", view: 3, total: 18 },
        { title: "New Players", view: 3, total: 20 },
        { title: "Pending Players", view: 4, total: 10 },
        { title: "Players who left", view: 3, total: 11 },
        { title: "Total Players", view: 15, total: 79 }
      ]
    };
  }

  PlayersTableHeader() {
    let header = Object.keys(this.state.status[0]);
    return header.map((key, index) => {
      return {key.toUpperCase()}	;
    });
  }

  PlayersTableData() {
    return this.state.status.map((status, index) => {
      const { title, view, total } = status;
      return (

          {title}
          {view}
          {total}

      );
    });
  }

  render() {
    return (

{this.PlayersTableHeader()}

            {this.PlayersTableData()}

    );
  }
}

export default Table;

Body:
I would separate the functional components for readability into three different files: Your mainfile.js that imitates your class Table component above, a playerstabledata.js file that brings in the PlayersTableData() component and a playerstableheader.js file that brings in PlayersTableHeader(); Now, inside of mainfile.js:

import React, { useState } from "react";
import PlayersTableHeader from "./playerstableheader.js";
import PlayersTableData from "./playerstabledata.js";
const Table = (props) => {
   const [status, setStatus] = useState([
        { title: "Clients", view: 1, total: 20 },
        { title: "Returning Players", view: 3, total: 18 },
        { title: "New Players", view: 3, total: 20 },
        { title: "Pending Players", view: 4, total: 10 },
        { title: "Players who left", view: 3, total: 11 },
        { title: "Total Players", view: 15, total: 79 }
      ]);

    return (
    <div>
        <table id="status">
          <tbody>
            <tr><PlayersTableHeader status={status} /></tr>
            <PlayersTableData status={status} />
          </tbody>
        </table>
      </div>
);
};
export default Table;

In playerstableheader.js file:

const PlayersTableHeader = ({status}) =>{
 let header = Object.keys(status[0]);
    return header.map((key, index) => {
       <th key={index}>{key.toUpperCase()}</th>;
    });

};
export default PlayersTableHeader;

In playerstabledata.js :

const PlayersTableData = ({status}) => {
 return status.map(({title, view, total}, index) => {
        <tr key={index}>
          <td>{title}</td>
          <td>{view}</td>
          <td>{total}</td>
        </tr>
    });

};
export default PlayersTableData;

Note how you I am passing down status state to each component. Hope this helps!