问:
Python multiprocessing, functions with arguments
I have a program that simulates an entire baseball season, but does a lot of calculations per game, so each game takes around 30 seconds to run. With 2430 games in a season, the program takes about 20 hours to run, per season. Obviously I'd like to speed this up, so the most immediate solution seems like multiprocessing. I could manually split it up into groups of ~600 and run four processes, but I'd like to figure out how the multiprocessing module works.

Here's what I've tried so far, but obviously it doesn't work.

```<code>def test_func():
    algorithm_selection = 1

    # Create sqlite database connection
    conn = sqlite3.connect('C:/F5 Prediction Engine/sqlite3/Version 2/statcast_db.db')
    c = conn.cursor()

    season = input('Year to simulate: ')
    c.execute('SELECT * FROM gamelogs_' + season)
    season_games = c.fetchall()

    game_num = 0
    for game in season_games:

        game_num = game_num + 1
        #Get away lineup in terms of MLB IDs
        away_lineup = ConvertLineup(game[105], game[108], game[111], game[114], game[117], game[120], game[123], game[126], game[129])
        #Get home lineup in terms of MLB IDs
        home_lineup = ConvertLineup(game[132], game[135], game[138], game[141], game[144], game[147], game[150], game[153], game[156])
        #Get away starting pitcher and hand in terms of MLB ID
        away_pitcher_results = GetPitcherIDandHand(game[101])
        away_pitcher_id = away_pitcher_results[0][0]
        away_pitcher_hand = away_pitcher_results[0][1]
        #Get home starting pitcher and hand in terms of MLB ID
        home_pitcher_results = GetPitcherIDandHand(game[103])
        home_pitcher_id = home_pitcher_results[0][0]
        home_pitcher_hand = home_pitcher_results[0][1]
        #Get the date of the game
        today_date = game[0]

        if algorithm_selection == 1:
            #Check if the current game has already been evaluated and entered into the database
            c.execute('SELECT * FROM pemstein_results_' + season + ' WHERE date = "' + game[0] + '" AND away_team = "' + game[3] + '" AND home_team = "' + game[6] + \
                  '" AND away_team_score = "' + game[9] + '" AND home_team_score = "' + game[10] + '"')
            check_results = c.fetchall()
            if len(check_results) == 0:
                exp_slgs = PemsteinSimulation(home_pitcher_id, away_pitcher_id, season, home_pitcher_hand, away_pitcher_hand, home_lineup, away_lineup, game[0])
                if exp_slgs[2] == 0: #if both pitches had at least 300 PAs to use for simulation
                    c.execute([long string to insert results into database])
                conn.commit()
                print('Game ' + str(game_num) + ' finished.')
                if exp_slgs[2] == 1: #if one of the pitches did not have enough PAs to qualify
                    c.execute([long string to insert results into database])
                    conn.commit()
                    print('Game ' + str(game_num) + ' finished.')
            if len(check_results) > 0:
                print('Game ' + str(game_num) + ' has already been evaluated.')

from multiprocessing import Process
import os

processes = []

for i in range(0, os.cpu_count()):
    print('Registering process %d' % i)
    processes.append(Process(target=test))

for process in processes:
    process.start()

for process in processes:
    process.join()
</code>```

==================

Edit: new code

```<code>#Child Process
def simulate_games(games_list, counter, lock):
    while(1):
        # Create sqlite database connection
        conn = sqlite3.connect('C:/F5 Prediction Engine/sqlite3/Version 2/statcast_db.db')
        c = conn.cursor()

        #acquire the lock which grants access to the shared variable
        with lock:

            #check the termination condition
            if counter >= len(games_list):
                break

            #get the game_num and game to simulate
            game_num = counter.value
            game_to_simulate = game_list[counter.value]

            #update the counter for the next process
            counter.value += 1

        #Do simulation
        game_num = 0

        game_num = game_num + 1
        #Get away lineup in terms of MLB IDs
        away_lineup = ConvertLineup(game_to_simulate[105], game_to_simulate[108], game_to_simulate[111], game_to_simulate[114], game_to_simulate[117], game_to_simulate[120], game_to_simulate[123], game_to_simulate[126], game_to_simulate[129])
        #Get home lineup in terms of MLB IDs
        home_lineup = ConvertLineup(game_to_simulate[132], game_to_simulate[135], game_to_simulate[138], game_to_simulate[141], game_to_simulate[144], game_to_simulate[147], game_to_simulate[150], game_to_simulate[153], game_to_simulate[156])
        #Get away starting pitcher and hand in terms of MLB ID
        away_pitcher_results = GetPitcherIDandHand(game[101])
        away_pitcher_id = away_pitcher_results[0][0]
        away_pitcher_hand = away_pitcher_results[0][1]
        #Get home starting pitcher and hand in terms of MLB ID
        home_pitcher_results = GetPitcherIDandHand(game[103])
        home_pitcher_id = home_pitcher_results[0][0]
        home_pitcher_hand = home_pitcher_results[0][1]
        #Get the date of the game
        today_date = game_to_simulate[0]
        if algorithm_selection == 1:
            #Check if the current game has already been evaluated and entered into the database
            c.execute('SELECT * FROM pemstein_results_' + season + ' WHERE date = "' + game_to_simulate[0] + '" AND away_team = "' + game_to_simulate[3] + '" AND home_team = "' + game_to_simulate[6] + \
                      '" AND away_team_score = "' + game_to_simulate[9] + '" AND home_team_score = "' + game_to_simulate[10] + '"')
            check_results = c.fetchall()
            if len(check_results) == 0:
                exp_slgs = PemsteinSimulation(home_pitcher_id, away_pitcher_id, season, home_pitcher_hand, away_pitcher_hand, home_lineup, away_lineup, game_to_simulate[0])
                if exp_slgs[2] == 0: #if both pitches had at least 300 PAs to use for simulation
                    c.execute('long sql')
                    conn.commit()
                    print('Game ' + str(game_num) + ' finished.')
                if exp_slgs[2] == 1: #if one of the pitches did not have enough PAs to qualify
                    c.execute('long sql')
                    conn.commit()
                    print('Game ' + str(game_num) + ' finished.')
            if len(check_results) > 0:
                print('Game ' + str(game_num) + ' has already been evaluated.')

if __name__ == "__main__":
    # Create sqlite database connection
    conn = sqlite3.connect('C:/F5 Prediction Engine/sqlite3/Version 2/statcast_db.db')
    c = conn.cursor()

    #Query all games for season to be simulated
    season = int(input('Year to simulate: '))
    c.execute('SELECT * FROM gamelogs_' + str(season))
    season_games = c.fetchall()

    algorithmSelection = 1

    if algorithmSelection == 1:
        PemsteinSQLresults(str(season))

    counter = mp.Value('i', 0)
    lock = mp.Lock()
    children = []
    for i in range(os.cpu_count()):
        children.append(mp.Process(target=simulate_games, args=(season_games, counter, lock)))

    for child in children:
        child.start()

    for child in children:
        child.join()
</code>```

Error:

```<code>Traceback (most recent call last):
  File "C:\F5 Prediction Engine\Version 2\SimulateSeason v2.py", line 126, in <module>
    child.start()
  File "C:\Python\lib\multiprocessing\process.py", line 105, in start
    self._popen = self._Popen(self)
  File "C:\Python\lib\multiprocessing\context.py", line 223, in _Popen
    return _default_context.get_context().Process._Popen(process_obj)
  File "C:\Python\lib\multiprocessing\context.py", line 322, in _Popen
    return Popen(process_obj)
  File "C:\Python\lib\multiprocessing\popen_spawn_win32.py", line 65, in __init__
    reduction.dump(process_obj, to_child)
  File "C:\Python\lib\multiprocessing\reduction.py", line 60, in dump
    ForkingPickler(file, protocol).dump(obj)
BrokenPipeError: [Errno 32] Broken pipe
</code>```

=============

So I went to this website to review some things, and tried a new script with the following code that I copied from the site:

```<code>import mp

def worker(num):
    """thread worker function"""
    print('Worker:' + num)
    return

if __name__ == '__main__':
    jobs = []
    for i in range(5):
        p = mp.Process(target=worker, args=(i,))
        jobs.append(p)
        p.start()
</code>```

But it likewise doesn't do anything. The site says it should print Worker:0 Worker:1 etc, but I'm getting no prints. Is it possible there's something wrong locally on my machine?

答:
It seems to me that you have simply tried to instantiate a new process for each cpu and had them run the same function that you wrote at first, however if you want to work with processes you would have to adapt it and handle process synchonization.

As an example you could have a master process which prompts the user for the season year, fetches all the games for that year and then the child processes would read from the resulting array. See the following example:

```<code># Parent Process
import multiprocessing as mp

# establish db connection [ ... ]

season = int(input("Year to simulate: "))
c.execute('SELECT * FROM gamelogs_' + season)
season_games = c.fetchall()

counter = mp.Value("i", 0)
lock = mp.Lock()
children = []
for i in range(os.cpu_count()):
    children.append(mp.Process(target=simulate_games, args=(season_games, counter, lock,)))

for child in children:
    child.start()

for child in children:
    child.join()

# Child Process
def simulate_games(games_list, counter, lock):
    while(1):
        # acquire the lock which grants the access to the shared variable
        with lock:

            # check the termination condition
            if counter.value >= len(games_list):
                break

            # get the game_num and the game to simulate
            game_num = counter.value
            game_to_simulate = games_list[counter.value]

            # update counter for the next process
            counter.value += 1

        #  Do simulation here
</code>```

What we have above is a parent process which is basically preparing some data and creating new child processes.

The counter is implemented by means of a special class, i.e Value, which is used for sharing scalar values among processes; Lock is basically a mutex, which we use to synchronize the access to the counter variable and avoid concurrent access: note that you could have used the Lock which is automatically created inside of the counter shared variable, but I thought it would be easier to understand by separating the two.

The children processes by first acquiring the lock, read the counter value and increment it, then proceed to their normal behavior, thus simulating the games

Body:
I have a program that simulates an entire baseball season, but does a lot of calculations per game, so each game takes around 30 seconds to run. With 2430 games in a season, the program takes about 20 hours to run, per season. Obviously I'd like to speed this up, so the most immediate solution seems like multiprocessing. I could manually split it up into groups of ~600 and run four processes, but I'd like to figure out how the multiprocessing module works.

Here's what I've tried so far, but obviously it doesn't work.

def test_func():
    algorithm_selection = 1

    # Create sqlite database connection
    conn = sqlite3.connect('C:/F5 Prediction Engine/sqlite3/Version 2/statcast_db.db')
    c = conn.cursor()

    season = input('Year to simulate: ')
    c.execute('SELECT * FROM gamelogs_' + season)
    season_games = c.fetchall()

    game_num = 0
    for game in season_games:

        game_num = game_num + 1
        #Get away lineup in terms of MLB IDs
        away_lineup = ConvertLineup(game[105], game[108], game[111], game[114], game[117], game[120], game[123], game[126], game[129])
        #Get home lineup in terms of MLB IDs
        home_lineup = ConvertLineup(game[132], game[135], game[138], game[141], game[144], game[147], game[150], game[153], game[156])
        #Get away starting pitcher and hand in terms of MLB ID
        away_pitcher_results = GetPitcherIDandHand(game[101])
        away_pitcher_id = away_pitcher_results[0][0]
        away_pitcher_hand = away_pitcher_results[0][1]
        #Get home starting pitcher and hand in terms of MLB ID
        home_pitcher_results = GetPitcherIDandHand(game[103])
        home_pitcher_id = home_pitcher_results[0][0]
        home_pitcher_hand = home_pitcher_results[0][1]
        #Get the date of the game
        today_date = game[0]

        if algorithm_selection == 1:
            #Check if the current game has already been evaluated and entered into the database
            c.execute('SELECT * FROM pemstein_results_' + season + ' WHERE date = "' + game[0] + '" AND away_team = "' + game[3] + '" AND home_team = "' + game[6] + \
                  '" AND away_team_score = "' + game[9] + '" AND home_team_score = "' + game[10] + '"')
            check_results = c.fetchall()
            if len(check_results) == 0:
                exp_slgs = PemsteinSimulation(home_pitcher_id, away_pitcher_id, season, home_pitcher_hand, away_pitcher_hand, home_lineup, away_lineup, game[0])
                if exp_slgs[2] == 0: #if both pitches had at least 300 PAs to use for simulation
                    c.execute([long string to insert results into database])
                conn.commit()
                print('Game ' + str(game_num) + ' finished.')
                if exp_slgs[2] == 1: #if one of the pitches did not have enough PAs to qualify
                    c.execute([long string to insert results into database])
                    conn.commit()
                    print('Game ' + str(game_num) + ' finished.')
            if len(check_results) > 0:
                print('Game ' + str(game_num) + ' has already been evaluated.')

from multiprocessing import Process
import os

processes = []

for i in range(0, os.cpu_count()):
    print('Registering process %d' % i)
    processes.append(Process(target=test))

for process in processes:
    process.start()

for process in processes:
    process.join()

==================

Edit: new code

#Child Process
def simulate_games(games_list, counter, lock):
    while(1):
        # Create sqlite database connection
        conn = sqlite3.connect('C:/F5 Prediction Engine/sqlite3/Version 2/statcast_db.db')
        c = conn.cursor()

        #acquire the lock which grants access to the shared variable
        with lock:

            #check the termination condition
            if counter >= len(games_list):
                break

            #get the game_num and game to simulate
            game_num = counter.value
            game_to_simulate = game_list[counter.value]

            #update the counter for the next process
            counter.value += 1

        #Do simulation
        game_num = 0

        game_num = game_num + 1
        #Get away lineup in terms of MLB IDs
        away_lineup = ConvertLineup(game_to_simulate[105], game_to_simulate[108], game_to_simulate[111], game_to_simulate[114], game_to_simulate[117], game_to_simulate[120], game_to_simulate[123], game_to_simulate[126], game_to_simulate[129])
        #Get home lineup in terms of MLB IDs
        home_lineup = ConvertLineup(game_to_simulate[132], game_to_simulate[135], game_to_simulate[138], game_to_simulate[141], game_to_simulate[144], game_to_simulate[147], game_to_simulate[150], game_to_simulate[153], game_to_simulate[156])
        #Get away starting pitcher and hand in terms of MLB ID
        away_pitcher_results = GetPitcherIDandHand(game[101])
        away_pitcher_id = away_pitcher_results[0][0]
        away_pitcher_hand = away_pitcher_results[0][1]
        #Get home starting pitcher and hand in terms of MLB ID
        home_pitcher_results = GetPitcherIDandHand(game[103])
        home_pitcher_id = home_pitcher_results[0][0]
        home_pitcher_hand = home_pitcher_results[0][1]
        #Get the date of the game
        today_date = game_to_simulate[0]
        if algorithm_selection == 1:
            #Check if the current game has already been evaluated and entered into the database
            c.execute('SELECT * FROM pemstein_results_' + season + ' WHERE date = "' + game_to_simulate[0] + '" AND away_team = "' + game_to_simulate[3] + '" AND home_team = "' + game_to_simulate[6] + \
                      '" AND away_team_score = "' + game_to_simulate[9] + '" AND home_team_score = "' + game_to_simulate[10] + '"')
            check_results = c.fetchall()
            if len(check_results) == 0:
                exp_slgs = PemsteinSimulation(home_pitcher_id, away_pitcher_id, season, home_pitcher_hand, away_pitcher_hand, home_lineup, away_lineup, game_to_simulate[0])
                if exp_slgs[2] == 0: #if both pitches had at least 300 PAs to use for simulation
                    c.execute('long sql')
                    conn.commit()
                    print('Game ' + str(game_num) + ' finished.')
                if exp_slgs[2] == 1: #if one of the pitches did not have enough PAs to qualify
                    c.execute('long sql')
                    conn.commit()
                    print('Game ' + str(game_num) + ' finished.')
            if len(check_results) > 0:
                print('Game ' + str(game_num) + ' has already been evaluated.')

if __name__ == "__main__":
    # Create sqlite database connection
    conn = sqlite3.connect('C:/F5 Prediction Engine/sqlite3/Version 2/statcast_db.db')
    c = conn.cursor()

    #Query all games for season to be simulated
    season = int(input('Year to simulate: '))
    c.execute('SELECT * FROM gamelogs_' + str(season))
    season_games = c.fetchall()

    algorithmSelection = 1

    if algorithmSelection == 1:
        PemsteinSQLresults(str(season))

    counter = mp.Value('i', 0)
    lock = mp.Lock()
    children = []
    for i in range(os.cpu_count()):
        children.append(mp.Process(target=simulate_games, args=(season_games, counter, lock)))

    for child in children:
        child.start()

    for child in children:
        child.join()

Error:

Traceback (most recent call last):
  File "C:\F5 Prediction Engine\Version 2\SimulateSeason v2.py", line 126, in <module>
    child.start()
  File "C:\Python\lib\multiprocessing\process.py", line 105, in start
    self._popen = self._Popen(self)
  File "C:\Python\lib\multiprocessing\context.py", line 223, in _Popen
    return _default_context.get_context().Process._Popen(process_obj)
  File "C:\Python\lib\multiprocessing\context.py", line 322, in _Popen
    return Popen(process_obj)
  File "C:\Python\lib\multiprocessing\popen_spawn_win32.py", line 65, in __init__
    reduction.dump(process_obj, to_child)
  File "C:\Python\lib\multiprocessing\reduction.py", line 60, in dump
    ForkingPickler(file, protocol).dump(obj)
BrokenPipeError: [Errno 32] Broken pipe

=============

So I went to this website to review some things, and tried a new script with the following code that I copied from the site:

import mp

def worker(num):
    """thread worker function"""
    print('Worker:' + num)
    return

if __name__ == '__main__':
    jobs = []
    for i in range(5):
        p = mp.Process(target=worker, args=(i,))
        jobs.append(p)
        p.start()

But it likewise doesn't do anything. The site says it should print Worker:0 Worker:1 etc, but I'm getting no prints. Is it possible there's something wrong locally on my machine?

Body:
It seems to me that you have simply tried to instantiate a new process for each cpu and had them run the same function that you wrote at first, however if you want to work with processes you would have to adapt it and handle process synchonization.

As an example you could have a master process which prompts the user for the season year, fetches all the games for that year and then the child processes would read from the resulting array. See the following example:

# Parent Process
import multiprocessing as mp

# establish db connection [ ... ]

season = int(input("Year to simulate: "))
c.execute('SELECT * FROM gamelogs_' + season)
season_games = c.fetchall()

counter = mp.Value("i", 0)
lock = mp.Lock()
children = []
for i in range(os.cpu_count()):
    children.append(mp.Process(target=simulate_games, args=(season_games, counter, lock,)))

for child in children:
    child.start()

for child in children:
    child.join()

# Child Process
def simulate_games(games_list, counter, lock):
    while(1):
        # acquire the lock which grants the access to the shared variable
        with lock:

            # check the termination condition
            if counter.value >= len(games_list):
                break

            # get the game_num and the game to simulate
            game_num = counter.value
            game_to_simulate = games_list[counter.value]

            # update counter for the next process
            counter.value += 1

        #  Do simulation here

What we have above is a parent process which is basically preparing some data and creating new child processes.

The counter is implemented by means of a special class, i.e Value, which is used for sharing scalar values among processes; Lock is basically a mutex, which we use to synchronize the access to the counter variable and avoid concurrent access: note that you could have used the Lock which is automatically created inside of the counter shared variable, but I thought it would be easier to understand by separating the two.

The children processes by first acquiring the lock, read the counter value and increment it, then proceed to their normal behavior, thus simulating the games


来源: stackexchange

问:
PHP - How to get OAuth 2.0 Token
I want to connect to OAuth 2.0 authorization type (with password grant_type) to get token with POST method, it's ok to test from Postman but i couldn't connect through PHP...

here's my information:

request url: 'http://example.com/core/connect/token'

ClientName: 'something1'

ClientId: 'something2'

Secret: 'something3'

UserName: 'something4'

Password: 'something5'

Scope: 'something6'

could you please just give me an example to get token and use?

i've already tested:

```<code>$base_url = 'https://example.com/oauth/token';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $base_url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
        'client_id'     => YOUR-CLIENT-ID,
        'client_secret' => YOUR-CLIENT-SECRET,
        'username'      => YOUR-USERNAME-OR-EMAIL,
        'password'      => YOUR-PASSWORD,
        'grant_type'    => 'password'
));

$data = curl_exec($ch);

$auth_string = json_decode($data, true);
</code>```

and this

```<code>$api = "KEY GOES HERE";
$authurl = "http://example.com/core/connect/token";

$client_id = "ID GOES HERE";
$client_secret = "SECRET GOES HERE";

// Creating base 64 encoded authkey
$Auth_Key = $client_id.":".$client_secret;
$encoded_Auth_Key=base64_encode($Auth_Key);

$headers = array();
$headers['Authorization'] = "Basic ".$encoded_Auth_Key;
$headers['Content-Type'] = "application/x-www-form-urlencoded";

$data = array(
    'grant_type' => 'password',
    'scope'      => 'read write',
    'username'   => $api,
    'password'   => $api,
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $authurl);
curl_setopt($ch, CURLOPT_POST, 1 );
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);

$auth = curl_exec( $ch );

if ( curl_errno( $ch ) ){
    echo 'Error: ' . curl_error( $ch );
}
curl_close($ch);

$secret = json_decode($auth);
$access_key = $secret->access_token;
echo $secret;
</code>```

答:
The first call seems OK for the password grant type. The scope parameter should be optional. So...

Add this to your code to know the response from the server and therefore know the missing parameter or setting.

```<code>curl_setopt($ch, CURLOPT_VERBOSE, true);
</code>```

Check the status code and a possible body with an error message.

ContentLicense: CC BY-SA 4.0

Title: PHP - How to get OAuth 2.0 Token

Body:
I want to connect to OAuth 2.0 authorization type (with password grant_type) to get token with POST method, it's ok to test from Postman but i couldn't connect through PHP...

here's my information:

request url: 'http://example.com/core/connect/token'

ClientName: 'something1'

ClientId: 'something2'

Secret: 'something3'

UserName: 'something4'

Password: 'something5'

Scope: 'something6'

could you please just give me an example to get token and use?

i've already tested:

$base_url = 'https://example.com/oauth/token';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $base_url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
        'client_id'     => YOUR-CLIENT-ID,
        'client_secret' => YOUR-CLIENT-SECRET,
        'username'      => YOUR-USERNAME-OR-EMAIL,
        'password'      => YOUR-PASSWORD,
        'grant_type'    => 'password'
));

$data = curl_exec($ch);

$auth_string = json_decode($data, true);

and this

$api = "KEY GOES HERE";
$authurl = "http://example.com/core/connect/token";

$client_id = "ID GOES HERE";
$client_secret = "SECRET GOES HERE";

// Creating base 64 encoded authkey
$Auth_Key = $client_id.":".$client_secret;
$encoded_Auth_Key=base64_encode($Auth_Key);

$headers = array();
$headers['Authorization'] = "Basic ".$encoded_Auth_Key;
$headers['Content-Type'] = "application/x-www-form-urlencoded";

$data = array(
    'grant_type' => 'password',
    'scope'      => 'read write',
    'username'   => $api,
    'password'   => $api,
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $authurl);
curl_setopt($ch, CURLOPT_POST, 1 );
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);

$auth = curl_exec( $ch );

if ( curl_errno( $ch ) ){
    echo 'Error: ' . curl_error( $ch );
}
curl_close($ch);

$secret = json_decode($auth);
$access_key = $secret->access_token;
echo $secret;

Body:
The first call seems OK for the password grant type. The scope parameter should be optional. So...

Add this to your code to know the response from the server and therefore know the missing parameter or setting.

curl_setopt($ch, CURLOPT_VERBOSE, true);

Check the status code and a possible body with an error message.


问:
Time measuring overhead in Java
When measuring elapsed time on a low level, I have the choice of using any of these:

```<code>System.currentTimeMillis();
System.nanoTime();
</code>```

Both methods are implemented native. Before digging into any C code, does anyone know if there is any substantial overhead calling one or the other? I mean, if I don't really care about the extra precision, which one would be expected to be less CPU time consuming?

N.B: I'm using the standard Java 1.6 JDK, but the question may be valid for any JRE...

答:
You should only ever use System.nanoTime() for measuring how long it takes something to run. It's not just a matter of the nanosecond precision, System.currentTimeMillis() is "wall clock time" while System.nanoTime() is intended for timing things and doesn't have the "real world time" quirks that the other does. From the Javadoc of System.nanoTime():

This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time.

ContentLicense: CC BY-SA 3.0

Title: Time measuring overhead in Java

Body:
When measuring elapsed time on a low level, I have the choice of using any of these:

System.currentTimeMillis();
System.nanoTime();

Both methods are implemented native. Before digging into any C code, does anyone know if there is any substantial overhead calling one or the other? I mean, if I don't really care about the extra precision, which one would be expected to be less CPU time consuming?

N.B: I'm using the standard Java 1.6 JDK, but the question may be valid for any JRE...


问:
What is required for a class so that a property grid shows its properties?

Language: C# .Net Framework 4.6.1

Operating System: Window 7 Home 64 bit

Can someone tell me what is required of a class for a property grid to display it's properties?

I tried just inheriting and implementing ICustomTypeDescriptor but nothing is showing up.

I would like the properties grid to also try to parse the values instead of just accepting a string, and I would like to be able to specify a category.

here is my code..

```<code>using System;
using System.Collections;
using System.Dynamic;
using System.Collections.Generic;
using System.Web.Script.Serialization;
using System.Collections.Specialized;
using System.ComponentModel;

namespace PureCore.Library.Data
{

    public class Property : DynamicObject, ICustomTypeDescriptor
    {
        private Dictionary<string, object> Properties = new Dictionary<string, object>();

        public override bool TryGetMember(GetMemberBinder binder, out object value)
        {
            if (Properties.ContainsKey(binder.Name))
            {
                value = Properties[binder.Name];
                return true;
            }
            return base.TryGetMember(binder, out value);
        }
        public override bool TrySetMember(SetMemberBinder binder,     object value)
        {
            if (Properties.ContainsKey(binder.Name))
            {
                Properties[binder.Name] = value;
                return true;
            }

            Properties.Add(binder.Name, value);
            return true;
        }

        public AttributeCollection GetAttributes()
        {
            return TypeDescriptor.GetAttributes(this, true);
        }
        public string GetClassName()
        {
            return TypeDescriptor.GetClassName(this, true);
        }
        public string GetComponentName()
        {
            return TypeDescriptor.GetComponentName(this, true);
        }
        public TypeConverter GetConverter()
        {
            return TypeDescriptor.GetConverter(this, true);
        }
        public EventDescriptor GetDefaultEvent()
        {
            return TypeDescriptor.GetDefaultEvent(this, true);
        }
        public PropertyDescriptor GetDefaultProperty()
        {
            return TypeDescriptor.GetDefaultProperty(this, true);
        }
        public object GetEditor(Type editorBaseType)
        {
            return TypeDescriptor.GetEditor(this, editorBaseType, true);
        }
        public EventDescriptorCollection GetEvents()
        {
            return TypeDescriptor.GetEvents(this, true);
        }
        public EventDescriptorCollection GetEvents(Attribute[] attributes)
        {
            return TypeDescriptor.GetEvents(this, attributes, true);
        }
        public PropertyDescriptorCollection GetProperties()
        {
            return TypeDescriptor.GetProperties(this, true);
        }
        public PropertyDescriptorCollection GetProperties(Attribute[] attributes)
        {
            return TypeDescriptor.GetProperties(this, attributes, true);
        }
        public object GetPropertyOwner(PropertyDescriptor pd)
        {
            return this;
        }
    }
}
</code>```

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

namespace Editor
{
    public partial class EnemyEditor : Form
    {
        dynamic property = new Property();
        public EnemyEditor()
        {
            InitializeComponent();
            property.HI = "Hello";
            propertyGrid1.SelectedObject = property;
        }

    }
}
</code>```

答:
You have to add a bit more code, specifically you must give the grid a list of properties explicitly, deriving from PropertyDescriptor, something like this:</p>

```<code>public class CustomType : DynamicObject, ICustomTypeDescriptor
{
    private readonly Dictionary<string, object> _properties = new Dictionary<string, object>();

    public AttributeCollection GetAttributes() => new AttributeCollection();
    public string GetClassName() => null;
    public string GetComponentName() => null;
    public TypeConverter GetConverter() => null;
    public EventDescriptor GetDefaultEvent() => null;
    public PropertyDescriptor GetDefaultProperty() => null;
    public object GetEditor(Type editorBaseType) => null;
    public EventDescriptorCollection GetEvents() => GetEvents(null);
    public EventDescriptorCollection GetEvents(Attribute[] attributes) => new EventDescriptorCollection(null);
    public PropertyDescriptorCollection GetProperties() => GetProperties(null);
    public object GetPropertyOwner(PropertyDescriptor pd) => this;
    public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => new PropertyDescriptorCollection(_properties.Select(p => new CustomProperty(p.Key, p.Value, "Mycats")).ToArray());

    public override bool TryGetMember(GetMemberBinder binder, out object value) => _properties.TryGetValue(binder.Name, out value);
    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
        _properties[binder.Name] = value;
        return true;
    }
}

public class CustomProperty : PropertyDescriptor
{
    public CustomProperty(string name, object value, string category)
        : base(name, new Attribute[] { new CategoryAttribute(category) })
    {
        Value = value;
    }

    public object Value { get; set; }
    public override Type ComponentType => typeof(CustomType);
    public override bool IsReadOnly => false;
    public override Type PropertyType => Value != null ? Value.GetType() : typeof(object);
    public override bool CanResetValue(object component) => false;
    public override object GetValue(object component) => Value;
    public override void ResetValue(object component) => throw new NotSupportedException();
    public override void SetValue(object component, object value) => Value = value;
    public override bool ShouldSerializeValue(object component) => false;
}
</code>```

Body:
Language: C# .Net Framework 4.6.1

Operating System: Window 7 Home 64 bit

Can someone tell me what is required of a class for a property grid to display it's properties?

I tried just inheriting and implementing ICustomTypeDescriptor but nothing is showing up.

I would like the properties grid to also try to parse the values instead of just accepting a string, and I would like to be able to specify a category.

here is my code..

using System;
using System.Collections;
using System.Dynamic;
using System.Collections.Generic;
using System.Web.Script.Serialization;
using System.Collections.Specialized;
using System.ComponentModel;

namespace PureCore.Library.Data
{

    public class Property : DynamicObject, ICustomTypeDescriptor
    {
        private Dictionary<string, object> Properties = new Dictionary<string, object>();

        public override bool TryGetMember(GetMemberBinder binder, out object value)
        {
            if (Properties.ContainsKey(binder.Name))
            {
                value = Properties[binder.Name];
                return true;
            }
            return base.TryGetMember(binder, out value);
        }
        public override bool TrySetMember(SetMemberBinder binder,     object value)
        {
            if (Properties.ContainsKey(binder.Name))
            {
                Properties[binder.Name] = value;
                return true;
            }

            Properties.Add(binder.Name, value);
            return true;
        }

        public AttributeCollection GetAttributes()
        {
            return TypeDescriptor.GetAttributes(this, true);
        }
        public string GetClassName()
        {
            return TypeDescriptor.GetClassName(this, true);
        }
        public string GetComponentName()
        {
            return TypeDescriptor.GetComponentName(this, true);
        }
        public TypeConverter GetConverter()
        {
            return TypeDescriptor.GetConverter(this, true);
        }
        public EventDescriptor GetDefaultEvent()
        {
            return TypeDescriptor.GetDefaultEvent(this, true);
        }
        public PropertyDescriptor GetDefaultProperty()
        {
            return TypeDescriptor.GetDefaultProperty(this, true);
        }
        public object GetEditor(Type editorBaseType)
        {
            return TypeDescriptor.GetEditor(this, editorBaseType, true);
        }
        public EventDescriptorCollection GetEvents()
        {
            return TypeDescriptor.GetEvents(this, true);
        }
        public EventDescriptorCollection GetEvents(Attribute[] attributes)
        {
            return TypeDescriptor.GetEvents(this, attributes, true);
        }
        public PropertyDescriptorCollection GetProperties()
        {
            return TypeDescriptor.GetProperties(this, true);
        }
        public PropertyDescriptorCollection GetProperties(Attribute[] attributes)
        {
            return TypeDescriptor.GetProperties(this, attributes, true);
        }
        public object GetPropertyOwner(PropertyDescriptor pd)
        {
            return this;
        }
    }
}

using PureCore.Library.Data;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Editor
{
    public partial class EnemyEditor : Form
    {
        dynamic property = new Property();
        public EnemyEditor()
        {
            InitializeComponent();
            property.HI = "Hello";
            propertyGrid1.SelectedObject = property;
        }

    }
}

Body:
You have to add a bit more code, specifically you must give the grid a list of properties explicitly, deriving from PropertyDescriptor, something like this:

public class CustomType : DynamicObject, ICustomTypeDescriptor
{
    private readonly Dictionary<string, object> _properties = new Dictionary<string, object>();

    public AttributeCollection GetAttributes() => new AttributeCollection();
    public string GetClassName() => null;
    public string GetComponentName() => null;
    public TypeConverter GetConverter() => null;
    public EventDescriptor GetDefaultEvent() => null;
    public PropertyDescriptor GetDefaultProperty() => null;
    public object GetEditor(Type editorBaseType) => null;
    public EventDescriptorCollection GetEvents() => GetEvents(null);
    public EventDescriptorCollection GetEvents(Attribute[] attributes) => new EventDescriptorCollection(null);
    public PropertyDescriptorCollection GetProperties() => GetProperties(null);
    public object GetPropertyOwner(PropertyDescriptor pd) => this;
    public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => new PropertyDescriptorCollection(_properties.Select(p => new CustomProperty(p.Key, p.Value, "Mycats")).ToArray());

    public override bool TryGetMember(GetMemberBinder binder, out object value) => _properties.TryGetValue(binder.Name, out value);
    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
        _properties[binder.Name] = value;
        return true;
    }
}

public class CustomProperty : PropertyDescriptor
{
    public CustomProperty(string name, object value, string category)
        : base(name, new Attribute[] { new CategoryAttribute(category) })
    {
        Value = value;
    }

    public object Value { get; set; }
    public override Type ComponentType => typeof(CustomType);
    public override bool IsReadOnly => false;
    public override Type PropertyType => Value != null ? Value.GetType() : typeof(object);
    public override bool CanResetValue(object component) => false;
    public override object GetValue(object component) => Value;
    public override void ResetValue(object component) => throw new NotSupportedException();
    public override void SetValue(object component, object value) => Value = value;
    public override bool ShouldSerializeValue(object component) => false;
}


问:
moment isBetween include from and to dates
I'm trying to filter an array and get data between two dates. What I've done does not give me the data on fromDate or toDate.

```<code>  $scope.visitorFilterByDate = function(fromDate, toDate, array, arrayCopy, searchArray){
    debugger
    $scope[array] = $scope[arrayCopy].filter(function(v){
      debugger
      return moment(v.visit_date, 'DD-MM-YYYY')
             .isBetween(moment($scope[fromDate], 'DD-MM-YYYY'),
                           moment($scope[toDate], 'DD-MM-YYYY'), null, []);
    })
    $scope[searchArray] = angular.copy($scope[array]);
  }
</code>```

答:
isBetween function takes only string formatted dates as arguments, so you should covert it to string using format function like this:

```<code> moment(moment(v.visit_date).format('DD-MM-YYYY'))
         .isBetween(moment($scope[fromDate]).format('DD-MM-YYYY'),
                       moment($scope[toDate]).format('DD-MM-YYYY'), null, [])
</code>```

Body:
I'm trying to filter an array and get data between two dates. What I've done does not give me the data on fromDate or toDate.

  $scope.visitorFilterByDate = function(fromDate, toDate, array, arrayCopy, searchArray){
    debugger
    $scope[array] = $scope[arrayCopy].filter(function(v){
      debugger
      return moment(v.visit_date, 'DD-MM-YYYY')
             .isBetween(moment($scope[fromDate], 'DD-MM-YYYY'),
                           moment($scope[toDate], 'DD-MM-YYYY'), null, []);
    })
    $scope[searchArray] = angular.copy($scope[array]);
  }

Body:
isBetween function takes only string formatted dates as arguments, so you should covert it to string using format function like this:

 moment(moment(v.visit_date).format('DD-MM-YYYY'))
         .isBetween(moment($scope[fromDate]).format('DD-MM-YYYY'),
                       moment($scope[toDate]).format('DD-MM-YYYY'), null, [])


问:
Displaying English on the right side of Chinese after click Chinese
After applying the given code, the 3 languages working without fail. But when we click the chinease language, English is displaying on the right side of Chinese. I just want to remove that.I have tried different ways but nothing is working.

ENG | 中文 | 한국어

```<code><div id="google_translate_element2"></div>
<script type="text/javascript">
  function googleTranslateElementInit2() {
    new google.translate.TranslateElement({
      pageLanguage: 'en',
      autoDisplay: false
    }, 'google_translate_element2');
  }
</script>
<script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit2"></script>

<script type="text/javascript">
  function GTranslateGetCurrentLang() {
    var keyValue = document['cookie'].match('(^|;) ?googtrans=([^;]*)(;|$)');
    return keyValue ? keyValue[2].split('/')[2] : null;
  }

  function GTranslateFireEvent(element, event) {
    try {
      if (document.createEventObject) {
        var evt = document.createEventObject();
        element.fireEvent('on' + event, evt)
      } else {
        var evt = document.createEvent('HTMLEvents');
        evt.initEvent(event, true, true);
        element.dispatchEvent(evt)
      }
    } catch (e) {}
  }

  function doGTranslate(lang_pair) {
    if (lang_pair.value) lang_pair = lang_pair.value;
    if (lang_pair == '') return;
    var lang = lang_pair.split('|')[1];
    if (GTranslateGetCurrentLang() == null && lang == lang_pair.split('|')[0]) return;
    var teCombo;
    var sel = document.getElementsByTagName('select');
    for (var i = 0; i < sel.length; i++)
      if (/goog-te-combo/.test(sel[i].className)) {
        teCombo = sel[i];
        break;
      }
    if (document.getElementById('google_translate_element2') == null || document.getElementById('google_translate_element2').innerHTML.length == 0 || teCombo.length == 0 || teCombo.innerHTML.length == 0) {
      setTimeout(function() {
        doGTranslate(lang_pair)
      }, 500)
    } else {
      teCombo.value = lang;
      GTranslateFireEvent(teCombo, 'change');
      GTranslateFireEvent(teCombo, 'change')
    }
  }
</script>
</code>```

答: It's just because of the text that you gave inside the anchor tag. You can replace the text with the image.</p>


问:
Ora 06512/04088 triggers errors when INSERT INTO statement
I'm at work for a trigger which provide a "domain" for column Molteplicità in a table called Partecipa using a function.

The trigger I've created is the following:

```<code>CREATE OR REPLACE TRIGGER dominioMolteplicità
BEFORE INSERT OR UPDATE ON partecipa
FOR EACH ROW
BEGIN
    IF moltepl_valido(:NEW.molteplicità) = 'f' THEN
        RAISE_APPLICAZION_ERROR(-20002, 'Invalid type');
    END IF;
END;
</code>```

which uses the following function:

```<code>CREATE OR REPLACE FUNCTION motepl_valido(mol VARCHAR2) RETURN CHAR IS
BEGIN
    IF regexp_like(LOWER(mol), ' [*]\..[*] ') THEN
        RETURN 't';
    ELSE
        RETURN 'f';
    END IF;
END;
</code>```

Table Partecipa has the following columns:

```<code>CodP INT,
molteplicità VARCHAR2,
codAss INT,
className VARCHAR2,
PRIMARY KEY (codP),
FOREIGN KEY (className) REFERENCES class(name),
FOREIGN KEY (codAss) REFERENCES associazione(cod)`
</code>```

and even though in my Associazione table there are rows (in particular codaAss: 42) and in my Class table there are rows (in particular className: 'Impiegato')

When I execute the following statement

```<code>insert into Partecipa(molteplicità, className, codAss)
values ('*..*', 'Impiegato', 42);
</code>```

I get these errors:

ORA-20002 INVALID TYPE

  ORA-06512: AT "dominioMolteplicità", line 3

  ORA-04088: ERROR DURING EXECUTION OF TRIGGER "dominioMolteplicità"

(Note that if I disable my trigger, the insert statement works properly. There's some problem with the trigger, but I can't find the mistake.)

答:
Beacue your pattern doesn't conform your data

I suppose regexp_like( lower(mol), '\*..\*') would be alright, and in this case the values such as '*=-*' or '*34*' for molteplicità would work.

Btw, even using '[\*]..[\*]'(where backslash used as an escape character) as the pattern might be possible for the above regular expression.

Demo :

```<code>with t( mol ) as
(
 select '*24*' from dual union all
 select 'B' from dual union all
 select '*=-*' from dual
)
select
  case when regexp_like(lower(mol), '\*..\*') then 't' else 'f' end suggested_pattern1,
  case when regexp_like(lower(mol), '[\*]..[\*]') then 't' else 'f' end suggested_pattern2,
  case when regexp_like(lower(mol), '[*]\..[*]') then 't' else 'f' end original_pattern,
  case when regexp_like(lower(mol), '*..*') then 't' else 'f' end anticipated_pattern
  from t;

SUGGESTED_PATTERN1  SUGGESTED_PATTERN2  ORIGINAL_PATTERN  ANTICIPATED_PATTERN
t                   t                   f                 t
f                   f                   f                 t
t                   t                   f                 t
</code>```

P.S. Note that anticipated_pattern would fail also ( for mol = 'B' in the above sample).

Body:
I'm at work for a trigger which provide a "domain" for column Molteplicità in a table called Partecipa using a function.

The trigger I've created is the following:

CREATE OR REPLACE TRIGGER dominioMolteplicità
BEFORE INSERT OR UPDATE ON partecipa
FOR EACH ROW
BEGIN
    IF moltepl_valido(:NEW.molteplicità) = 'f' THEN
        RAISE_APPLICAZION_ERROR(-20002, 'Invalid type');
    END IF;
END;

which uses the following function:

CREATE OR REPLACE FUNCTION motepl_valido(mol VARCHAR2) RETURN CHAR IS
BEGIN
    IF regexp_like(LOWER(mol), ' [*]\..[*] ') THEN
        RETURN 't';
    ELSE
        RETURN 'f';
    END IF;
END;

Table Partecipa has the following columns:

CodP INT,
molteplicità VARCHAR2,
codAss INT,
className VARCHAR2,
PRIMARY KEY (codP),
FOREIGN KEY (className) REFERENCES class(name),
FOREIGN KEY (codAss) REFERENCES associazione(cod)`

and even though in my Associazione table there are rows (in particular codaAss: 42) and in my Class table there are rows (in particular className: 'Impiegato')

When I execute the following statement

insert into Partecipa(molteplicità, className, codAss)
values ('*..*', 'Impiegato', 42);

I get these errors:

ORA-20002 INVALID TYPE

  ORA-06512: AT "dominioMolteplicità", line 3

  ORA-04088: ERROR DURING EXECUTION OF TRIGGER "dominioMolteplicità"

(Note that if I disable my trigger, the insert statement works properly. There's some problem with the trigger, but I can't find the mistake.)

Body:
Beacue your pattern doesn't conform your data

I suppose regexp_like( lower(mol), '\*..\*') would be alright, and in this case the values such as '*=-*' or '*34*' for molteplicità would work.

Btw, even using '[\*]..[\*]'(where backslash used as an escape character) as the pattern might be possible for the above regular expression.

Demo :

with t( mol ) as
(
 select '*24*' from dual union all
 select 'B' from dual union all
 select '*=-*' from dual
)
select
  case when regexp_like(lower(mol), '\*..\*') then 't' else 'f' end suggested_pattern1,
  case when regexp_like(lower(mol), '[\*]..[\*]') then 't' else 'f' end suggested_pattern2,
  case when regexp_like(lower(mol), '[*]\..[*]') then 't' else 'f' end original_pattern,
  case when regexp_like(lower(mol), '*..*') then 't' else 'f' end anticipated_pattern
  from t;

SUGGESTED_PATTERN1  SUGGESTED_PATTERN2  ORIGINAL_PATTERN  ANTICIPATED_PATTERN
t                   t                   f                 t
f                   f                   f                 t
t                   t                   f                 t

P.S. Note that anticipated_pattern would fail also ( for mol = 'B' in the above sample).


问:
intent-filter build two apps instead of one in Android Studio
I have a react native Project that's integrated with onesignal notification, in Android app when I built my app using Android Studio it installs two apps one called onesignal and the other one my main app and app runs perfect

I tried to remove the intent from my activity

```<code>       <activity android:name="bkholdnews.beonews.MainActivity" android:label="OneSignal Example" android:launchMode="singleTop" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
</code>```

and rebuilt the app, it installs one app but when I open it it says app keeps stooping!

my MainActivity code

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.hhz20.bkholdnews"
    android:versionCode="29"
    android:versionName="1.0">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> <!-- Approximate location - If you want to use promptLocation for letting OneSignal know the user location. -->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> <!--  Precise location If you want to use promptLocation for letting OneSignal know the user location. -->

    <uses-sdk
        android:minSdkVersion="16"
        android:targetSdkVersion="22" />

    <application
        android:name="bkholdnews.beonews.MainApplication"
        android:allowBackup="true"
        android:hardwareAccelerated="true"
        android:usesCleartextTraffic="true"
        android:largeHeap="true"
        android:supportsRtl="true"
        android:label="@string/app_name"
        android:icon="@drawable/icon"
        android:theme="@style/SplashTheme">

        <activity
            android:launchMode="singleTop"
            android:name="bkholdnews.beonews.SplashActivity"
            android:label="@string/app_name"
            android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
            android:windowSoftInputMode="adjustResize">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name="bkholdnews.beonews.MainActivity" android:label="OneSignal Example" android:launchMode="singleTop" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
        <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>
    </application>

</manifest>

</code>```

CRASH LOGCAT

```<code>    --------- beginning of crash
2019-06-01 17:31:18.598 30803-30803/com.hhz20.bkholdnews E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.hhz20.bkholdnews, PID: 30803
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.hhz20.bkholdnews/bkholdnews.beonews.SplashActivity}: android.content.res.Resources$NotFoundException: Drawable com.hhz20.bkholdnews:drawable/splash_screen with resource ID #0x7f0700b1
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
     Caused by: android.content.res.Resources$NotFoundException: Drawable com.hhz20.bkholdnews:drawable/splash_screen with resource ID #0x7f0700b1
     Caused by: android.content.res.Resources$NotFoundException: File res/drawable/splash_screen.xml from drawable resource ID #0x7f0700b1
        at android.content.res.ResourcesImpl.loadDrawableForCookie(ResourcesImpl.java:847)
        at android.content.res.ResourcesImpl.loadDrawable(ResourcesImpl.java:631)
        at android.content.res.Resources.getDrawableForDensity(Resources.java:888)
        at android.content.res.Resources.getDrawable(Resources.java:827)
        at android.content.Context.getDrawable(Context.java:626)
        at android.support.v4.content.ContextCompat.getDrawable(ContextCompat.java:463)
        at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:203)
        at android.support.v7.widget.TintTypedArray.getDrawableIfKnown(TintTypedArray.java:86)
        at android.support.v7.app.AppCompatDelegateImpl.<init>(AppCompatDelegateImpl.java:260)
        at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:182)
        at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:520)
        at android.support.v7.app.AppCompatActivity.onCreate(AppCompatActivity.java:71)
        at bkholdnews.beonews.SplashActivity.onCreate(SplashActivity.java:9)
        at android.app.Activity.performCreate(Activity.java:7136)
        at android.app.Activity.performCreate(Activity.java:7127)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
     Caused by: org.xmlpull.v1.XmlPullParserException: Binary XML file line #4: <bitmap> requires a valid 'src' attribute
        at android.graphics.drawable.BitmapDrawable.updateStateFromTypedArray(BitmapDrawable.java:849)
        at android.graphics.drawable.BitmapDrawable.inflate(BitmapDrawable.java:770)
        at android.graphics.drawable.DrawableInflater.inflateFromXmlForDensity(DrawableInflater.java:142)
2019-06-01 17:31:18.599 30803-30803/com.hhz20.bkholdnews E/AndroidRuntime:     at android.graphics.drawable.Drawable.createFromXmlInnerForDensity(Drawable.java:1332)
        at android.graphics.drawable.Drawable.createFromXmlInner(Drawable.java:1321)
        at android.graphics.drawable.LayerDrawable.inflateLayers(LayerDrawable.java:279)
        at android.graphics.drawable.LayerDrawable.inflate(LayerDrawable.java:194)
        at android.graphics.drawable.DrawableInflater.inflateFromXmlForDensity(DrawableInflater.java:142)
        at android.graphics.drawable.Drawable.createFromXmlInnerForDensity(Drawable.java:1332)
        at android.graphics.drawable.Drawable.createFromXmlForDensity(Drawable.java:1291)
        at android.content.res.ResourcesImpl.loadDrawableForCookie(ResourcesImpl.java:833)
            ... 27 more
2019-06-01 17:31:18.612 30803-30803/com.hhz20.bkholdnews I/Process: Sending signal. PID: 30803 SIG: 9
</code>```

答: you might have to remove intent filter from main  activity in the manifest file and  start activity transaction through splash screen to main activity and also remove launchmode from mainactivity</p>

Body:
I have a react native Project that's integrated with onesignal notification, in Android app when I built my app using Android Studio it installs two apps one called onesignal and the other one my main app and app runs perfect

I tried to remove the intent from my activity

       <activity android:name="bkholdnews.beonews.MainActivity" android:label="OneSignal Example" android:launchMode="singleTop" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

and rebuilt the app, it installs one app but when I open it it says app keeps stooping!

my MainActivity code

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.hhz20.bkholdnews"
    android:versionCode="29"
    android:versionName="1.0">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

    <uses-sdk
        android:minSdkVersion="16"
        android:targetSdkVersion="22" />

    <application
        android:name="bkholdnews.beonews.MainApplication"
        android:allowBackup="true"
        android:hardwareAccelerated="true"
        android:usesCleartextTraffic="true"
        android:largeHeap="true"
        android:supportsRtl="true"
        android:label="@string/app_name"
        android:icon="@drawable/icon"
        android:theme="@style/SplashTheme">

        <activity
            android:launchMode="singleTop"
            android:name="bkholdnews.beonews.SplashActivity"
            android:label="@string/app_name"
            android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
            android:windowSoftInputMode="adjustResize">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name="bkholdnews.beonews.MainActivity" android:label="OneSignal Example" android:launchMode="singleTop" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
        <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>
    </application>

</manifest>

CRASH LOGCAT

    --------- beginning of crash
2019-06-01 17:31:18.598 30803-30803/com.hhz20.bkholdnews E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.hhz20.bkholdnews, PID: 30803
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.hhz20.bkholdnews/bkholdnews.beonews.SplashActivity}: android.content.res.Resources$NotFoundException: Drawable com.hhz20.bkholdnews:drawable/splash_screen with resource ID #0x7f0700b1
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
     Caused by: android.content.res.Resources$NotFoundException: Drawable com.hhz20.bkholdnews:drawable/splash_screen with resource ID #0x7f0700b1
     Caused by: android.content.res.Resources$NotFoundException: File res/drawable/splash_screen.xml from drawable resource ID #0x7f0700b1
        at android.content.res.ResourcesImpl.loadDrawableForCookie(ResourcesImpl.java:847)
        at android.content.res.ResourcesImpl.loadDrawable(ResourcesImpl.java:631)
        at android.content.res.Resources.getDrawableForDensity(Resources.java:888)
        at android.content.res.Resources.getDrawable(Resources.java:827)
        at android.content.Context.getDrawable(Context.java:626)
        at android.support.v4.content.ContextCompat.getDrawable(ContextCompat.java:463)
        at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:203)
        at android.support.v7.widget.TintTypedArray.getDrawableIfKnown(TintTypedArray.java:86)
        at android.support.v7.app.AppCompatDelegateImpl.<init>(AppCompatDelegateImpl.java:260)
        at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:182)
        at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:520)
        at android.support.v7.app.AppCompatActivity.onCreate(AppCompatActivity.java:71)
        at bkholdnews.beonews.SplashActivity.onCreate(SplashActivity.java:9)
        at android.app.Activity.performCreate(Activity.java:7136)
        at android.app.Activity.performCreate(Activity.java:7127)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
     Caused by: org.xmlpull.v1.XmlPullParserException: Binary XML file line #4: <bitmap> requires a valid 'src' attribute
        at android.graphics.drawable.BitmapDrawable.updateStateFromTypedArray(BitmapDrawable.java:849)
        at android.graphics.drawable.BitmapDrawable.inflate(BitmapDrawable.java:770)
        at android.graphics.drawable.DrawableInflater.inflateFromXmlForDensity(DrawableInflater.java:142)
2019-06-01 17:31:18.599 30803-30803/com.hhz20.bkholdnews E/AndroidRuntime:     at android.graphics.drawable.Drawable.createFromXmlInnerForDensity(Drawable.java:1332)
        at android.graphics.drawable.Drawable.createFromXmlInner(Drawable.java:1321)
        at android.graphics.drawable.LayerDrawable.inflateLayers(LayerDrawable.java:279)
        at android.graphics.drawable.LayerDrawable.inflate(LayerDrawable.java:194)
        at android.graphics.drawable.DrawableInflater.inflateFromXmlForDensity(DrawableInflater.java:142)
        at android.graphics.drawable.Drawable.createFromXmlInnerForDensity(Drawable.java:1332)
        at android.graphics.drawable.Drawable.createFromXmlForDensity(Drawable.java:1291)
        at android.content.res.ResourcesImpl.loadDrawableForCookie(ResourcesImpl.java:833)
            ... 27 more
2019-06-01 17:31:18.612 30803-30803/com.hhz20.bkholdnews I/Process: Sending signal. PID: 30803 SIG: 9


问:
PHPMailer 6 Contact Form with Gmail SMTP
I'm trying to make it so that emails can be sent to my Gmail address rather than my domain name email using a PHPMailer form that is in a Bootstrap website. That is my main goal, and the other is to figure out how to have the form include the person's name, email and a subject populate the email rather than the set subject and "no-reply" email.  Any help I could get on this would be great; I thought I would see if anyone wanted to solve this for the community here before I hire a freelancer. Thanks!!

I've tried several tutorials to solve this as well as trying to combine the existing code I'm posting below with the SMTP Gmail version on the PHPMailer Github page ( https://github.com/PHPMailer/PHPMailer/blob/master/examples/gmail.phps )but I was not successful, I would instead post the working code here to my domain name email than my failed attempts at sending to Gmail.

```<code>    <form id="contact-form" method="post" action="contact.php">

        <div class="messages"></div>
        <div class="controls">

            <div class="form-group">
                <input id="form_name" type="text" name="name" class="form-control" placeholder="Enter your name." required="required">
            </div>

            <div class="form-group">
                <input id="form_email" type="email" name="email" class="form-control" placeholder="Enter your email." required="required">
            </div>

            <div class="form-group">
                <textarea id="form_message" name="message" class="form-control" placeholder="Add your message." rows="4" required="required"></textarea>
            </div>

            <input type="submit" class="btn btn-outline-light btn-sm" value="Send message">

        </div>

    </form>

<?php

use PHPMailer\PHPMailer\PHPMailer;

require './PHPMailer-master/vendor/autoload.php';

$fromEmail = 'noreply@email.com';
$fromName = 'No Reply Email';

$sendToEmail = 'name@mydomain.com';
$sendToName = 'New Website Email Message';

$subject = 'New message from contact form';

$fields = array('name' => 'Name:', 'email' => 'Email:', 'message' => 'Message:');

$okMessage = 'Successfully submitted - we will get back to you soon!';

$errorMessage = 'There was an error while submitting the form. Please try again later';

error_reporting(E_ALL & ~E_NOTICE);

try
{

    if(count($_POST) == 0) throw new \Exception('Form is empty');
    $emailTextHtml .= "<h3>New message from website:</h3><hr>";
    $emailTextHtml .= "<table>";

    foreach ($_POST as $key => $value) {

        if (isset($fields[$key])) {
            $emailTextHtml .= "<tr><th>$fields[$key]</th><td>$value</td></tr>";
        }
    }
    $emailTextHtml .= "</table><hr>";
    $emailTextHtml .= "<p>Have a great day!</p>";

    $mail = new PHPMailer;

    $mail->setFrom($fromEmail, $fromName);
    $mail->addAddress($sendToEmail, $sendToName);
    $mail->addReplyTo($_POST['email'], $_POST['name']);

    $mail->Subject = $subject;

    $mail->Body = $emailTextHtml;
    $mail->isHTML(true);

    if(!$mail->send()) {
        throw new \Exception('Email send failed. ' . $mail->ErrorInfo);
    }

    $responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
    $responseArray = array('type' => 'danger', 'message' => $e->getMessage());
}

if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    $encoded = json_encode($responseArray);

    header('Content-Type: application/json');

    echo $encoded;
}
else {
    echo $responseArray['message'];
}
?>
</code>```

答:
It is working on my projects. You can also remove the part of the code which you don't need like attachments. One more thing if you want to hide the debugging code errors and notifications remove or comment this line $mail->SMTPDebug = 2.
Check this similar StackOverflow article for more help

If you still need more help to let me know.
Hope this may help you.

<?php
// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'path/to/PHPMailer/src/Exception.php';
require 'path/to/PHPMailer/src/PHPMailer.php';
require 'path/to/PHPMailer/src/SMTP.php';

$mail = new PHPMailer(true);                              // Passing `true` enables exceptions
try {
    //Server settings
    $mail->SMTPDebug = 2;                                 // Enable verbose debug output
    $mail->isSMTP();                                      // Set mailer to use SMTP
    $mail->Host = 'smtp1.example.com;smtp2.example.com';  // Specify main and backup SMTP servers
    $mail->SMTPAuth = true;                               // Enable SMTP authentication
    $mail->Username = 'user@example.com';                 // SMTP username
    $mail->Password = 'secret';                           // SMTP password
    $mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 587;                                    // TCP port to connect to

    //Recipients
    $mail->setFrom('from@example.com', 'Mailer');
    $mail->addAddress('joe@example.net', 'Joe User');     // Add a recipient
    $mail->addAddress('ellen@example.com');               // Name is optional
    $mail->addReplyTo('info@example.com', 'Information');

    //Attachments
    $mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
    $mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name

    //Content
    $mail->isHTML(true);                                  // Set email format to HTML
    $mail->Subject = 'Here is the subject';
    $mail->Body    = 'This is the HTML message body in bold!';
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

    $mail->send();
    echo 'Message has been sent';
} catch (Exception $e) {
    echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
}`enter code here`
s

```

Body:
I'm trying to make it so that emails can be sent to my Gmail address rather than my domain name email using a PHPMailer form that is in a Bootstrap website. That is my main goal, and the other is to figure out how to have the form include the person's name, email and a subject populate the email rather than the set subject and "no-reply" email.  Any help I could get on this would be great; I thought I would see if anyone wanted to solve this for the community here before I hire a freelancer. Thanks!!

I've tried several tutorials to solve this as well as trying to combine the existing code I'm posting below with the SMTP Gmail version on the PHPMailer Github page ( https://github.com/PHPMailer/PHPMailer/blob/master/examples/gmail.phps )but I was not successful, I would instead post the working code here to my domain name email than my failed attempts at sending to Gmail.

    <form id="contact-form" method="post" action="contact.php">

                <input id="form_name" type="text" name="name" class="form-control" placeholder="Enter your name." required="required">

                <input id="form_email" type="email" name="email" class="form-control" placeholder="Enter your email." required="required">

                <textarea id="form_message" name="message" class="form-control" placeholder="Add your message." rows="4" required="required"></textarea>

            <input type="submit" class="btn btn-outline-light btn-sm" value="Send message">

    </form>

<?php

use PHPMailer\PHPMailer\PHPMailer;

require './PHPMailer-master/vendor/autoload.php';

$fromEmail = 'noreply@email.com';
$fromName = 'No Reply Email';

$sendToEmail = 'name@mydomain.com';
$sendToName = 'New Website Email Message';

$subject = 'New message from contact form';

$fields = array('name' => 'Name:', 'email' => 'Email:', 'message' => 'Message:');

$okMessage = 'Successfully submitted - we will get back to you soon!';

$errorMessage = 'There was an error while submitting the form. Please try again later';

error_reporting(E_ALL & ~E_NOTICE);

try
{

    if(count($_POST) == 0) throw new \Exception('Form is empty');
    $emailTextHtml .= "
New message from website:

";
    $emailTextHtml .= "
";

    foreach ($_POST as $key => $value) {

        if (isset($fields[$key])) {
            $emailTextHtml .= "
$fields[$key]	$value
";
        }
    }
    $emailTextHtml .= "

";
    $emailTextHtml .= "
Have a great day!
";

    $mail = new PHPMailer;

    $mail->setFrom($fromEmail, $fromName);
    $mail->addAddress($sendToEmail, $sendToName);
    $mail->addReplyTo($_POST['email'], $_POST['name']);

    $mail->Subject = $subject;

    $mail->Body = $emailTextHtml;
    $mail->isHTML(true);

    if(!$mail->send()) {
        throw new \Exception('Email send failed. ' . $mail->ErrorInfo);
    }

    $responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
    $responseArray = array('type' => 'danger', 'message' => $e->getMessage());
}

if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    $encoded = json_encode($responseArray);

    header('Content-Type: application/json');

    echo $encoded;
}
else {
    echo $responseArray['message'];
}
?>

Body:
It is working on my projects. You can also remove the part of the code which you don't need like attachments. One more thing if you want to hide the debugging code errors and notifications remove or comment this line $mail->SMTPDebug = 2.
Check this similar StackOverflow article for more help

If you still need more help to let me know.
Hope this may help you.

<?php
// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'path/to/PHPMailer/src/Exception.php';
require 'path/to/PHPMailer/src/PHPMailer.php';
require 'path/to/PHPMailer/src/SMTP.php';

$mail = new PHPMailer(true);                              // Passing `true` enables exceptions
try {
    //Server settings
    $mail->SMTPDebug = 2;                                 // Enable verbose debug output
    $mail->isSMTP();                                      // Set mailer to use SMTP
    $mail->Host = 'smtp1.example.com;smtp2.example.com';  // Specify main and backup SMTP servers
    $mail->SMTPAuth = true;                               // Enable SMTP authentication
    $mail->Username = 'user@example.com';                 // SMTP username
    $mail->Password = 'secret';                           // SMTP password
    $mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 587;                                    // TCP port to connect to

    //Recipients
    $mail->setFrom('from@example.com', 'Mailer');
    $mail->addAddress('joe@example.net', 'Joe User');     // Add a recipient
    $mail->addAddress('ellen@example.com');               // Name is optional
    $mail->addReplyTo('info@example.com', 'Information');

    //Attachments
    $mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
    $mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name

    //Content
    $mail->isHTML(true);                                  // Set email format to HTML
    $mail->Subject = 'Here is the subject';
    $mail->Body    = 'This is the HTML message body <b>in bold!</b>';
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

    $mail->send();
    echo 'Message has been sent';
} catch (Exception $e) {
    echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
}`enter code here`
s


问:
Flowtype constantly requiring null checks
I'm wondering how to avoid these numerous null checks or at least understand what the point is because it seems counter-productive.

Flowtype is giving me an error for this if I omit the null check:

```<code>var myEl = new MyElement()
if (document.body != null) { // error on next line if omitted
    document.body.appendChild(myEl)
}
</code>```

I have to do that null check for the document body in every single callback too, because who knows, maybe the body is null here right?!
I think this is total overkill. Not only that, but what's the point of such a simple nullcheck? It will just silently skip over a vital part of the program and exhibit undefined behavior somewhere else and make debugging the app that much harder.
I'd really prefer just having a null exception at this point if an error ever happens here, because to be really sure this tiny 2-line code segment that I'd write in javascript would have to be like this in flowtype:

```<code>var myEl = new MyElement()
if (document.body != null) {
    document.body.appendChild(myEl)
} else {
    console.error("null error")
}
</code>```

So 4 additional code lines and some nesting just to trace something I'd get for free if I just let the app run into an error. And I need those 4 lines on every single querySelector. On every single document.body. On every single getElementByTagName. This alone probably increases my entire codebase by 10%.
What's the point of enforcing this so strictly?

In other languages I'd also be able to try-catch around these hotspots gradually as needed, flow doesn't let me do that either. It shows errors whether I add a try-catch or not.

答:
When I know for sure that my variable won't be null and Flow doesn't, I use an unwrap() function:

export default function unwrap<T>(value: T): $NonMaybeType<T> {
  if (value !== null && value !== undefined) return value
  throw new Error('Unwrapping not possible because the variable is null or undefined!')
}```

Body:
I'm wondering how to avoid these numerous null checks or at least understand what the point is because it seems counter-productive.

Flowtype is giving me an error for this if I omit the null check:

var myEl = new MyElement()
if (document.body != null) { // error on next line if omitted
    document.body.appendChild(myEl)
}

I have to do that null check for the document body in every single callback too, because who knows, maybe the body is null here right?!
I think this is total overkill. Not only that, but what's the point of such a simple nullcheck? It will just silently skip over a vital part of the program and exhibit undefined behavior somewhere else and make debugging the app that much harder.
I'd really prefer just having a null exception at this point if an error ever happens here, because to be really sure this tiny 2-line code segment that I'd write in javascript would have to be like this in flowtype:

var myEl = new MyElement()
if (document.body != null) {
    document.body.appendChild(myEl)
} else {
    console.error("null error")
}

So 4 additional code lines and some nesting just to trace something I'd get for free if I just let the app run into an error. And I need those 4 lines on every single querySelector. On every single document.body. On every single getElementByTagName. This alone probably increases my entire codebase by 10%.
What's the point of enforcing this so strictly?

In other languages I'd also be able to try-catch around these hotspots gradually as needed, flow doesn't let me do that either. It shows errors whether I add a try-catch or not.


问:
How to remove duplicate words from a string comparing to other string in SQL
I need to check string2 if there are words that I already have in string1 and remove those.

```<code>declare @Text1 nvarchar(500) = 'apple, orange, pear'
declare @Text2 nvarchar(500) = 'banana, apple'
</code>```

The output should be 'banana'

Edit: I just realized I made the question not properly.
So, this is right:

```<code>DECLARE @Tab TABLE (Ingredients nvarchar(500))

insert @Tab select 'apple, orange, pear'

insert @Tab select 'banana, apple'

insert @Tab select 'pear, mango'

declare @Ingredients nvarchar(4000) = ''

select @Ingredients = @Ingredients + value + ',' from @Tab cross apply STRING_SPLIT(Ingredients, ',')

SELECT @Ingredients
</code>```

current result:
apple,orange,pear,banana,apple,pear,mango,

expected result:
apple,orange,pear,banana,mango,

答:
You can try this:</p>

```<code>DECLARE @Text1 NVARCHAR(500)= 'apple, orange, pear';
DECLARE @Text2 NVARCHAR(500)= 'banana, apple';
SELECT *
INTO #temp
FROM
(
    SELECT *
    FROM fn_split(@Text1, ',')
) a;
SELECT *
INTO #temp1
FROM
(
    SELECT *
    FROM fn_split(@Text2, ',')
) b;
SELECT item
FROM #temp1 a
WHERE NOT EXISTS
(
    SELECT item
    FROM #temp b
    WHERE a.item = b.item
);
</code>```

Body:
I need to check string2 if there are words that I already have in string1 and remove those.

declare @Text1 nvarchar(500) = 'apple, orange, pear'
declare @Text2 nvarchar(500) = 'banana, apple'

The output should be 'banana'

Edit: I just realized I made the question not properly.
So, this is right:

DECLARE @Tab TABLE (Ingredients nvarchar(500))

insert @Tab select 'apple, orange, pear'

insert @Tab select 'banana, apple'

insert @Tab select 'pear, mango'

declare @Ingredients nvarchar(4000) = ''

select @Ingredients = @Ingredients + value + ',' from @Tab cross apply STRING_SPLIT(Ingredients, ',')

SELECT @Ingredients

current result:
apple,orange,pear,banana,apple,pear,mango,

expected result:
apple,orange,pear,banana,mango,

Body:
You can try this:

DECLARE @Text1 NVARCHAR(500)= 'apple, orange, pear';
DECLARE @Text2 NVARCHAR(500)= 'banana, apple';
SELECT *
INTO #temp
FROM
(
    SELECT *
    FROM fn_split(@Text1, ',')
) a;
SELECT *
INTO #temp1
FROM
(
    SELECT *
    FROM fn_split(@Text2, ',')
) b;
SELECT item
FROM #temp1 a
WHERE NOT EXISTS
(
    SELECT item
    FROM #temp b
    WHERE a.item = b.item
);


问:
Basic C# question if - else
I was wondering if someone could tell me if this sample is correct please.
Please ignore the if statement i wrote it for demonstration purposes only.

basically what I want to know is, if I need to throw an exception in my else, is it right to have it return false then thrown an exception, like follows:

```<code>public bool test(Int j)
{
    if(!TestOnJThatcanThrowOutOfMemoryException E)
    {
        return true;
    }
    else
    {
        return false;
        throw new OutOfMemoryException();
    }
}
</code>```

OR - should I throw exception then return false outside else statement like this:

```<code>public bool test(Int j)
{
    if(!TestOnJThatcanThrowOutOfMemoryException E)
    {
        return true;
    }
    else
    {
        throw new OutOfMemoryException();
    }
    return false;
}
</code>```

答:
Either of the following would make sense:

a) return the result of the test, don't throw:

```<code>    public bool test(Int j)
    {
        if(!TestOnJThatcanThrowOutOfMemoryException(j))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
</code>```

(Note that this example is overly verbose, and can be rewritten as:)

```<code>    public bool test(Int j)
    {
        return !TestOnJThatcanThrowOutOfMemoryException(j)
    }
</code>```

b) throw if the test fails, do nothing otherwise:

```<code>    public void test(Int j)
    {
        if(TestOnJThatcanThrowOutOfMemoryException(j))
        {
            throw new OutOfMemoryException();
        }
    }
</code>```

In other words, make up your mind what that method is supposed to do - execute the test and return the result as a boolean value, or execute the test and throw when it fails.

Title: Basic C# question if - else

Body:
I was wondering if someone could tell me if this sample is correct please.
Please ignore the if statement i wrote it for demonstration purposes only.

basically what I want to know is, if I need to throw an exception in my else, is it right to have it return false then thrown an exception, like follows:

public bool test(Int j)
{
    if(!TestOnJThatcanThrowOutOfMemoryException E)
    {
        return true;
    }
    else
    {
        return false;
        throw new OutOfMemoryException();
    }
}

OR - should I throw exception then return false outside else statement like this:

public bool test(Int j)
{
    if(!TestOnJThatcanThrowOutOfMemoryException E)
    {
        return true;
    }
    else
    {
        throw new OutOfMemoryException();
    }
    return false;
}

Body:
Either of the following would make sense:

a) return the result of the test, don't throw:

    public bool test(Int j)
    {
        if(!TestOnJThatcanThrowOutOfMemoryException(j))
        {
            return true;
        }
        else
        {
            return false;
        }
    }

(Note that this example is overly verbose, and can be rewritten as:)

    public bool test(Int j)
    {
        return !TestOnJThatcanThrowOutOfMemoryException(j)
    }

b) throw if the test fails, do nothing otherwise:

    public void test(Int j)
    {
        if(TestOnJThatcanThrowOutOfMemoryException(j))
        {
            throw new OutOfMemoryException();
        }
    }

In other words, make up your mind what that method is supposed to do - execute the test and return the result as a boolean value, or execute the test and throw when it fails.


答:
It's not related to the trigger.

Your function motepl_valido raises ORA-20002 INVALID TYPE if the supplied string (in this case '*..*') does not match the regex ' [*]\..[*] '. It doesn't match because it's missing the required spaces.

Demo showing the effect of a selection of regex patterns (I've added | around the patterns to show the leading and trailing spaces):

```<code>with demo (molteplicita) as
     ( select '*..*' from dual union all
       select ' *..* ' from dual union all
       select ' *x.* ' from dual )
   , patterns (pattern) as
     ( select '[*]\..[*]' from dual union all
       select ' [*]\..[*] ' from dual union all
       select ' *[*]\..[*] *' from dual union all
       select ' *\*\..\* *' from dual )
select '|'||pattern||'|' as pattern
     , '|'||molteplicita||'|' as molteplicita
     , case when regexp_like(molteplicita, pattern) then 'Yes' else 'No' end as matched
from   demo cross join patterns
order by pattern, molteplicita desc;

PATTERN          MOLTEPLICITA MATCHED
---------------- ------------ -------
| *[*]\..[*] *|  |*..*|       Yes
| *[*]\..[*] *|  | *x.* |     No
| *[*]\..[*] *|  | *..* |     Yes

| *\*\..\* *|    |*..*|       Yes
| *\*\..\* *|    | *x.* |     No
| *\*\..\* *|    | *..* |     Yes

| [*]\..[*] |    |*..*|       No
| [*]\..[*] |    | *x.* |     No
| [*]\..[*] |    | *..* |     Yes

|[*]\..[*]|      |*..*|       Yes
|[*]\..[*]|      | *x.* |     No
|[*]\..[*]|      | *..* |     Yes

12 rows selected.
</code>```

Title: Ora 06512/04088 triggers errors when INSERT INTO statement

Body:
It's not related to the trigger.

Your function motepl_valido raises ORA-20002 INVALID TYPE if the supplied string (in this case '*..*') does not match the regex ' [*]\..[*] '. It doesn't match because it's missing the required spaces.

Demo showing the effect of a selection of regex patterns (I've added | around the patterns to show the leading and trailing spaces):

with demo (molteplicita) as
     ( select '*..*' from dual union all
       select ' *..* ' from dual union all
       select ' *x.* ' from dual )
   , patterns (pattern) as
     ( select '[*]\..[*]' from dual union all
       select ' [*]\..[*] ' from dual union all
       select ' *[*]\..[*] *' from dual union all
       select ' *\*\..\* *' from dual )
select '|'||pattern||'|' as pattern
     , '|'||molteplicita||'|' as molteplicita
     , case when regexp_like(molteplicita, pattern) then 'Yes' else 'No' end as matched
from   demo cross join patterns
order by pattern, molteplicita desc;

PATTERN          MOLTEPLICITA MATCHED
---------------- ------------ -------
| *[*]\..[*] *|  |*..*|       Yes
| *[*]\..[*] *|  | *x.* |     No
| *[*]\..[*] *|  | *..* |     Yes

| *\*\..\* *|    |*..*|       Yes
| *\*\..\* *|    | *x.* |     No
| *\*\..\* *|    | *..* |     Yes

| [*]\..[*] |    |*..*|       No
| [*]\..[*] |    | *x.* |     No
| [*]\..[*] |    | *..* |     Yes

|[*]\..[*]|      |*..*|       Yes
|[*]\..[*]|      | *x.* |     No
|[*]\..[*]|      | *..* |     Yes

12 rows selected.


问:
Fgets-How to prevent user from exceeding Maxsize?
I use fgets to get a name from the user and i put it in a char array.
If the user gives let's say beyond maxsize in fgets, then my program has a problem. I thought that if the user exceeds maxsize, NULL is returned. But that's not the case. How can i control this error?

Of course i can set maxsize at 200 and even more. But i think that's not a very good solution.

i have used fgets inside an if statement and if it's ==NULL, i print an error, but as i already told that won't work if the user exceeds maxsize.

```<code> fgets(name, 20, stdin);
</code>```

答:
As far as fgets is concerned, that's not an error. When you do fgets(name, 20, stdin), it will simply read up to 19 characters from standard input (or less if one of the characters is '\n'). The remaining characters will remain in stdin and the next call to an input function will pick them up.

You can detect this case by checking for a successful call to fgets where the string does not contain '\n':

```<code>if (!fgets(name, 20, stdin)) {
    // fgets failed; handle error
}
if (!strchr(name, '\n')) {
    // no newline in 'name'; a partial line was read
}
</code>```

You then have the choice of allocating a bigger buffer, or throwing the rest of the line away, or complaining to the user.

Body:
I use fgets to get a name from the user and i put it in a char array.
If the user gives let's say beyond maxsize in fgets, then my program has a problem. I thought that if the user exceeds maxsize, NULL is returned. But that's not the case. How can i control this error?

Of course i can set maxsize at 200 and even more. But i think that's not a very good solution.

i have used fgets inside an if statement and if it's ==NULL, i print an error, but as i already told that won't work if the user exceeds maxsize.

 fgets(name, 20, stdin);

Body:
As far as fgets is concerned, that's not an error. When you do fgets(name, 20, stdin), it will simply read up to 19 characters from standard input (or less if one of the characters is '\n'). The remaining characters will remain in stdin and the next call to an input function will pick them up.

You can detect this case by checking for a successful call to fgets where the string does not contain '\n':

if (!fgets(name, 20, stdin)) {
    // fgets failed; handle error
}
if (!strchr(name, '\n')) {
    // no newline in 'name'; a partial line was read
}

You then have the choice of allocating a bigger buffer, or throwing the rest of the line away, or complaining to the user.


问:
Goland Mac "cmd + [" and "cmd + ]" equivalent in Goland Linux
Recently switch to linux for development. As title, I cannot find a Goland Mac "cmd + [" and "cmd + ]" equivalent in linux version. I tried to use ctrl instead, but seems not right. </p>

答: I assume you mean navigation to the prev/next caret position. In this case, you can use Ctrl+Alt+← and Ctrl+Alt+→ on Window/Linux. You can find more information about possible ways of navigation here.


问:
how to set permissions of all the folders and all the files in as few steps as possible CHMOD

I am trying to set permissions of all of my folders to 775

and all the files (documents) to 644
There are many MANY files and Folders. All of those files and folders are contained in a single Folder.

I was wondering if there was a way to do it quickly!!

Any help would be really appreciated!

答:
```<code>find somedir/ \( -type d -exec chmod 0775 {} + -true \) -o \( -exec chmod 0644 {} + \)
</code>```