问:
Convert repetitive pattern into JSON file with python
Hope you are doing fine,

I have a data file(containing 1000s of a structured pattern of data), like below

```<code>PARTNER="ABC"
  ADDRESS1="ABC Country INN"
  DEPARTMENT="ABC Department"
  CONTACT_PERSON="HR"
  TELEPHONE="+91.90.XX XX X XXX"
  FAX="+01.XX.XX XX XX XX"
  EMAIL=""

PARTNER="DEF"
  ADDRESS1="DEF Malaysia"
  DEPARTMENT=""
  CONTACT_PERSON=""
  TELEPHONE="(YYY)YYYYY"
  FAX="(001)YYYYYYYY"
  EMAIL=""

PARTNER="GEH-LOP"
  ADDRESS1="GEH LOP Street"
  DEPARTMENT="HR"
  CONTACT_PERSON="Adam"
  TELEPHONE="+91.ZZ.ZZ.ZZZZ"
  FAX="+91.ZZ.ZZ.ZZZ"
  EMAIL=""
</code>```

I tried to convert the datafile(partner.txt) to JSON with below code:

Created empty dictionaries dict1 and dict2

Reading the data file line by line

used this if not line.isspace() to make sure the linefeed is read is written in dictionary dict1

When linebreak(empty line appears) appended the content of dict1 to dict2 using dict2.update(dict1)

```<code>import json

dict1 = {}
dict2 ={}

with open("partner.txt", "r") as fh:
    out_file = open("test1.json", "w")
    for line in fh:
        if not line.isspace():
            command, description = line.strip().split("=")
            dict1[command] = description.strip('"')

        else:
            dict2.update(dict1)
            print("space found")
    json.dump(dict2,out_file,indent=1)

out_file.close()

print("json file created")

</code>```

But this code creates a json(test1.json) with only the single block of PARTNER

```<code>{
 "PARTNER": "DEF",
 "ADDRESS1": "DEF Malaysia",
 "DEPARTMENT": "",
 "CONTACT_PERSON": "",
 "TELEPHONE": "(YYY)YYYYY",
 "FAX": "(001)YYYYYYYY",
 "EMAIL": ""
}
</code>```

Expected Output
I tried looking up a lot but couldn't find a way:-

```<code>{
"data":[
{
 "PARTNER": "ABC",
 "ADDRESS1": "ABC Country INN",
 "DEPARTMENT": "ABC Department",
 "CONTACT_PERSON": "HR",
 "TELEPHONE": "+91.90.XX XX X XXX",
 "FAX": "+01.XX.XX XX XX XX",
 "EMAIL": ""
},
{
 "PARTNER": "DEF",
 "ADDRESS1": "DEF Malaysia",
 "DEPARTMENT": "",
 "CONTACT_PERSON": "",
 "TELEPHONE": "(YYY)YYYYY",
 "FAX": "(001)YYYYYYYY",
 "EMAIL": ""
},
{
 "PARTNER": "GEH-LOP",
 "ADDRESS1": "GEH LOP Street",
 "DEPARTMENT": "HR",
 "CONTACT_PERSON": "Adam",
 "TELEPHONE": "+91.ZZ.ZZ.ZZZZ",
 "FAX": "+91.ZZ.ZZ.ZZZ",
 "EMAIL": ""
}
]
}
</code>```

答:
Solution

Using regex + json + dict/list-comprehension

You can do this using the regex (regular expression) and json libraries together. The text-processing is carried out with regex and finally the json library is used to format the dictionary into JSON format and write to a .json file.

Additionally we use dict and list comprehensions to gather the intended fields.

Note:

The regex pattern used here is as follows:

# longer manually written version
pat = r'PARTNER="(.*)"\n\s*ADDRESS1="(.*)"\n\s*DEPARTMENT="(.*)"\n\s*CONTACT_PERSON="(.*)"\n\s*TELEPHONE="(.*)"\n\s*FAX="(.*)"\n\s*EMAIL="(.*)"'

# shorter equivalent automated version
pat = '="(.*)"\n\s*'.join(field_labels) + '="(.*)"'
```
</blockquote>

<hr>

<h2>Code</h2>

<pre class="lang-py prettyprint-override"><code>import re
import json

# Read from file or use the dummy data
with open("partner.txt", "r") as f:
    s = f.read()

field_labels = [
                'PARTNER',
                'ADDRESS1',
                'DEPARTMENT',
                'CONTACT_PERSON',
                'TELEPHONE',
                'FAX',
                'EMAIL'
                ]
# Define regex pattern and compile for speed
pat = '="(.*)"\n\s*'.join(field_labels) + '="(.*)"'
pat = re.compile(pat)

# Extract target fields
data = pat.findall(s)

# Prepare a list of dicts: each dict for a single block of data
d = [dict((k,v) for k,v in zip(field_labels, field_values)) for field_values in data]
text = json.dumps({'data': d}, indent=2)
print(text)
# Write to a json file
with open('output.json', 'w') as f:
    f.write(text)
</code>```

Output:

# output.json
{
  "data": [
    {
      "PARTNER": "ABC",
      "ADDRESS1": "ABC Country INN",
      "DEPARTMENT": "ABC Department",
      "CONTACT_PERSON": "HR",
      "TELEPHONE": "+91.90.XX XX X XXX",
      "FAX": "+01.XX.XX XX XX XX",
      "EMAIL": ""
    },
    {
      "PARTNER": "DEF",
      "ADDRESS1": "DEF Malaysia",
      "DEPARTMENT": "",
      "CONTACT_PERSON": "",
      "TELEPHONE": "(YYY)YYYYY",
      "FAX": "(001)YYYYYYYY",
      "EMAIL": ""
    },
    {
      "PARTNER": "GEH-LOP",
      "ADDRESS1": "GEH LOP Street",
      "DEPARTMENT": "HR",
      "CONTACT_PERSON": "Adam",
      "TELEPHONE": "+91.ZZ.ZZ.ZZZZ",
      "FAX": "+91.ZZ.ZZ.ZZZ",
      "EMAIL": ""
    }
  ]
}
```

<hr>

<h2>Dummy Data</h2>

<pre class="lang-py prettyprint-override"><code># Dummy Data
s = """
PARTNER="ABC"
  ADDRESS1="ABC Country INN"
  DEPARTMENT="ABC Department"
  CONTACT_PERSON="HR"
  TELEPHONE="+91.90.XX XX X XXX"
  FAX="+01.XX.XX XX XX XX"
  EMAIL=""

PARTNER="DEF"
  ADDRESS1="DEF Malaysia"
  DEPARTMENT=""
  CONTACT_PERSON=""
  TELEPHONE="(YYY)YYYYY"
  FAX="(001)YYYYYYYY"
  EMAIL=""

PARTNER="GEH-LOP"
  ADDRESS1="GEH LOP Street"
  DEPARTMENT="HR"
  CONTACT_PERSON="Adam"
  TELEPHONE="+91.ZZ.ZZ.ZZZZ"
  FAX="+91.ZZ.ZZ.ZZZ"
  EMAIL=""
"""
</code>```

Body:
Hope you are doing fine,

I have a data file(containing 1000s of a structured pattern of data), like below

PARTNER="ABC"
  ADDRESS1="ABC Country INN"
  DEPARTMENT="ABC Department"
  CONTACT_PERSON="HR"
  TELEPHONE="+91.90.XX XX X XXX"
  FAX="+01.XX.XX XX XX XX"
  EMAIL=""

PARTNER="DEF"
  ADDRESS1="DEF Malaysia"
  DEPARTMENT=""
  CONTACT_PERSON=""
  TELEPHONE="(YYY)YYYYY"
  FAX="(001)YYYYYYYY"
  EMAIL=""

PARTNER="GEH-LOP"
  ADDRESS1="GEH LOP Street"
  DEPARTMENT="HR"
  CONTACT_PERSON="Adam"
  TELEPHONE="+91.ZZ.ZZ.ZZZZ"
  FAX="+91.ZZ.ZZ.ZZZ"
  EMAIL=""

I tried to convert the datafile(partner.txt) to JSON with below code:

Created empty dictionaries dict1 and dict2

Reading the data file line by line

used this if not line.isspace() to make sure the linefeed is read is written in dictionary dict1

When linebreak(empty line appears) appended the content of dict1 to dict2 using dict2.update(dict1)

import json

dict1 = {}
dict2 ={}

with open("partner.txt", "r") as fh:
    out_file = open("test1.json", "w")
    for line in fh:
        if not line.isspace():
            command, description = line.strip().split("=")
            dict1[command] = description.strip('"')

        else:
            dict2.update(dict1)
            print("space found")
    json.dump(dict2,out_file,indent=1)

out_file.close()

print("json file created")

But this code creates a json(test1.json) with only the single block of PARTNER

{
 "PARTNER": "DEF",
 "ADDRESS1": "DEF Malaysia",
 "DEPARTMENT": "",
 "CONTACT_PERSON": "",
 "TELEPHONE": "(YYY)YYYYY",
 "FAX": "(001)YYYYYYYY",
 "EMAIL": ""
}

Expected Output
I tried looking up a lot but couldn't find a way:-

{
"data":[
{
 "PARTNER": "ABC",
 "ADDRESS1": "ABC Country INN",
 "DEPARTMENT": "ABC Department",
 "CONTACT_PERSON": "HR",
 "TELEPHONE": "+91.90.XX XX X XXX",
 "FAX": "+01.XX.XX XX XX XX",
 "EMAIL": ""
},
{
 "PARTNER": "DEF",
 "ADDRESS1": "DEF Malaysia",
 "DEPARTMENT": "",
 "CONTACT_PERSON": "",
 "TELEPHONE": "(YYY)YYYYY",
 "FAX": "(001)YYYYYYYY",
 "EMAIL": ""
},
{
 "PARTNER": "GEH-LOP",
 "ADDRESS1": "GEH LOP Street",
 "DEPARTMENT": "HR",
 "CONTACT_PERSON": "Adam",
 "TELEPHONE": "+91.ZZ.ZZ.ZZZZ",
 "FAX": "+91.ZZ.ZZ.ZZZ",
 "EMAIL": ""
}
]
}

Body:
Solution

Using regex + json + dict/list-comprehension

You can do this using the regex (regular expression) and json libraries together. The text-processing is carried out with regex and finally the json library is used to format the dictionary into JSON format and write to a .json file.

Additionally we use dict and list comprehensions to gather the intended fields.

Note:

The regex pattern used here is as follows:

# longer manually written version
pat = r'PARTNER="(.*)"\n\s*ADDRESS1="(.*)"\n\s*DEPARTMENT="(.*)"\n\s*CONTACT_PERSON="(.*)"\n\s*TELEPHONE="(.*)"\n\s*FAX="(.*)"\n\s*EMAIL="(.*)"'

# shorter equivalent automated version
pat = '="(.*)"\n\s*'.join(field_labels) + '="(.*)"'

Code

import re
import json

# Read from file or use the dummy data
with open("partner.txt", "r") as f:
    s = f.read()

field_labels = [
                'PARTNER',
                'ADDRESS1',
                'DEPARTMENT',
                'CONTACT_PERSON',
                'TELEPHONE',
                'FAX',
                'EMAIL'
                ]
# Define regex pattern and compile for speed
pat = '="(.*)"\n\s*'.join(field_labels) + '="(.*)"'
pat = re.compile(pat)

# Extract target fields
data = pat.findall(s)

# Prepare a list of dicts: each dict for a single block of data
d = [dict((k,v) for k,v in zip(field_labels, field_values)) for field_values in data]
text = json.dumps({'data': d}, indent=2)
print(text)
# Write to a json file
with open('output.json', 'w') as f:
    f.write(text)

Output:

# output.json
{
  "data": [
    {
      "PARTNER": "ABC",
      "ADDRESS1": "ABC Country INN",
      "DEPARTMENT": "ABC Department",
      "CONTACT_PERSON": "HR",
      "TELEPHONE": "+91.90.XX XX X XXX",
      "FAX": "+01.XX.XX XX XX XX",
      "EMAIL": ""
    },
    {
      "PARTNER": "DEF",
      "ADDRESS1": "DEF Malaysia",
      "DEPARTMENT": "",
      "CONTACT_PERSON": "",
      "TELEPHONE": "(YYY)YYYYY",
      "FAX": "(001)YYYYYYYY",
      "EMAIL": ""
    },
    {
      "PARTNER": "GEH-LOP",
      "ADDRESS1": "GEH LOP Street",
      "DEPARTMENT": "HR",
      "CONTACT_PERSON": "Adam",
      "TELEPHONE": "+91.ZZ.ZZ.ZZZZ",
      "FAX": "+91.ZZ.ZZ.ZZZ",
      "EMAIL": ""
    }
  ]
}

Dummy Data

# Dummy Data
s = """
PARTNER="ABC"
  ADDRESS1="ABC Country INN"
  DEPARTMENT="ABC Department"
  CONTACT_PERSON="HR"
  TELEPHONE="+91.90.XX XX X XXX"
  FAX="+01.XX.XX XX XX XX"
  EMAIL=""

PARTNER="DEF"
  ADDRESS1="DEF Malaysia"
  DEPARTMENT=""
  CONTACT_PERSON=""
  TELEPHONE="(YYY)YYYYY"
  FAX="(001)YYYYYYYY"
  EMAIL=""

PARTNER="GEH-LOP"
  ADDRESS1="GEH LOP Street"
  DEPARTMENT="HR"
  CONTACT_PERSON="Adam"
  TELEPHONE="+91.ZZ.ZZ.ZZZZ"
  FAX="+91.ZZ.ZZ.ZZZ"
  EMAIL=""
"""


来源: stackexchange

问:
FinViz - Stock scraping giving error --AMZN not found 'NoneType' object has no attribute 'find_next'
I am new to BeautifulSoup package.
I am playing with a code that I got from some website and I got stuck with the above error. Please help.</p>

```<code>import pandas as pd
import re
from bs4 import BeautifulSoup as bs
import requests

def get_fundamental_data(df):
    for symbol in df.index:
        try:
            url = ("http://finviz.com/quote.ashx?t=" + symbol.lower())
            soup = bs(requests.get(url).content)
            for m in df.columns:
                df.loc[symbol,m] = fundamental_metric(soup,m)
        except Exception as e:
            print (symbol, 'not found')
            print(e)
    return df

def fundamental_metric(soup, metric):
    return soup.find(text=metric).find_next(class_='snapshot-td2').text

# Define A List Of Stocks And The Fundamental Metrics

stock_list = ['AMZN', 'GOOG', 'PG', 'KO', 'IBM', 'DG', 'XOM',
              'KO', 'PEP', 'MT', 'NL', 'ALDW', 'DCM', 'GSB', 'LPL']
metric = ['P/B',
          'P/E',
          'Forward P/E'
          ]

df = pd.DataFrame(index=stock_list, columns=metric)
df = get_fundamental_data(df)
df.head()
</code>```

答:
I was able to fix my own code based on this thread.

BeautifulSoup Scraping ERROR: AttributeError: 'NoneType' object has no attribute

My code after fix:

```<code>import pandas as pd
import re
from bs4 import BeautifulSoup as bs
import requests
import requests
from bs4 import BeautifulSoup
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36',
          'Upgrade-Insecure-Requests': '1', 'Cookie': 'v2=1495343816.182.19.234.142', 'Accept-Encoding': 'gzip, deflate, sdch',
           'Referer': "http://finviz.com/quote.ashx?t="}

def get_fundamental_data(df):
    for symbol in df.index:
        try:
            #url = ("http://finviz.com/quote.ashx?t=" + symbol.lower())
            r = requests.get("http://finviz.com/quote.ashx?t="+ symbol.lower(),headers=headers)
            soup = bs(r.content,'html.parser')
            for m in df.columns:
                df.loc[symbol,m] = fundamental_metric(soup,m)
        except Exception as e:
            print (symbol, 'not found')
            print(e)
    return df

def fundamental_metric(soup, metric):
    return soup.find(text=metric).find_next(class_='snapshot-td2').text

# Define A List Of Stocks And The Fundamental Metrics

stock_list = ['AMZN', 'GOOG','ABC']
metric = ['P/B',
          'P/E',
          'Forward P/E'
          ]

df = pd.DataFrame(index=stock_list, columns=metric)
df = get_fundamental_data(df)
df.head()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am new to BeautifulSoup package.
I am playing with a code that I got from some website and I got stuck with the above error. Please help.

import pandas as pd
import re
from bs4 import BeautifulSoup as bs
import requests

def get_fundamental_data(df):
    for symbol in df.index:
        try:
            url = ("http://finviz.com/quote.ashx?t=" + symbol.lower())
            soup = bs(requests.get(url).content)
            for m in df.columns:
                df.loc[symbol,m] = fundamental_metric(soup,m)
        except Exception as e:
            print (symbol, 'not found')
            print(e)
    return df

def fundamental_metric(soup, metric):
    return soup.find(text=metric).find_next(class_='snapshot-td2').text

# Define A List Of Stocks And The Fundamental Metrics

stock_list = ['AMZN', 'GOOG', 'PG', 'KO', 'IBM', 'DG', 'XOM',
              'KO', 'PEP', 'MT', 'NL', 'ALDW', 'DCM', 'GSB', 'LPL']
metric = ['P/B',
          'P/E',
          'Forward P/E'
          ]

df = pd.DataFrame(index=stock_list, columns=metric)
df = get_fundamental_data(df)
df.head()

Body:
I was able to fix my own code based on this thread.

BeautifulSoup Scraping ERROR: AttributeError: 'NoneType' object has no attribute

My code after fix:

import pandas as pd
import re
from bs4 import BeautifulSoup as bs
import requests
import requests
from bs4 import BeautifulSoup
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36',
          'Upgrade-Insecure-Requests': '1', 'Cookie': 'v2=1495343816.182.19.234.142', 'Accept-Encoding': 'gzip, deflate, sdch',
           'Referer': "http://finviz.com/quote.ashx?t="}

def get_fundamental_data(df):
    for symbol in df.index:
        try:
            #url = ("http://finviz.com/quote.ashx?t=" + symbol.lower())
            r = requests.get("http://finviz.com/quote.ashx?t="+ symbol.lower(),headers=headers)
            soup = bs(r.content,'html.parser')
            for m in df.columns:
                df.loc[symbol,m] = fundamental_metric(soup,m)
        except Exception as e:
            print (symbol, 'not found')
            print(e)
    return df

def fundamental_metric(soup, metric):
    return soup.find(text=metric).find_next(class_='snapshot-td2').text

# Define A List Of Stocks And The Fundamental Metrics

stock_list = ['AMZN', 'GOOG','ABC']
metric = ['P/B',
          'P/E',
          'Forward P/E'
          ]

df = pd.DataFrame(index=stock_list, columns=metric)
df = get_fundamental_data(df)
df.head()


问:
SwiftUI binding boolean if statement (Cannot convert value of type 'Binding<Bool>' to expected condition type 'Bool')
I'm trying to conditionally show a View (not using .sheet) and using a binding boolean returns the error above in the title. If I use self.menuactivated, no view will be presented upon the @State variable toggle. Is there a way around this?

```<code>struct ContentView: View {
    @State private var menuActivated  = false

    var body: some View {
        NavigationView {
            ... // code
        }
        if $menuActivated {
            menuView()
        }
    }
}
</code>```

答:
I assume this was the intention (menu will be shown over NavigationView on toggle)</p>

```<code>struct ContentView: View {
    @State private var menuActivated  = false

    var body: some View {
        ZStack {
           NavigationView {
            ... // code
           }
           if menuActivated {
              menuView()
           }
        }
    }
}
</code>```

Body:
I'm trying to conditionally show a View (not using .sheet) and using a binding boolean returns the error above in the title. If I use self.menuactivated, no view will be presented upon the @State variable toggle. Is there a way around this?

struct ContentView: View {
    @State private var menuActivated  = false

    var body: some View {
        NavigationView {
            ... // code
        }
        if $menuActivated {
            menuView()
        }
    }
}

Body:
I assume this was the intention (menu will be shown over NavigationView on toggle)

struct ContentView: View {
    @State private var menuActivated  = false

    var body: some View {
        ZStack {
           NavigationView {
            ... // code
           }
           if menuActivated {
              menuView()
           }
        }
    }
}


问:
Not understanding Android Mediaplayer Synchronization
Recently I've been learning Android from Beginning Android games when I came across this code:

```<code>    MediaPlayer mediaPlayer;
    boolean isPrepared = false;
    public AndroidMusic(AssetFileDescriptor assetDescriptor) {
        mediaPlayer = new MediaPlayer();
        try {
            mediaPlayer.setDataSource(assetDescriptor.getFileDescriptor(),
                    assetDescriptor.getStartOffset(),
                    assetDescriptor.getLength());
            mediaPlayer.prepare();
            isPrepared = true;
            mediaPlayer.setOnCompletionListener(this);
        } catch (Exception e) {
            throw new RuntimeException("Couldn't load music");
        }
    }
    public void dispose() {
        if (mediaPlayer.isPlaying())
            mediaPlayer.stop();
        mediaPlayer.release();
    }
    public boolean isLooping() {
        return mediaPlayer.isLooping();
    }

    public boolean isPlaying() {
        return mediaPlayer.isPlaying();
    }

    public boolean isStopped() {
        return !isPrepared;
    }
    public void pause() {
        if (mediaPlayer.isPlaying())
            mediaPlayer.pause();
    }
    public void play() {
        if (mediaPlayer.isPlaying())
            return;
        try {
            synchronized (this) {
                if (!isPrepared)
                    mediaPlayer.prepare();
                mediaPlayer.start();
            }
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void setLooping(boolean isLooping) {
        mediaPlayer.setLooping(isLooping);
    }

    public void setVolume(float volume) {
        mediaPlayer.setVolume(volume, volume);
    }
    public void stop() {
        mediaPlayer.stop();
        synchronized (this) {
            isPrepared = false;
        }
    }
    public void onCompletion(MediaPlayer player) {
        synchronized (this) {
            isPrepared = false;
        }
    }
}
</code>```

I'm very confused as to why we need to synchronize things here. Will there be more than one thing accessing these synchronized blocks? The book states, " The method
OnCompletionListener.onCompletion() might be called in a separate thread, and since
we set the isPrepared member in this method, we have to make sure that it is safe from
concurrent modifications. "
CallBacks are new to me, but I assume that when the MediaPlayer finishes, onCompletion is called. How will this onCompletion be called from a separate thread? Won't it be called on the thread that's executing this class? Eg, Thread 1 is executing play() and eventually the file ends, so onCompletion() is called on Thread 1. How will this be called on Thread 2? The synchronization on onCompletion() confuses me most, as with the other ones I somewhat understand that a different thread(UI thread) might edit the value of isPrepared in stop(), so that needs to be synchronized. The book's explanation further confuses me. How does this synchronization work, and what purpose does it serve?

答:
All synchronized blocks synchronized on the same object can only have one thread executing inside them at the same time. All other threads attempting to enter the synchronized block are blocked until the thread inside the synchronized block exits the block.

Will there be more than one thing accessing these synchronized blocks?
It's your choice. You could have a central AndroidMusic class, and request to play something from threads.

YourClass.java

```<code>  AndroidMusic androidMusic;
  public void initialize(){
    Thread thread = new Thread(
      Runnable runnable = new Runnable() {
            @Override
            public void run() {
                androidMusic = new AndroidMusic(myAssetDescriptor);
            }
        };
    );
    thread.start();
  }

  public void playMusic(){
    Thread thread = new Thread(
      Runnable runnable = new Runnable() {
            @Override
            public void run() {
                androidMusic.play();
            }
        };
    );
    thread.start();
  }
</code>```

The strategy in this code is useful because you are using the method prepare(). This method is not async, so the UI can be blocked on the execution if is not called from a thread.

Assuming that you have the execution of the player in threads you could have concurrent request trying to modify the isPrepared at the same time. With the synchronized block all the threads will be waiting for his turn to access or modify the value.

About the onCompletion listeners:
The listener of the MediaPlayer is referencing the self instance of the AndroidMusic class.

You initialize a new AndroidMusic();

You have a MediaPlayer with a Callback to self class (AndroidMusic)

The callback will be in the same thread that the AndroidMusic instance is.
With the synchronized block your AndroidMusic class will be safe when a multiple threads request the play action at same time.

Body:
Recently I've been learning Android from Beginning Android games when I came across this code:

    MediaPlayer mediaPlayer;
    boolean isPrepared = false;
    public AndroidMusic(AssetFileDescriptor assetDescriptor) {
        mediaPlayer = new MediaPlayer();
        try {
            mediaPlayer.setDataSource(assetDescriptor.getFileDescriptor(),
                    assetDescriptor.getStartOffset(),
                    assetDescriptor.getLength());
            mediaPlayer.prepare();
            isPrepared = true;
            mediaPlayer.setOnCompletionListener(this);
        } catch (Exception e) {
            throw new RuntimeException("Couldn't load music");
        }
    }
    public void dispose() {
        if (mediaPlayer.isPlaying())
            mediaPlayer.stop();
        mediaPlayer.release();
    }
    public boolean isLooping() {
        return mediaPlayer.isLooping();
    }

    public boolean isPlaying() {
        return mediaPlayer.isPlaying();
    }

    public boolean isStopped() {
        return !isPrepared;
    }
    public void pause() {
        if (mediaPlayer.isPlaying())
            mediaPlayer.pause();
    }
    public void play() {
        if (mediaPlayer.isPlaying())
            return;
        try {
            synchronized (this) {
                if (!isPrepared)
                    mediaPlayer.prepare();
                mediaPlayer.start();
            }
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void setLooping(boolean isLooping) {
        mediaPlayer.setLooping(isLooping);
    }

    public void setVolume(float volume) {
        mediaPlayer.setVolume(volume, volume);
    }
    public void stop() {
        mediaPlayer.stop();
        synchronized (this) {
            isPrepared = false;
        }
    }
    public void onCompletion(MediaPlayer player) {
        synchronized (this) {
            isPrepared = false;
        }
    }
}

I'm very confused as to why we need to synchronize things here. Will there be more than one thing accessing these synchronized blocks? The book states, " The method
OnCompletionListener.onCompletion() might be called in a separate thread, and since
we set the isPrepared member in this method, we have to make sure that it is safe from
concurrent modifications. "
CallBacks are new to me, but I assume that when the MediaPlayer finishes, onCompletion is called. How will this onCompletion be called from a separate thread? Won't it be called on the thread that's executing this class? Eg, Thread 1 is executing play() and eventually the file ends, so onCompletion() is called on Thread 1. How will this be called on Thread 2? The synchronization on onCompletion() confuses me most, as with the other ones I somewhat understand that a different thread(UI thread) might edit the value of isPrepared in stop(), so that needs to be synchronized. The book's explanation further confuses me. How does this synchronization work, and what purpose does it serve?

Body:
All synchronized blocks synchronized on the same object can only have one thread executing inside them at the same time. All other threads attempting to enter the synchronized block are blocked until the thread inside the synchronized block exits the block.

Will there be more than one thing accessing these synchronized blocks?
It's your choice. You could have a central AndroidMusic class, and request to play something from threads.

YourClass.java

  AndroidMusic androidMusic;
  public void initialize(){
    Thread thread = new Thread(
      Runnable runnable = new Runnable() {
            @Override
            public void run() {
                androidMusic = new AndroidMusic(myAssetDescriptor);
            }
        };
    );
    thread.start();
  }

  public void playMusic(){
    Thread thread = new Thread(
      Runnable runnable = new Runnable() {
            @Override
            public void run() {
                androidMusic.play();
            }
        };
    );
    thread.start();
  }

The strategy in this code is useful because you are using the method prepare(). This method is not async, so the UI can be blocked on the execution if is not called from a thread.

Assuming that you have the execution of the player in threads you could have concurrent request trying to modify the isPrepared at the same time. With the synchronized block all the threads will be waiting for his turn to access or modify the value.

About the onCompletion listeners:
The listener of the MediaPlayer is referencing the self instance of the AndroidMusic class.

You initialize a new AndroidMusic();

You have a MediaPlayer with a Callback to self class (AndroidMusic)

The callback will be in the same thread that the AndroidMusic instance is.
With the synchronized block your AndroidMusic class will be safe when a multiple threads request the play action at same time.


问:
How to determine how many times '0' to '9' have been used in a specific range instantly
I want to count how many times '0' to '9' have been used in a specific range

e.g. 112 has two '1' and one '2'

Thanks for your advices, I changed my code now.

But it is not efficient as I want.

```<code>num = int(input('n : '))
start_time = time.time()
num_arr = [0] * 10
progress_arr = ['%d' % (num * (i / 100)) for i in range(1, 101)]

for i in range(1, num + 1):
    if str(i) in progress_arr:
        print(str(progress_arr.index(str(i)) + 1) + '%')
    for digit in str(i):
        num_arr[int(digit)] += 1

print('Time : %.2f' % (time.time() - start_time))
print(num_arr)
</code>```

When I input 1000 as n, my program will print this arr instantly

[192, 301, 300, 300, 300, 300, 300, 300, 300, 300]

It means for 1 to 1000,
'0' has been used 192 times and '1' has been used 301 times and ···

But when I input 2,000,000,000 as n, my program will print the result after
11 minutes(Using pypy3, Ryzen 2600).

So I want to change my code as efficient to get the result of a very large number instantly.

And in my previous question, I mentioned the time complexity of O(N), which confused you because of my poor understanding of algorithm and time complexity. So I deleted it.

What I want to know is just the efficient algorithm.

I'm trying to find a specific rule by analyzing the difference in the results of increment, but it's not easy.

答:
Use collections.Counter to count the occurrence of digits in each number in the range. And by maintaining the count as you loop through the range, you do it in one pass.

```<code>def digits(number):
    c = Counter()
    for n in range(1, number+1):
        c.update(str(n))

    # return [c[str(k)] for k in range(10)]
    return c
</code>```

Output:

```<code>>>> digits(1000)
Counter({'1': 301, '2': 300, '3': 300, '4': 300, '5': 300, '6': 300, '7': 300, '8': 300, '9': 300, '0': 192})
</code>```

And if you want it as a list of the digits counts from 0 to 9, then change the return line to:

```<code>return [c[str(k)] for k in range(10)]
</code>```

```<code>>>> digits(1000)
[192, 301, 300, 300, 300, 300, 300, 300, 300, 300]
</code>```

As for complexity:

```<code>In [8]: %timeit digits(10)
16.8 µs ± 151 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

In [9]: %timeit digits(100)
113 µs ± 1.22 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

In [10]: %timeit digits(1000)
1.14 ms ± 8.92 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
</code>```

For a 10x increase in the input value, there's a 10x increase in the time taken. That's O(n), not O(n^2).

If you're defining "n" not as the input number but as the length of the input number (number of digits), then yes, it's O(n^2). But that's an arbitrary decision on what "n" is. By that metric, all numerical algorithms which are currently O(n) would immediately become O(n^2). (I suppose defining the basis of 'n' is flexible.)

Here's a slightly version faster version of the same function, though having the same time complexity:

```<code>def digits(number):
    c = Counter(char for n in range(1, number+1) for char in str(n))
    return c  # or as one line
</code>```

```<code>In [19]: %timeit digits(10)
7.15 µs ± 231 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

In [20]: %timeit digits(100)
47.5 µs ± 1.81 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

In [21]: %timeit digits(1000)
606 µs ± 48.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
</code>```

Body:
I want to count how many times '0' to '9' have been used in a specific range

e.g. 112 has two '1' and one '2'

Thanks for your advices, I changed my code now.

But it is not efficient as I want.

num = int(input('n : '))
start_time = time.time()
num_arr = [0] * 10
progress_arr = ['%d' % (num * (i / 100)) for i in range(1, 101)]

for i in range(1, num + 1):
    if str(i) in progress_arr:
        print(str(progress_arr.index(str(i)) + 1) + '%')
    for digit in str(i):
        num_arr[int(digit)] += 1

print('Time : %.2f' % (time.time() - start_time))
print(num_arr)

When I input 1000 as n, my program will print this arr instantly

[192, 301, 300, 300, 300, 300, 300, 300, 300, 300]

It means for 1 to 1000,
'0' has been used 192 times and '1' has been used 301 times and ···

But when I input 2,000,000,000 as n, my program will print the result after
11 minutes(Using pypy3, Ryzen 2600).

So I want to change my code as efficient to get the result of a very large number instantly.

And in my previous question, I mentioned the time complexity of O(N), which confused you because of my poor understanding of algorithm and time complexity. So I deleted it.

What I want to know is just the efficient algorithm.

I'm trying to find a specific rule by analyzing the difference in the results of increment, but it's not easy.

Body:
Use collections.Counter to count the occurrence of digits in each number in the range. And by maintaining the count as you loop through the range, you do it in one pass.

def digits(number):
    c = Counter()
    for n in range(1, number+1):
        c.update(str(n))

    # return [c[str(k)] for k in range(10)]
    return c

Output:

>>> digits(1000)
Counter({'1': 301, '2': 300, '3': 300, '4': 300, '5': 300, '6': 300, '7': 300, '8': 300, '9': 300, '0': 192})

And if you want it as a list of the digits counts from 0 to 9, then change the return line to:

return [c[str(k)] for k in range(10)]

>>> digits(1000)
[192, 301, 300, 300, 300, 300, 300, 300, 300, 300]

As for complexity:

In [8]: %timeit digits(10)
16.8 µs ± 151 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

In [9]: %timeit digits(100)
113 µs ± 1.22 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

In [10]: %timeit digits(1000)
1.14 ms ± 8.92 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

For a 10x increase in the input value, there's a 10x increase in the time taken. That's O(n), not O(n^2).

If you're defining "n" not as the input number but as the length of the input number (number of digits), then yes, it's O(n^2). But that's an arbitrary decision on what "n" is. By that metric, all numerical algorithms which are currently O(n) would immediately become O(n^2). (I suppose defining the basis of 'n' is flexible.)

Here's a slightly version faster version of the same function, though having the same time complexity:

def digits(number):
    c = Counter(char for n in range(1, number+1) for char in str(n))
    return c  # or as one line

In [19]: %timeit digits(10)
7.15 µs ± 231 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

In [20]: %timeit digits(100)
47.5 µs ± 1.81 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

In [21]: %timeit digits(1000)
606 µs ± 48.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)


问:
c# constructor injection and constructor overloads
I'm using constructor injection for the first time and wish to write my code defensively.

Therefore if I have a class with a constructor and a save method as below:

```<code>public SomeConstructor(string name, Object someObject)
{
  _name= name;
  _someObject= someObject;
}

public void Save()
{
  // Does a database save
}
</code>```

But then need to create another related method in this Class that doesn't need the _someObject so I create an overloaded chained constructor as:

```<code>public SomeConstructor(string name) : this(name, null)
{
}
</code>```

How can I successfully stop someone instantiating the class with this second constructor with 1 parameter and using the Save() which has someObject as null?

I'm not using an injection tool.

Above is a simple example and in it, you are correct I could just throw an exception for a null just as I would if a property was not set.

What I wanted to avoid was a series of validation checks at the start of each method.

答:
The IoC it is just a way to dinamically resolve the dependency but doens't solve any OO problem.
I would focus on a good OO design instead of try to find a way to cheat the framework forcing to use a contractor instead of another.The question is how would you do that if you were not using an IoC framework?
probabily checking if SomeObject is null?</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm using constructor injection for the first time and wish to write my code defensively.

Therefore if I have a class with a constructor and a save method as below:

public SomeConstructor(string name, Object someObject)
{
  _name= name;
  _someObject= someObject;
}

public void Save()
{
  // Does a database save
}

But then need to create another related method in this Class that doesn't need the _someObject so I create an overloaded chained constructor as:

public SomeConstructor(string name) : this(name, null)
{
}

How can I successfully stop someone instantiating the class with this second constructor with 1 parameter and using the Save() which has someObject as null?

I'm not using an injection tool.

Above is a simple example and in it, you are correct I could just throw an exception for a null just as I would if a property was not set.

What I wanted to avoid was a series of validation checks at the start of each method.


问:
Flutter dart displayName and photoURL is null after linkWithCredential?
Flutter dart displayName and photoURL is null after linkWithCredential? I login thru facebook login.

```<code>AuthResult result = await _firebaseUser.linkWithCredential(credential);
_firebaseUser = result.user;
print(_firebaseUser.photoUrl); // null
</code>```

i am successfully linked but it doesnt get the profile data

答: Once there are multiple providers, each of them could have a different photo URL. That why the provider-specific data, and likely the photo URL you're looking for, is in one of the items in the UserInfo.providerData array.

Body:
Flutter dart displayName and photoURL is null after linkWithCredential? I login thru facebook login.

AuthResult result = await _firebaseUser.linkWithCredential(credential);
_firebaseUser = result.user;
print(_firebaseUser.photoUrl); // null

i am successfully linked but it doesnt get the profile data


问:
How to add an integer to each element in a list?
If I have list=[1,2,3] and I want to add 1 to each element to get the output [2,3,4],
how would I do that?

I assume I would use a for loop but not sure exactly how.

答:
```<code>import numpy as np

np.add([1, 2, 3], 1).tolist()
</code>```

which gives

```<code>[2, 3, 4]
</code>```

Body:
import numpy as np

np.add([1, 2, 3], 1).tolist()

which gives

[2, 3, 4]


问:
Leetcode Best Time to Buy and Sell Stock with Transaction Fee, How to think in it
I understand the solution to Best Time to Buy and Sell Stock with Transaction Fee, and other 5 problems relative to Stock Sell. I just want deep understanding of how to come up with such recursive relation in problems alike.

I have read https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/discuss/108870/most-consistent-ways-of-dealing-with-the-series-of-stock-problems and I understand entirely.

But, I am having trouble resolving some similar problem with minor changes, such as if one can buy stock without sell those previously bought first.

So, what is the general approach on coming up with correct recursive relation?

I am really confused. Thank you so much

答:
```<code> class Solution {
   public int maxProfit(int[] prices, int fee) {
    if (prices == null || prices.length <= 1) {
        return 0;
    }
    long profit = 0, minPrice = Integer.MIN_VALUE;
    //Integer.MIN_VALUE = - 2147483648

  for (int price : prices) {
    long profit_old = profit;
    profit = Math.max(profit, minPrice + price - fee);
    minPrice = Math.max(minPrice, profit_old - price);
   }

  return (int)profit;

  }
}
</code>```

Your Input [1,3,2,8,4,9] 2

see how Profit & minPrice value gets updated in code

profit  0.
minPrice -1

profit 0
minPrice -1

profit 0
minPrice -1

profit 5
minPrice -1

profit 5
minPrice 1

profit 8
minPrice 1

So Final  MaxProfit is 8.

Body:
 class Solution {
   public int maxProfit(int[] prices, int fee) {
    if (prices == null || prices.length <= 1) {
        return 0;
    }
    long profit = 0, minPrice = Integer.MIN_VALUE;
    //Integer.MIN_VALUE = - 2147483648

  for (int price : prices) {
    long profit_old = profit;
    profit = Math.max(profit, minPrice + price - fee);
    minPrice = Math.max(minPrice, profit_old - price);
   }

  return (int)profit;

  }
}

Your Input [1,3,2,8,4,9] 2

see how Profit & minPrice value gets updated in code

profit  0.
minPrice -1

profit 0
minPrice -1

profit 0
minPrice -1

profit 5
minPrice -1

profit 5
minPrice 1

profit 8
minPrice 1

So Final  MaxProfit is 8.


问:
SQL query to find duplicate records and discount from COUNT with condition AND
I am using below SQL query to count the records. I would like to discount the duplicate testID after I got the count.

example:

```<code>select count (*) from PRODUCT MP
   join PRODUCT_UOM pu on pu.PRODUCT_KEY = mp.PRODUCT_KEY
   join UOM u on u.UOM_ID = pu.UOM_ID
   join PRODUCT_BARCODE pb on pb.PRODUCT_UOM_KEY = pu.PRODUCT_UOM_KEY
</code>```

the excel data when query select * looks like below:

i want to discount the records which TESTID AND NAME is duplicate.

total count = 6 - 2 = 4

I understand there is distinct query which i can used, but i am not sure how to make condition with 2 columns, when duplicate then do not count them.

答:
You can reuse your existing query. For example:

```<code>select count(*) from (
  select distinct testid, name
  from PRODUCT MP
  join PRODUCT_UNIT pu on pu.PRODUCT_KEY = mp.PRODUCT_KEY
  join UNITu on u.UNIT_ID = pu.UNIT_ID
  join PRODUCT_BAR pb on pb.PRODUCT_UNIT_KEY = pu.PRODUCT_UNIT_KEY
) x
</code>```

Your existing query acts as a table expresison, but you replace COUNT(*) by DISTINCT TESTID, NAME.

Body:
I am using below SQL query to count the records. I would like to discount the duplicate testID after I got the count.

example:

select count (*) from PRODUCT MP
   join PRODUCT_UOM pu on pu.PRODUCT_KEY = mp.PRODUCT_KEY
   join UOM u on u.UOM_ID = pu.UOM_ID
   join PRODUCT_BARCODE pb on pb.PRODUCT_UOM_KEY = pu.PRODUCT_UOM_KEY

the excel data when query select * looks like below:

i want to discount the records which TESTID AND NAME is duplicate.

total count = 6 - 2 = 4

I understand there is distinct query which i can used, but i am not sure how to make condition with 2 columns, when duplicate then do not count them.

Body:
You can reuse your existing query. For example:

select count(*) from (
  select distinct testid, name
  from PRODUCT MP
  join PRODUCT_UNIT pu on pu.PRODUCT_KEY = mp.PRODUCT_KEY
  join UNITu on u.UNIT_ID = pu.UNIT_ID
  join PRODUCT_BAR pb on pb.PRODUCT_UNIT_KEY = pu.PRODUCT_UNIT_KEY
) x

Your existing query acts as a table expresison, but you replace COUNT(*) by DISTINCT TESTID, NAME.


问:
Invariant failed: You should not use <Switch> outside a <Router> using Static Router
I'm getting an error trying to make a server side rendering using reactDomServer and Static Router.

Im getting the following output:

```<code>Error: Invariant failed: You should not use <Switch> outside a <Router>
at invariant (webpack:///./node_modules/tiny-invariant/dist/tiny-invariant.esm.js?:14:9)
at Object.eval [as children] (webpack:///./node_modules/react-router/esm/react-router.js?:658:88)
at ReactDOMServerRenderer.render (/home/jesusap21/jps_webapp/node_modules/react-dom/cjs/react-dom-server.node.development.js:3635:55)
at ReactDOMServerRenderer.read (/home/jesusap21/jps_webapp/node_modules/react-dom/cjs/react-dom-server.node.development.js:3373:29)
at Object.renderToString (/home/jesusap21/jps_webapp/node_modules/react-dom/cjs/react-dom-server.node.development.js:3988:27)
at Server.<anonymous> (/home/jesusap21/jps_webapp/src/ssr/http.js:23:37)
at Server.emit (events.js:198:13)
at parserOnIncoming (_http_server.js:691:12)
at HTTPParser.parserOnHeadersComplete (_http_common.js:111:17)
</code>```

My Server:

```<code>http.createServer((req, res) => {
    // This context object contains the results of the render
    const context = {};
    const html = ReactDOMServer.renderToString(
        <ReactRouter.StaticRouter location={req.url} context={context}>
            <App />
        </ReactRouter.StaticRouter>
    );

    // context.url will contain the URL to redirect to if a <Redirect> was used
    if (context.url) {
        res.writeHead(302, {
            Location: context.url
        });
    } else {
        res.write(html);
    }
    res.end();
}).listen(port);
</code>```

I'm using BrowserRouter in the client side and it's working fine using the same component "App". but in the server side I'm having this problem.

** EDIT **

This is my App Component Code:

```<code>import React from 'react';
import configureStore from './store/configureStore';
import { Provider } from 'react-redux';
import Container from './Container'

const store = configureStore();

export default class App extends React.Component {
    render() {
        return (
            <Provider store={store}>
                <Container />
            </Provider>
        )
    }
}
</code>```

And then my Container

```<code> function Container(props: LinkStateProp) {
  const theme = createMuiTheme({
    palette: {
      primary: {
        light: 'rgba(153, 28, 31, 0.4)',
        main: '#C8283B',
        contrastText: '#FFFFFF',
      },
      secondary: {
        light: '#F2F2F2',
        main: 'rgba(0, 0, 0, 0.08)',
        dark: 'rgba(0, 0, 0, 0.2)',
        contrastText: '#000000',
      },
      contrastThreshold: 3,
      tonalOffset: 0.2,
    },
    typography: {
      fontFamily: "Roboto",
    }
  });

  const useStyles = makeStyles((theme: Theme) =>
    createStyles({
      root: {

      },
      layout: {
        marginTop: '10vh',
        minHeight: '90vh',
        display: 'flex',
      }
    }),
  );

  const classes = useStyles();
  const [open, setOpen] = React.useState(false);

  const handleDrawerOpen = () => {
    setOpen(true);
  };

  const handleDrawerClose = () => {
    setOpen(false);
  };

  return (
      <Switch>
        <MuiThemeProvider theme={theme}>
          <Container className={classes.root} maxWidth={false} disableGutters={true}>
            <Nav open={open} handleDrawerOpen={handleDrawerOpen} handleDrawerClose={handleDrawerClose}/>
            <LeftDrawer open={open} handleDrawerClose={handleDrawerClose}/>
              <div className={classes.layout}>
                <Route exact path="/" component={Home}/>
                <Route exact path="/iniciarsesion">
                  {props.isAuthUser ? <Redirect to="/" /> : <SignIn />}
                </Route>
                <Route exact path="/crearcuenta">
                  {props.isAuthUser ? <Redirect to="/" /> : <SignUp />}
                </Route>
              </div>
          </Container>
        </MuiThemeProvider>
      </Switch>
  );
}

interface LinkStateProp {
  isAuthUser: boolean,
}

const mapStateToProps = (state: ApplicationState) => ({
  isAuthUser: state.customer.isAuthUser,
});

export default connect(mapStateToProps)(Container);
</code>```

答:
You need to wrap your container in <Router> just like you did using <Provider/> in App Component

```<code>            <Provider store={store}>
              <Router>
                <Container />
             </Router>
            </Provider>
</code>```

Body:
I'm getting an error trying to make a server side rendering using reactDomServer and Static Router.

Im getting the following output:

Error: Invariant failed: You should not use <Switch> outside a <Router>
at invariant (webpack:///./node_modules/tiny-invariant/dist/tiny-invariant.esm.js?:14:9)
at Object.eval [as children] (webpack:///./node_modules/react-router/esm/react-router.js?:658:88)
at ReactDOMServerRenderer.render (/home/jesusap21/jps_webapp/node_modules/react-dom/cjs/react-dom-server.node.development.js:3635:55)
at ReactDOMServerRenderer.read (/home/jesusap21/jps_webapp/node_modules/react-dom/cjs/react-dom-server.node.development.js:3373:29)
at Object.renderToString (/home/jesusap21/jps_webapp/node_modules/react-dom/cjs/react-dom-server.node.development.js:3988:27)
at Server.<anonymous> (/home/jesusap21/jps_webapp/src/ssr/http.js:23:37)
at Server.emit (events.js:198:13)
at parserOnIncoming (_http_server.js:691:12)
at HTTPParser.parserOnHeadersComplete (_http_common.js:111:17)

My Server:

http.createServer((req, res) => {
    // This context object contains the results of the render
    const context = {};
    const html = ReactDOMServer.renderToString(
        <ReactRouter.StaticRouter location={req.url} context={context}>
            <App />
        </ReactRouter.StaticRouter>
    );

    // context.url will contain the URL to redirect to if a <Redirect> was used
    if (context.url) {
        res.writeHead(302, {
            Location: context.url
        });
    } else {
        res.write(html);
    }
    res.end();
}).listen(port);

I'm using BrowserRouter in the client side and it's working fine using the same component "App". but in the server side I'm having this problem.

** EDIT **

This is my App Component Code:

import React from 'react';
import configureStore from './store/configureStore';
import { Provider } from 'react-redux';
import Container from './Container'

const store = configureStore();

export default class App extends React.Component {
    render() {
        return (
            <Provider store={store}>
                <Container />
            </Provider>
        )
    }
}

And then my Container

 function Container(props: LinkStateProp) {
  const theme = createMuiTheme({
    palette: {
      primary: {
        light: 'rgba(153, 28, 31, 0.4)',
        main: '#C8283B',
        contrastText: '#FFFFFF',
      },
      secondary: {
        light: '#F2F2F2',
        main: 'rgba(0, 0, 0, 0.08)',
        dark: 'rgba(0, 0, 0, 0.2)',
        contrastText: '#000000',
      },
      contrastThreshold: 3,
      tonalOffset: 0.2,
    },
    typography: {
      fontFamily: "Roboto",
    }
  });

  const useStyles = makeStyles((theme: Theme) =>
    createStyles({
      root: {

      },
      layout: {
        marginTop: '10vh',
        minHeight: '90vh',
        display: 'flex',
      }
    }),
  );

  const classes = useStyles();
  const [open, setOpen] = React.useState(false);

  const handleDrawerOpen = () => {
    setOpen(true);
  };

  const handleDrawerClose = () => {
    setOpen(false);
  };

  return (
      <Switch>
        <MuiThemeProvider theme={theme}>
          <Container className={classes.root} maxWidth={false} disableGutters={true}>

            <LeftDrawer open={open} handleDrawerClose={handleDrawerClose}/>

                <Route exact path="/" component={Home}/>
                <Route exact path="/iniciarsesion">
                  {props.isAuthUser ? <Redirect to="/" /> : <SignIn />}
                </Route>
                <Route exact path="/crearcuenta">
                  {props.isAuthUser ? <Redirect to="/" /> : <SignUp />}
                </Route>

          </Container>
        </MuiThemeProvider>
      </Switch>
  );
}

interface LinkStateProp {
  isAuthUser: boolean,
}

const mapStateToProps = (state: ApplicationState) => ({
  isAuthUser: state.customer.isAuthUser,
});

export default connect(mapStateToProps)(Container);

Body:
You need to wrap your container in <Router> just like you did using <Provider/> in App Component

            <Provider store={store}>
              <Router>
                <Container />
             </Router>
            </Provider>


问:
Filter list items within a Django JSONField
Here is a simplified version of a Django model I'm working on.

```<code>class Course(models.Model):
    infos = JSONField()
</code>```

The infos JSONField looks like this :

```<code>infos = {
    category: "Maths",
    students: [
        {
            name: "Alice",
            result: 8
        },
        {
            name: "Bob",
            result: 12
        }
    ]
}

# (students can have 0 -> n items)
</code>```

I'm trying to get a list of all students that got at least 10 on any course (result >= 10).
However I'm having trouble figuring out a way to filter the QuerySet accordingly.

I'm trying to do something like this :

```<code>(Course.objects.filter(students__result__gte=10)
               .values_list('students', flat=True))
</code>```

But since students is a list, I can't access directly to the result property of each item. Besides, I don't think it would exclude the "Alice" object from the results.

I'd like to get results like this :

```<code>items = [
    {
        name: "Bob",
        result: 12
    }
]
</code>```

Bonus points if there is a way to link filtered students and course category :

```<code>items = [
    {
        category: "Maths",
        students: [
            {
                name: "Bob",
                result: 12
            }
        ]
    }
 ]
</code>```

How can I achieve the desired result ?

答:
By using raw SQL, I have managed to obtain the result.

```<code>select array_to_json(array_agg(students_array))
FROM
    course_table,
    json_array_elements(CAST(course_table.infos->>'students' as json)) students_array
WHERE
    CAST(students_array->>'result' as integer) >= 10
;</code>```

Result

```<code>sample_db=# SELECT version();
PostgreSQL 10.12 (Ubuntu 10.12-0ubuntu0.18.04.1) on x86_64-pc-linux-gnu, compiled by gcc (Ubuntu 7.4.0-1ubuntu1~18.04.1) 7.4.0, 64-bit

sample_db=# select infos from course_table;
{"category": "Maths", "students": [{"name": "Alice", "result": 8}, {"name": "Bob", "result": 12}]}
{"category": "Science", "students": [{"name": "Jerin", "result": 8}, {"name": "George", "result": 12}]}
{"category": "Physics", "students": [{"name": "Vivek", "result": 17}, {"name": "Osama", "result": 6}]}

sample_db=# select array_to_json(array_agg(students_array))
sample_db-# FROM
sample_db-# course_table,
sample_db-#  json_array_elements(CAST(course_table.infos->>'students' as json)) students_array
sample_db-# WHERE
sample_db-#  CAST(students_array->>'result' as integer) >= 10
sample_db-# ;
[{"name": "Bob", "result": 12},{"name": "George", "result": 12},{"name": "Vivek", "result": 17}]
</code>```

This raw SQL can be executed by Django as,

```<code>raw_sql = """
select 1 as id, array_to_json(array_agg(students_array)) as result
FROM
    course_table,
    json_array_elements(CAST(course_table.infos->>'students' as json)) students_array
WHERE
    CAST(students_array->>'result' as integer) >= 10
;
"""
qs = Course.objects.raw(raw_sql)
for i in qs:
    print(i.result)
</code>```

Body:
Here is a simplified version of a Django model I'm working on.

class Course(models.Model):
    infos = JSONField()

The infos JSONField looks like this :

infos = {
    category: "Maths",
    students: [
        {
            name: "Alice",
            result: 8
        },
        {
            name: "Bob",
            result: 12
        }
    ]
}

# (students can have 0 -> n items)

I'm trying to get a list of all students that got at least 10 on any course (result >= 10).
However I'm having trouble figuring out a way to filter the QuerySet accordingly.

I'm trying to do something like this :

(Course.objects.filter(students__result__gte=10)
               .values_list('students', flat=True))

But since students is a list, I can't access directly to the result property of each item. Besides, I don't think it would exclude the "Alice" object from the results.

I'd like to get results like this :

items = [
    {
        name: "Bob",
        result: 12
    }
]

Bonus points if there is a way to link filtered students and course category :

items = [
    {
        category: "Maths",
        students: [
            {
                name: "Bob",
                result: 12
            }
        ]
    }
 ]

How can I achieve the desired result ?

Body:
By using raw SQL, I have managed to obtain the result.

select array_to_json(array_agg(students_array))
FROM
    course_table,
    json_array_elements(CAST(course_table.infos->>'students' as json)) students_array
WHERE
    CAST(students_array->>'result' as integer) >= 10
;

Result

sample_db=# SELECT version();
PostgreSQL 10.12 (Ubuntu 10.12-0ubuntu0.18.04.1) on x86_64-pc-linux-gnu, compiled by gcc (Ubuntu 7.4.0-1ubuntu1~18.04.1) 7.4.0, 64-bit

sample_db=# select infos from course_table;
{"category": "Maths", "students": [{"name": "Alice", "result": 8}, {"name": "Bob", "result": 12}]}
{"category": "Science", "students": [{"name": "Jerin", "result": 8}, {"name": "George", "result": 12}]}
{"category": "Physics", "students": [{"name": "Vivek", "result": 17}, {"name": "Osama", "result": 6}]}

sample_db=# select array_to_json(array_agg(students_array))
sample_db-# FROM
sample_db-# course_table,
sample_db-#  json_array_elements(CAST(course_table.infos->>'students' as json)) students_array
sample_db-# WHERE
sample_db-#  CAST(students_array->>'result' as integer) >= 10
sample_db-# ;
[{"name": "Bob", "result": 12},{"name": "George", "result": 12},{"name": "Vivek", "result": 17}]

This raw SQL can be executed by Django as,

raw_sql = """
select 1 as id, array_to_json(array_agg(students_array)) as result
FROM
    course_table,
    json_array_elements(CAST(course_table.infos->>'students' as json)) students_array
WHERE
    CAST(students_array->>'result' as integer) >= 10
;
"""
qs = Course.objects.raw(raw_sql)
for i in qs:
    print(i.result)


问:
IIS 10 The resource class for this page was not found. Please check if the resource file exists and try again
Getting this error randomly on server here is the iis details.

IIS version= 10.0.14393.0

Windows server 2016

System.Web.Management.WebRequestErrorEvent, System.InvalidOperationException, An unhandled exception has occurred.The resource class for this page was not found.  Please check if the resource file exists and try again.

```<code>Stack trace: at System.Web.Compilation.LocalResXResourceProvider.CreateResourceManager()
at System.Web.Compilation.BaseResXResourceProvider.EnsureResourceManager()
at System.Web.Compilation.BaseResXResourceProvider.GetObject(String resourceKey, CultureInfo culture)
at System.Web.Compilation.ResourceExpressionBuilder.GetResourceObject(IResourceProvider resourceProvider, String resourceKey, CultureInfo culture, Type objType, String propName)
at ASP.usercontrols_uc_adduser_ascx.__BuildControlImage1()
at ASP.usercontrols_uc_adduser_ascx.__BuildControlcontractorUC_RadAjaxLoadingPanel1()
at ASP.usercontrols_uc_adduser_ascx.__BuildControlTree(secure_usercontrols_uc_adduser_ascx __ctrl)
at ASP.testpage_aspx.__BuildControlAddQuickContractor1()
at ASP.testpage_aspx.__BuildControlfrmMain()
at ASP.testpage_aspx.__BuildControlTree(secure_bidmain_aspx __ctrl)
at ASP.testpage_aspx.FrameworkInitialize()
at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest()
at System.Web.UI.Page.ProcessRequest(HttpContext context)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step)
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
</code>```

This error is coming randomly, but after recycling the app pool fixes it. Can some help with this.

答:
I doubt if the case relates to the Network/Route issue. For example, some requests are discarded by the application gateway, which may be caused by the wrong NAT tables configured in the public firewall or router.  You could verify this by accessing the website with a local IP.

please check the below issue.

https://serverfault.com/questions/845606/iis-randomly-returning-inet-e-resource-not-found

Body:
Getting this error randomly on server here is the iis details.

IIS version= 10.0.14393.0

Windows server 2016

System.Web.Management.WebRequestErrorEvent, System.InvalidOperationException, An unhandled exception has occurred.The resource class for this page was not found.  Please check if the resource file exists and try again.

Stack trace: at System.Web.Compilation.LocalResXResourceProvider.CreateResourceManager()
at System.Web.Compilation.BaseResXResourceProvider.EnsureResourceManager()
at System.Web.Compilation.BaseResXResourceProvider.GetObject(String resourceKey, CultureInfo culture)
at System.Web.Compilation.ResourceExpressionBuilder.GetResourceObject(IResourceProvider resourceProvider, String resourceKey, CultureInfo culture, Type objType, String propName)
at ASP.usercontrols_uc_adduser_ascx.__BuildControlImage1()
at ASP.usercontrols_uc_adduser_ascx.__BuildControlcontractorUC_RadAjaxLoadingPanel1()
at ASP.usercontrols_uc_adduser_ascx.__BuildControlTree(secure_usercontrols_uc_adduser_ascx __ctrl)
at ASP.testpage_aspx.__BuildControlAddQuickContractor1()
at ASP.testpage_aspx.__BuildControlfrmMain()
at ASP.testpage_aspx.__BuildControlTree(secure_bidmain_aspx __ctrl)
at ASP.testpage_aspx.FrameworkInitialize()
at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest()
at System.Web.UI.Page.ProcessRequest(HttpContext context)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step)
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

This error is coming randomly, but after recycling the app pool fixes it. Can some help with this.


问:
Remove empty rows within a dataframe and check similarity
I am having some difficulties to select not empty fields using regex (findall) within my dataframe, looking for words contained into a text source:

```<code>text = "Be careful otherwise police will capture you quickly."
</code>```

I will need to look for words that ends with ful in my text string, then looking for words that ends with full in my dataset.

```<code>Author      DF_Text

31       Better the devil you know than the one you don't
53       Beware the door with too many keys.
563      Be careful what you tolerate. You are teaching people how to treat you.
41       Fear the Greeks bearing gifts.
539      NaN
51       The honey is sweet but the bee has a sting.
21       Be careful what you ask for; you may get it.
</code>```

(from csv/txt file).
I need to extract words ending with ful in text, then look at both DF_Text (thus Author) which contains words ending with ful and appending results in a list.

```<code>n=0
for i in df['DF_Text']:
        print(re.findall(r"\w+ful", i))
        n=n+1
        print(n)
</code>```

My question is: how can I remove empty rows([]) from the analysis (NaN) and report the author names (e.g. 563, 21) related to?
I will be happy to provide further information, in case it would be not clear.

答:
I would use the .notna() function of Pandas to get rid of that row in your datafrae. l.
Something like this

```<code>df = df[df['DF_Text'].notna()]
</code>```

And please note that Python calls the dataframe twice before overwriting it, this is correct.

See https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.notna.htm

Body:
I am having some difficulties to select not empty fields using regex (findall) within my dataframe, looking for words contained into a text source:

text = "Be careful otherwise police will capture you quickly."

I will need to look for words that ends with ful in my text string, then looking for words that ends with full in my dataset.

Author      DF_Text

31       Better the devil you know than the one you don't
53       Beware the door with too many keys.
563      Be careful what you tolerate. You are teaching people how to treat you.
41       Fear the Greeks bearing gifts.
539      NaN
51       The honey is sweet but the bee has a sting.
21       Be careful what you ask for; you may get it.

(from csv/txt file).
I need to extract words ending with ful in text, then look at both DF_Text (thus Author) which contains words ending with ful and appending results in a list.

n=0
for i in df['DF_Text']:
        print(re.findall(r"\w+ful", i))
        n=n+1
        print(n)

My question is: how can I remove empty rows([]) from the analysis (NaN) and report the author names (e.g. 563, 21) related to?
I will be happy to provide further information, in case it would be not clear.

Body:
I would use the .notna() function of Pandas to get rid of that row in your datafrae. l.
Something like this

df = df[df['DF_Text'].notna()]

And please note that Python calls the dataframe twice before overwriting it, this is correct.

See https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.notna.htm


问:
How to avoid splitting of word with case
Below is the text that I want to split:

```<code>string content = "Tonight the warning from the Police commissioner as they crack down on anyone who leaves there house without a 'reasonable excuse'
(TAKE SOT)"

string[] contentList = content.split(' ');
</code>```

I do not want to split the word i.e (TAKE SOT), if there is a text within parentheses and in an upper case then how to avoid splitting of the part.

Thanks

答:
The split method can have two parameters.The first one delimits the substrings in this instance.The second one  is the maximum number of elements expected in the array.

The following code snippet work for me, you can refer to it.

```<code>string content = "Tonight the warning from the Police commissioner as they crack down on anyone who leaves there house without a 'reasonable excuse' (TAKE SOT)";
            string[] contents = content.Split(" ", content.Substring(0, content.IndexOf("(")).Split(" ").Length);
</code>```

And this is the result of the code:

I use the method Split(String, Int32, StringSplitOptions)

Body:
Below is the text that I want to split:

string content = "Tonight the warning from the Police commissioner as they crack down on anyone who leaves there house without a 'reasonable excuse'
(TAKE SOT)"

string[] contentList = content.split(' ');

I do not want to split the word i.e (TAKE SOT), if there is a text within parentheses and in an upper case then how to avoid splitting of the part.

Thanks

Body:
The split method can have two parameters.The first one delimits the substrings in this instance.The second one  is the maximum number of elements expected in the array.

The following code snippet work for me, you can refer to it.

string content = "Tonight the warning from the Police commissioner as they crack down on anyone who leaves there house without a 'reasonable excuse' (TAKE SOT)";
            string[] contents = content.Split(" ", content.Substring(0, content.IndexOf("(")).Split(" ").Length);

And this is the result of the code:

I use the method Split(String, Int32, StringSplitOptions)


问:
Can ASP.NET MVC be applied to web services?
I'm planning architecture for a web-based application using web services.  It has been recommended that I look into using the ASP.NET MVC Framework.  All of the information I'm finding on the MVC discusses its use with web pages, but I have found nothing regarding web services.  Can the MVC be used for web services? and if so, where might I find resources to support my research effort?</p>

答: MVC is a UI design pattern. It is not a natural fit to web services.</p>

OwnerDisplayName: John Saunders

ContentLicense: CC BY-SA 2.5


问:
Open the View over the other not as a subView?
I want to overlap view over the another view. I don't want to add it as a subView. The new view should be added with following rect size (280,400) on the super view of size (320,460).

Can any one suggest me the right way for doing this.

Thanks in advance

答: You can do this by use of UIAnimations, replacing one view with the other.</p>


问:
Are go modules meant to be installed as executable programs or packages?
Can Go modules be built as an executable program? Or, are they meant to be published as libraries for code reuse?</p>

答: They're intended to work as packages, like something you would install from NPM for a JavaScript project, or from PIP in a Python project. </p>


问:
Determine the controller, action, and ID of the given URLs
Determine the controller, action, and ID of the given URLs. Recreate and complete the table on a clean sheet of a paper.This is the table that need to answer Please help for my assignment thank you.</p>

答:
Usually, MVC-based implementations route urls as - controller/action/id - so in your example too, you can deduce using the same pattern from the endpoints mentioned in your first column in the image. (for ex: if it says test/pre/1000, then it will be TestController, Action method is pre and id is 1000). For action the default value is Index, if you do not find anything after the controller name in the endpoint.

I suggest to do a bit more research on it online. I'm sure it will not be tough to find an answer for your question or any follow up such questions, pretty quickly. Please refer this as a first - https://www.tutorialsteacher.com/mvc/routing-in-mvc - explains clearly and it almost answers your question directly. Look at the URL Pattern and Configuring a Route sections in that link. Once you follow that in your hands-On trials and you still face issues in routing that is when stackoverflow can be an appropriate forum to find answers for your real time hurdles. Hope this helps.


答:
Some databases (namely, MySQL) support list of columns in count(distinct), so you can just do:

```<code>select count(testid, name) cnt
from product mp
join product_uom pu on pu.product_key = mp.product_key
join uom u on u.uom_id = pu.uom_id
join product_barcode pb on pb.product_uom_key = pu.product_uom_key
</code>```

Note that you should qualify the column names with the table they belong to, to make the query clearer and avoid ambiguity.
Another option is to concatenate the columns and use count(distinct). You need to chose a separator the does not appear in of the strings being concatenated to avoid "fake" duplicates:

```<code>select count(distinct concat(testid, '###', name)) cnt
from product mp
join product_uom pu on pu.product_key = mp.product_key
join uom u on u.uom_id = pu.uom_id
join product_barcode pb on pb.product_uom_key = pu.product_uom_key
</code>```

You can also use distinct  in a subquery, and then count():

```<code>select count(*) cnt
from (
    select distinct testid, name
    from product mp
    join product_uom pu on pu.product_key = mp.product_key
    join uom u on u.uom_id = pu.uom_id
    join product_barcode pb on pb.product_uom_key = pu.product_uom_key
) t
</code>```

Title: SQL query to find duplicate records and discount from COUNT with condition AND

Body:
Some databases (namely, MySQL) support list of columns in count(distinct), so you can just do:

select count(testid, name) cnt
from product mp
join product_uom pu on pu.product_key = mp.product_key
join uom u on u.uom_id = pu.uom_id
join product_barcode pb on pb.product_uom_key = pu.product_uom_key

Note that you should qualify the column names with the table they belong to, to make the query clearer and avoid ambiguity.
Another option is to concatenate the columns and use count(distinct). You need to chose a separator the does not appear in of the strings being concatenated to avoid "fake" duplicates:

select count(distinct concat(testid, '###', name)) cnt
from product mp
join product_uom pu on pu.product_key = mp.product_key
join uom u on u.uom_id = pu.uom_id
join product_barcode pb on pb.product_uom_key = pu.product_uom_key

You can also use distinct  in a subquery, and then count():

select count(*) cnt
from (
    select distinct testid, name
    from product mp
    join product_uom pu on pu.product_key = mp.product_key
    join uom u on u.uom_id = pu.uom_id
    join product_barcode pb on pb.product_uom_key = pu.product_uom_key
) t


问:
Passing user provided docker build argument to python program
I am trying to take user input as build argument for Dockerfile and trying to pass the same to python program. Here is my use case :

```<code>Dockerfile :

FROM centos:7
USER root
RUN yum install -y python36-devel python36-pip
ARG number
COPY . /app
RUN ls -l /app
RUN echo ${number}.   <=================This displays output in Docker build console
CMD python3 /app/app.py -t ${number}

app.py

import argparse
import time

def input():
    parser = argparse.ArgumentParser()
    parser.add_argument('number', help='take program number as input')
    args = parser.parse_args()
    return args

def root(args):
    for i in range(10):
        print("Hello World from : " + str(args.number))
        time.sleep(2)

if __name__ == "__main__":
    args = input()
    root(args)
</code>```

Docker build command :

docker build -t passarg:1 --build-arg number=1 .

Docker run command :

docker run passarg:1

Error :

usage: app.py [-h] number

app.py: error: the following arguments are required: number

答:
Misread, ENV and ARG parameter, was able to solve using run time parameter :

```<code>FROM centos:7
USER root
RUN yum install -y python36-devel python36-pip
COPY . /app
RUN ls -l /app
ENTRYPOINT ["python","/app/app.py"]
</code>```

Docker Run command :

$ docker run -it passarg:1  1

Body:
I am trying to take user input as build argument for Dockerfile and trying to pass the same to python program. Here is my use case :

Dockerfile :

FROM centos:7
USER root
RUN yum install -y python36-devel python36-pip
ARG number
COPY . /app
RUN ls -l /app
RUN echo ${number}.   <=================This displays output in Docker build console
CMD python3 /app/app.py -t ${number}

app.py

import argparse
import time

def input():
    parser = argparse.ArgumentParser()
    parser.add_argument('number', help='take program number as input')
    args = parser.parse_args()
    return args

def root(args):
    for i in range(10):
        print("Hello World from : " + str(args.number))
        time.sleep(2)

if __name__ == "__main__":
    args = input()
    root(args)

Docker build command :

docker build -t passarg:1 --build-arg number=1 .

Docker run command :

docker run passarg:1

Error :

usage: app.py [-h] number

app.py: error: the following arguments are required: number

Body:
Misread, ENV and ARG parameter, was able to solve using run time parameter :

FROM centos:7
USER root
RUN yum install -y python36-devel python36-pip
COPY . /app
RUN ls -l /app
ENTRYPOINT ["python","/app/app.py"]

Docker Run command :

$ docker run -it passarg:1  1


问:
How to return result of chained async functions?
Using Typescript 3.7.

Given the standard concept of command and command handler as defined here, with the handler being potentially asynchronous:

```<code>export type Command = { name: string; body: any };
export type CommandHandler<TCommand extends Command, TResult = any> = (cmd: TCommand) => TResult | Promise<TResult>;
</code>```

I'm trying to a create a function which, given an array of command handlers, will return a new command handler that effectively invokes each handler sequentially and returns the result of the last executed handler, thereby allowing any handler to interrupt the handler chain.

I would expect something like this to work:

```<code>export const chain = <TCommand extends Command, TResult = any>(
  ...handlers: CommandHandler<TCommand, TResult>[]
): CommandHandler<TCommand, TResult> => async cmd => {
  let result: TResult;
  for (const handler of handlers) {
    result = await handler(cmd);
  }

  return result;
};
</code>```

but the compiler is giving me this error: Variable 'result' is used before being assigned. ts(2454)

Why isn't this working and how should I go about organizing this code?

答:
If handlers is empty, TypeScript understands this as let result: TResult; return result, which returns undefined. any is rubbish and effectively disables TypeScript.

TypeScript uses the type any whenever it can’t tell what the type of an expression should be. Compared to Dynamic, calling any a type is an overstatement. It just turns off the type checker wherever it appears.

Consider this alternative -

```<code>type Command<T> =
  { name: string; body: T }

type CommandHandler<T> =
  (cmd: Command<T>) => Promise<T | void>

function chain <T>(...handlers: Array<CommandHandler<T>>): CommandHandler<T>
{ return async (cmd: Command<T>): Promise<T | void> =>
  { let r
    for (const h of handlers)
      r = await h(cmd)
    return r
  }
}
</code>```

Because we defined the return type of chain as CommandHandler<T> we don't even need the extra type hints around the async function -

```<code>type Command<T> =
  { name: string; body: T }

type CommandHandler<T> =
  (cmd: Command<T>) => Promise<T | void>

function chain <T>(...handlers: Array<CommandHandler<T>>): CommandHandler<T>
{ return async cmd =>  // <-- cmd inferred as Command<T>
  { let r
    for (const h of handlers)
      r = await h(cmd)
    return r // <-- inferred T | void
  }
}
</code>```

Demo: verify the results in this typescript sandbox

flexible return type

If you want your CommandHandlers to return a potentially different type, you can use two type variables -

type Command<T> =
  { name: string; body: T }

type CommandHandler<T,R> =                 // <--
  (cmd: Command<T>) => Promise<R | void>
```

<p>And heres' the updated <code>chain</code>. Now we can have an output type that differs from the input command type -</p>

```function chain <T,R>(...handlers: Array<CommandHandler<T,R>>): CommandHandler<T,R>
{ return async cmd =>  // <-- cmd inferred as Command<T>
  { let r
    for (const h of handlers)
      r = await h(cmd)
    return r // <-- inferred R | void
  }
}
```

Body:
Using Typescript 3.7.

Given the standard concept of command and command handler as defined here, with the handler being potentially asynchronous:

export type Command = { name: string; body: any };
export type CommandHandler<TCommand extends Command, TResult = any> = (cmd: TCommand) => TResult | Promise<TResult>;

I'm trying to a create a function which, given an array of command handlers, will return a new command handler that effectively invokes each handler sequentially and returns the result of the last executed handler, thereby allowing any handler to interrupt the handler chain.

I would expect something like this to work:

export const chain = <TCommand extends Command, TResult = any>(
  ...handlers: CommandHandler<TCommand, TResult>[]
): CommandHandler<TCommand, TResult> => async cmd => {
  let result: TResult;
  for (const handler of handlers) {
    result = await handler(cmd);
  }

  return result;
};

but the compiler is giving me this error: Variable 'result' is used before being assigned. ts(2454)

Why isn't this working and how should I go about organizing this code?

Body:
If handlers is empty, TypeScript understands this as let result: TResult; return result, which returns undefined. any is rubbish and effectively disables TypeScript.

TypeScript uses the type any whenever it can’t tell what the type of an expression should be. Compared to Dynamic, calling any a type is an overstatement. It just turns off the type checker wherever it appears.

Consider this alternative -

type Command<T> =
  { name: string; body: T }

type CommandHandler<T> =
  (cmd: Command<T>) => Promise<T | void>

function chain <T>(...handlers: Array<CommandHandler<T>>): CommandHandler<T>
{ return async (cmd: Command<T>): Promise<T | void> =>
  { let r
    for (const h of handlers)
      r = await h(cmd)
    return r
  }
}

Because we defined the return type of chain as CommandHandler<T> we don't even need the extra type hints around the async function -

type Command<T> =
  { name: string; body: T }

type CommandHandler<T> =
  (cmd: Command<T>) => Promise<T | void>

function chain <T>(...handlers: Array<CommandHandler<T>>): CommandHandler<T>
{ return async cmd =>  // <-- cmd inferred as Command<T>
  { let r
    for (const h of handlers)
      r = await h(cmd)
    return r // <-- inferred T | void
  }
}

Demo: verify the results in this typescript sandbox

flexible return type

If you want your CommandHandlers to return a potentially different type, you can use two type variables -

type Command<T> =
  { name: string; body: T }

type CommandHandler<T,R> =                 // <--
  (cmd: Command<T>) => Promise<R | void>

And heres' the updated chain. Now we can have an output type that differs from the input command type -

function chain <T,R>(...handlers: Array<CommandHandler<T,R>>): CommandHandler<T,R>
{ return async cmd =>  // <-- cmd inferred as Command<T>
  { let r
    for (const h of handlers)
      r = await h(cmd)
    return r // <-- inferred R | void
  }
}


问:
AWS Amplify and GraphQL Interfaces
How would you deal with interfaces and using them for connections in a data model using the AWS Amplify Model Transforms?

```<code>interface User @model {
  id: ID
  email: String
  created: AWSTimestamp
}

type ActiveUser implements User {
  id: ID
  first: String
  last: String
  email: String
  created: AWSTimestamp
}

type InvitedUser implements User {
  id: ID
  email: String
  created: AWSTimestamp
  invitedBy: String
}

type Team @model {
  users: [User] @connection
}
</code>```

It seems like my choices are to put @model on the types but then I get separate Dynamo tables and queries on the Query once amplify update api is run.

Can the transformer support interfaces as documented here: https://docs.aws.amazon.com/appsync/latest/devguide/interfaces-and-unions.html

I also found some support tickets, but was wondering if there was anything out there that enabled this feature. Here are the support tickets I found:

https://github.com/aws-amplify/amplify-cli/issues/1037

https://github.com/aws-amplify/amplify-cli/issues/202

答:
You only use @connection to link two databases together (which must be made from type and not interface), so if you don't want to do that then just get rid of the @connection and the Team database will simply have users be of type [User]. I am not entirely what you want to do but I would do something like:

```<code>type User @model {
  id: ID
  first: String!
  last: String!
  email: String!
  created: AWSTimestamp
  isActive: boolean
  invitedBy: String
  team: Team @connection(name: "UserTeamLink")
}

type Team @model {
  users: [User!] @connection(name: "UserTeamLink")
}
</code>```

Where the fields first, last, and email are required when creating a new user, and you can distinguish between an active user with a boolean, and when you query the User database it returns the Team item from the Team database as well (I am guessing you want other fields like team name, etc.?), so when you create a Team object you pass in the teamUserId (not shown below but created when using amplify) that will allow you to attach a newly created Team to an existing user or group of users.

Title: AWS Amplify and GraphQL Interfaces

Body:
How would you deal with interfaces and using them for connections in a data model using the AWS Amplify Model Transforms?

interface User @model {
  id: ID
  email: String
  created: AWSTimestamp
}

type ActiveUser implements User {
  id: ID
  first: String
  last: String
  email: String
  created: AWSTimestamp
}

type InvitedUser implements User {
  id: ID
  email: String
  created: AWSTimestamp
  invitedBy: String
}

type Team @model {
  users: [User] @connection
}

It seems like my choices are to put @model on the types but then I get separate Dynamo tables and queries on the Query once amplify update api is run.

Can the transformer support interfaces as documented here: https://docs.aws.amazon.com/appsync/latest/devguide/interfaces-and-unions.html

I also found some support tickets, but was wondering if there was anything out there that enabled this feature. Here are the support tickets I found:

https://github.com/aws-amplify/amplify-cli/issues/1037

https://github.com/aws-amplify/amplify-cli/issues/202

Body:
You only use @connection to link two databases together (which must be made from type and not interface), so if you don't want to do that then just get rid of the @connection and the Team database will simply have users be of type [User]. I am not entirely what you want to do but I would do something like:

type User @model {
  id: ID
  first: String!
  last: String!
  email: String!
  created: AWSTimestamp
  isActive: boolean
  invitedBy: String
  team: Team @connection(name: "UserTeamLink")
}

type Team @model {
  users: [User!] @connection(name: "UserTeamLink")
}

Where the fields first, last, and email are required when creating a new user, and you can distinguish between an active user with a boolean, and when you query the User database it returns the Team item from the Team database as well (I am guessing you want other fields like team name, etc.?), so when you create a Team object you pass in the teamUserId (not shown below but created when using amplify) that will allow you to attach a newly created Team to an existing user or group of users.


问:
SwiftUI, Fatal error: Unexpectedly found nil while unwrapping an Optional value
```<code>func loadImageFromUrl() {

        guard let urlString = self.urlString else {
        return
    }

    let url = URL(string: urlString)!
        let task = URLSession.shared.dataTask(with: url, completionHandler: self.getImageFromResponse(data:response:error:))
        task.resume()
}
</code>```

I keep on getting this fatal error (mentioned in title) for let url = URL(string: urlString)!, even if I have tried to guard it in previous lines. Also, when I move my cursor over urlString, it indeed shows a highlight of my intended url from the API.

答:
This should work</p>

```<code>if let url = URL(string: urlString) {
    let task = URLSession.shared.dataTask(with: url,
       completionHandler: self.getImageFromResponse(data:response:error:))
    task.resume()
}
</code>```

Body:
func loadImageFromUrl() {

        guard let urlString = self.urlString else {
        return
    }

    let url = URL(string: urlString)!
        let task = URLSession.shared.dataTask(with: url, completionHandler: self.getImageFromResponse(data:response:error:))
        task.resume()
}

I keep on getting this fatal error (mentioned in title) for let url = URL(string: urlString)!, even if I have tried to guard it in previous lines. Also, when I move my cursor over urlString, it indeed shows a highlight of my intended url from the API.

Body:
This should work

if let url = URL(string: urlString) {
    let task = URLSession.shared.dataTask(with: url,
       completionHandler: self.getImageFromResponse(data:response:error:))
    task.resume()
}


问:
Kubernetes certificate always disappear after few hours
I am new to kubernetes. I created a certificate in kubernetes for my validation webhook.
After approving the certificate, and checking if it is still there after few hours, by running

```<code>kubectl -n mynamespace get csr
</code>```

However, it shows no resources found in the namespace. But if the certificate is newly created
and run the same command above it shows the certificate.

Is this an expected behavior? where does the certificate go?

Please help. :(

答:
csr is short for Certificate Signing Requests

It dismiss after validated.

If your want to check certificates:

```<code>kubectl get cert -A
</code>```

-A for --all-namespaces

Body:
I am new to kubernetes. I created a certificate in kubernetes for my validation webhook.
After approving the certificate, and checking if it is still there after few hours, by running

kubectl -n mynamespace get csr

However, it shows no resources found in the namespace. But if the certificate is newly created
and run the same command above it shows the certificate.

Is this an expected behavior? where does the certificate go?

Please help. :(

Body:
csr is short for Certificate Signing Requests

It dismiss after validated.

If your want to check certificates:

kubectl get cert -A

-A for --all-namespaces


问:
Is there a way to dynamically change maximumSelectionLength on kartik/select2 in yii2?
I am trying to update through javascript the maximumSelectionLength parameter of a select2 field (listeProduits) based on the value of a second select2 (nom_id) when it is changed.
I'm first storing the maxChildren values in a js table before loading the form so that I can access it on the client side when a new nom_id is selected.
The below approach doesn't work though as it messes up the listeProduits select2.

```<code><script>
var nomMaxChildren = <?= json_encode(ArrayHelper::map(Nom::find()->asArray()->where(['type' => 'Boite'])->all(), 'id', 'max_children')); ?>;
alert(nomMaxChildren[1]);
</script>
<?php $form = ActiveForm::begin(); ?>

<?= $form->field($model, 'nom_id')->widget(Select2::classname(), [
    'data' => ArrayHelper::map(Nom::find()->asArray()->where(['type' => 'Boite'])->all(), 'id', 'nom'),
    'options' => ['placeholder' => Yii::t('app','Select a name...')],
    'pluginEvents' => [
       "select2:select" => "function() {
            $('select[name =\"listeProduits[]\"]').select2({
                maximumSelectionLength: nomMaxChildren[\$(this).val()]
            });
       }",
    ]
]);?>

<label class="control-label"><?= Yii::t('app', 'Produits')?></label>';

<?= Select2::widget([
    'attribute' => 'listeProduits',
    'name' => 'listeProduits',
    'data' => ArrayHelper::map(Produit::find()->asArray()->where(['statut_id' => 2])->andWhere(['boite_id' => null])->orWhere(['boite_id' => $model->id])->all(), 'id', 'numero_de_serie'),
    'value' => (is_null($model->id)) ? null : ArrayHelper::map(Produit::find()->asArray()->where(['boite_id' => $model->id])->all(), 'id', 'id'),
    'options' => ['placeholder' => Yii::t('app','Select products')],
    'pluginOptions' => [
        'allowClear' => true,
        'multiple' => true,
        'maximumSelectionLength' => (isset($model->nom)) ? $model->nom->max_children : null,
    ],
    'showToggleAll' => false,
]);?>
</code>```

Also if you have any idea on how to validate the fact that the maximumSelectionLength is ok on client side, it would be great :D

答:
set maximumSelectionLength property dynamically :

```<code>$('#demo-select').select2({ maximumSelectionLength: 1 });
</code>```

Body:
I am trying to update through javascript the maximumSelectionLength parameter of a select2 field (listeProduits) based on the value of a second select2 (nom_id) when it is changed.
I'm first storing the maxChildren values in a js table before loading the form so that I can access it on the client side when a new nom_id is selected.
The below approach doesn't work though as it messes up the listeProduits select2.

<?php $form = ActiveForm::begin(); ?>

<?= $form->field($model, 'nom_id')->widget(Select2::classname(), [
    'data' => ArrayHelper::map(Nom::find()->asArray()->where(['type' => 'Boite'])->all(), 'id', 'nom'),
    'options' => ['placeholder' => Yii::t('app','Select a name...')],
    'pluginEvents' => [
       "select2:select" => "function() {
            $('select[name =\"listeProduits[]\"]').select2({
                maximumSelectionLength: nomMaxChildren[\$(this).val()]
            });
       }",
    ]
]);?>

<?= Yii::t('app', 'Produits')?>';

<?= Select2::widget([
    'attribute' => 'listeProduits',
    'name' => 'listeProduits',
    'data' => ArrayHelper::map(Produit::find()->asArray()->where(['statut_id' => 2])->andWhere(['boite_id' => null])->orWhere(['boite_id' => $model->id])->all(), 'id', 'numero_de_serie'),
    'value' => (is_null($model->id)) ? null : ArrayHelper::map(Produit::find()->asArray()->where(['boite_id' => $model->id])->all(), 'id', 'id'),
    'options' => ['placeholder' => Yii::t('app','Select products')],
    'pluginOptions' => [
        'allowClear' => true,
        'multiple' => true,
        'maximumSelectionLength' => (isset($model->nom)) ? $model->nom->max_children : null,
    ],
    'showToggleAll' => false,
]);?>

Also if you have any idea on how to validate the fact that the maximumSelectionLength is ok on client side, it would be great :D

Body:
set maximumSelectionLength property dynamically :

$('#demo-select').select2({ maximumSelectionLength: 1 });


问:
Android : how to pass a integer value to service using KSOAP in android
Not able to pass an integer value to the service request.The value that reaches service request becomes null
Here is my code

```<code>private static final String METHOD_NAME ="GetPrivileges";
private static final String NAMESPACE = "http://AuthorizationManagement.ServiceContracts/2007/01/";
private static final String URL ="http://192.168.5.219/NTLS_Authorization
</code>```

/AuthorisationManager.asmx";

```<code>final String SOAP_ACTION ="http://AuthorizationManagement.ServiceContracts/2007/01/GetPrivileges";
    public void call() {
        try {
            SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

            PropertyInfo pi=new PropertyInfo();
            pi.type=PropertyInfo.INTEGER_CLASS;
            pi.setName("RoleID");
            pi.setValue(3);
            pi.setNamespace(NAMESPACE);
            request.addProperty(pi);

            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
            envelope.dotNet = true;
            envelope.setOutputSoapObject(request);

            HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
            androidHttpTransport.call(SOAP_ACTION, envelope);

            Object result = envelope.getResponse();

            String resultData = result.toString();
</code>```

答:
```<code> public void call(int number)
        {
            try
            {
                  String METHOD_NAME ="GetPrivileges";
                   String NAMESPACE = "http://AuthorizationManagement.ServiceContracts/2007/01/";
                   String URL ="http://192.168.5.219/NTLS_Authorization/AuthorisationManager.asmx";
                final String SOAP_ACTION ="http://AuthorizationManagement.ServiceContracts/2007/01/GetPrivileges";
                SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
                request.addProperty("RoleID",number);

                SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
                envelope.dotNet = true;
                envelope.setOutputSoapObject(request);

                AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(URL);
                androidHttpTransport.call(SOAP_ACTION, envelope);

                Object result = envelope.getResponse();

                String resultData = result.toString();
                Log.v("Result==>",resultData);
            }
            catch(Exception e)
            {
                e.printStackTrace();
                }
        }
</code>```

Body:
Not able to pass an integer value to the service request.The value that reaches service request becomes null
Here is my code

private static final String METHOD_NAME ="GetPrivileges";
private static final String NAMESPACE = "http://AuthorizationManagement.ServiceContracts/2007/01/";
private static final String URL ="http://192.168.5.219/NTLS_Authorization

/AuthorisationManager.asmx";

final String SOAP_ACTION ="http://AuthorizationManagement.ServiceContracts/2007/01/GetPrivileges";
    public void call() {
        try {
            SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

            PropertyInfo pi=new PropertyInfo();
            pi.type=PropertyInfo.INTEGER_CLASS;
            pi.setName("RoleID");
            pi.setValue(3);
            pi.setNamespace(NAMESPACE);
            request.addProperty(pi);

            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
            envelope.dotNet = true;
            envelope.setOutputSoapObject(request);

            HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
            androidHttpTransport.call(SOAP_ACTION, envelope);

            Object result = envelope.getResponse();

            String resultData = result.toString();


问:
AsyncStorage functions just producing garbage in react native
So I implemented this code in a file from the react native docs.

```<code>class Storage {

    //store data in 'key'

    store = async (key, data) => {
        try {
            await AsyncStorage.setItem(key, data);
        } catch (error) {
            // Error saving data
            console.log(error.message);
        }
    };

    retrieve = async (key) => {
        try {
            const   value = await AsyncStorage.getItem(key);
            if (value !== null) {
                // We have data!!
                console.log(value);
            }
        } catch (error) {
            // Error retrieving data
            console.log(error.message);
        }
    };

}
</code>```

And this in other I want to use to actually store and retrieve the variables:

```<code>strg.store('test', 'testing');
testing =  strg.retrieve('test');
</code>```

I kept getting an error but then looking it up here I figured out my storage output was an object and not a string as I expected. So I used JSON.stringify(***) and this gibberish came out instead of a "testing".

{"_40":0, "_65":0, "_55":null,"_72":null}
```

edit: I figure out how to use the console to debug and I found out the 'testing' was inside the promise object that comes out of my function. I read a little about async functions and now I want to know how do I extract the values from the promises?

答:
Your store and retrieve functions are asyn so you have to use await until the actual task is complete.

    So the code should be like below.
    await strg.store('test', 'testing');
    const testing = await strg.retrieve('test');
```

<p>The garbage value is a promise so it will be something like the object you got.</p>

<p>If you return value like this you will retrieve it from outside.</p>

<pre class="lang-js prettyprint-override"><code>           const value = await AsyncStorage.getItem(key);
            if (value !== null) {
                // We have data!!
                console.log(value);

            return value;
            }
</code>```

Body:
So I implemented this code in a file from the react native docs.

class Storage {

    //store data in 'key'

    store = async (key, data) => {
        try {
            await AsyncStorage.setItem(key, data);
        } catch (error) {
            // Error saving data
            console.log(error.message);
        }
    };

    retrieve = async (key) => {
        try {
            const   value = await AsyncStorage.getItem(key);
            if (value !== null) {
                // We have data!!
                console.log(value);
            }
        } catch (error) {
            // Error retrieving data
            console.log(error.message);
        }
    };

}

And this in other I want to use to actually store and retrieve the variables:

strg.store('test', 'testing');
testing =  strg.retrieve('test');

I kept getting an error but then looking it up here I figured out my storage output was an object and not a string as I expected. So I used JSON.stringify(***) and this gibberish came out instead of a "testing".

{"_40":0, "_65":0, "_55":null,"_72":null}

edit: I figure out how to use the console to debug and I found out the 'testing' was inside the promise object that comes out of my function. I read a little about async functions and now I want to know how do I extract the values from the promises?

Body:
Your store and retrieve functions are asyn so you have to use await until the actual task is complete.

    So the code should be like below.
    await strg.store('test', 'testing');
    const testing = await strg.retrieve('test');

The garbage value is a promise so it will be something like the object you got.

If you return value like this you will retrieve it from outside.

           const value = await AsyncStorage.getItem(key);
            if (value !== null) {
                // We have data!!
                console.log(value);

            return value;
            }