问:
Can't find crontab definition
On a Debian 10 machine, grep CRON /var/log/syslog logs CRON[455]: (root) CMD (/script.sh)

But crontab -e -u root is empty.

Where can I find the definition of that crontab job for the root user?

答:
first, check if the cron job is defined for other users, then you can check the below file it may include some of the cron jobs </p>

```<code>[root~]$ cat /etc/crontab
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
HOME=/

# For details see man 4 crontabs

# Example of job definition:
# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# |  |  |  |  |
# *  *  *  *  * user-name command to be executed
</code>```

Title: Can't find crontab definition

Body:
first, check if the cron job is defined for other users, then you can check the below file it may include some of the cron jobs

[root~]$ cat /etc/crontab
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
HOME=/

# For details see man 4 crontabs

# Example of job definition:
# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# |  |  |  |  |
# *  *  *  *  * user-name command to be executed


来源: stackexchange

问:
Blazor wasm unable to resolve AuthorizationOptions while attempting to activate DefaultAuthorizationPolicyProvider
I'm working on a Blazor wasm application and ran into an exception when adding the AuthorizeRouteView component in the App.razor file.  I lost quite some time trying to solve as there are few resources about this, so I want to share the solution here:

Error message was:

System.InvalidOperationException: Unable to resolve service for type 'Microsoft.Extensions.Options.IOptions`1[Microsoft.AspNetCore.Authorization.AuthorizationOptions]' while attempting to activate 'Microsoft.AspNetCore.Authorization.DefaultAuthorizationPolicyProvider'.

Package versions:

```<code>    <PackageReference Include="Microsoft.AspNetCore.Blazor.Build" Version="3.2.0-preview1.20073.1" PrivateAssets="all" />
    <PackageReference Include="Microsoft.AspNetCore.Blazor.DevServer" Version="3.2.0-preview1.20073.1" PrivateAssets="all" />
    <PackageReference Include="Microsoft.AspNetCore.Blazor.HttpClient" Version="3.2.0-preview1.20073.1" />
    <PackageReference Include="Microsoft.AspNetCore.Components.Authorization" Version="3.1.1" PrivateAssets="all"/>
</code>```

Following descriptions I only had to add AddAuthorizationCore() in the Program.cs Services:

```<code>builder.Services.AddAuthorizationCore();
</code>```

This then produces the above exception...

答:
I have a project which begun with Blazor 3.1 preview 4, and there was no need for this "AddOptions", it was all fine.
Then I´ve migrated it to Blazor 3.2.0 preview 1, did all the stuff recommended (no more startup, use program.cs only etc etc) and suddenly everything broke.
Those 2 lines from LYper´s answer solved my problem. Thanks.
Does anyone know why ???</p>

ContentLicense: CC BY-SA 4.0

Body:
I'm working on a Blazor wasm application and ran into an exception when adding the AuthorizeRouteView component in the App.razor file.  I lost quite some time trying to solve as there are few resources about this, so I want to share the solution here:

Error message was:

System.InvalidOperationException: Unable to resolve service for type 'Microsoft.Extensions.Options.IOptions`1[Microsoft.AspNetCore.Authorization.AuthorizationOptions]' while attempting to activate 'Microsoft.AspNetCore.Authorization.DefaultAuthorizationPolicyProvider'.

Package versions:

    <PackageReference Include="Microsoft.AspNetCore.Blazor.Build" Version="3.2.0-preview1.20073.1" PrivateAssets="all" />
    <PackageReference Include="Microsoft.AspNetCore.Blazor.DevServer" Version="3.2.0-preview1.20073.1" PrivateAssets="all" />
    <PackageReference Include="Microsoft.AspNetCore.Blazor.HttpClient" Version="3.2.0-preview1.20073.1" />
    <PackageReference Include="Microsoft.AspNetCore.Components.Authorization" Version="3.1.1" PrivateAssets="all"/>

Following descriptions I only had to add AddAuthorizationCore() in the Program.cs Services:

builder.Services.AddAuthorizationCore();

This then produces the above exception...


问:
LoginActivity has leaked window DecorView@bb62df1[LoginActivity] that was originally added here
I keep getting the error that my Login Activity has a leaked window of some sort,
This is my block of code where the error occurs. I have tried to dismiss both the dialog and the Alert Box respectively, but still, keep getting this error.

```<code>    try
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
        builder.setTitle(R.string.login_ok_title);
        builder.setMessage(R.string.login_ok_text).setCancelable(false).setPositiveButton(R.string.ok, (dialog, id) ->
        {
            Intent intent =new Intent(LoginActivity.this, TrackActivity.class);
            startActivity(intent);
            TrackManagerService trackManager =TrackManagerService.getInstance();
            if (trackManager != null) {
                trackManager.setLoginListener(null);
            }

            LoginActivity.this.finish();
            dialog.dismiss();
        });
        alert = builder.create();
        alert.show();

    }
    catch (Exception ex)
    {
        ex.printStackTrace();
        Intent intent = new Intent(LoginActivity.this, TrackActivity.class);
        alert.dismiss();
        startActivity(intent);
        TrackManagerService trackManager = TrackManagerService.getInstance();
        if (trackManager != null)
        {
            trackManager.setLoginListener(null);
        }
        finish();
    }
</code>```

This is the Error Log

```<code>E/WindowManager: android.view.WindowLeaked: Activity com.example.tornado_app.LoginActivity has leaked window DecorView@59e20b9[LoginActivity] that was originally added here
    at android.view.ViewRootImpl.<init>(ViewRootImpl.java:627)
    at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:389)
    at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:131)
    at android.app.Dialog.show(Dialog.java:531)
    at com.example.tornado_app.LoginActivity$2.lambda$onLoginResult$4$LoginActivity$2(LoginActivity.java:160)
    at com.example.tornado_app.-$$Lambda$LoginActivity$2$YvCiBtxWavxZ1iGtdLspSkuZOdU.run(Unknown Source:6)
    at android.os.Handler.handleCallback(Handler.java:907)
    at android.os.Handler.dispatchMessage(Handler.java:105)
    at android.os.Looper.loop(Looper.java:216)
    at android.app.ActivityThread.main(ActivityThread.java:7625)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)
</code>```

答:
pls try to check if activity is finished or not before showing dialog.</p>

```<code> if (!isFinishing()){
       alert.show();
    }
</code>```

Body:
I keep getting the error that my Login Activity has a leaked window of some sort,
This is my block of code where the error occurs. I have tried to dismiss both the dialog and the Alert Box respectively, but still, keep getting this error.

    try
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
        builder.setTitle(R.string.login_ok_title);
        builder.setMessage(R.string.login_ok_text).setCancelable(false).setPositiveButton(R.string.ok, (dialog, id) ->
        {
            Intent intent =new Intent(LoginActivity.this, TrackActivity.class);
            startActivity(intent);
            TrackManagerService trackManager =TrackManagerService.getInstance();
            if (trackManager != null) {
                trackManager.setLoginListener(null);
            }

            LoginActivity.this.finish();
            dialog.dismiss();
        });
        alert = builder.create();
        alert.show();

    }
    catch (Exception ex)
    {
        ex.printStackTrace();
        Intent intent = new Intent(LoginActivity.this, TrackActivity.class);
        alert.dismiss();
        startActivity(intent);
        TrackManagerService trackManager = TrackManagerService.getInstance();
        if (trackManager != null)
        {
            trackManager.setLoginListener(null);
        }
        finish();
    }

This is the Error Log

E/WindowManager: android.view.WindowLeaked: Activity com.example.tornado_app.LoginActivity has leaked window DecorView@59e20b9[LoginActivity] that was originally added here
    at android.view.ViewRootImpl.<init>(ViewRootImpl.java:627)
    at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:389)
    at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:131)
    at android.app.Dialog.show(Dialog.java:531)
    at com.example.tornado_app.LoginActivity$2.lambda$onLoginResult$4$LoginActivity$2(LoginActivity.java:160)
    at com.example.tornado_app.-$$Lambda$LoginActivity$2$YvCiBtxWavxZ1iGtdLspSkuZOdU.run(Unknown Source:6)
    at android.os.Handler.handleCallback(Handler.java:907)
    at android.os.Handler.dispatchMessage(Handler.java:105)
    at android.os.Looper.loop(Looper.java:216)
    at android.app.ActivityThread.main(ActivityThread.java:7625)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)

Body:
pls try to check if activity is finished or not before showing dialog.

 if (!isFinishing()){
       alert.show();
    }


问:
Seeking multi-dimensional array tutorial material
I want to know about multidimensional arrays on iPhone. Can anyone please explain it to me or give me some links? I'm new to iPhone programming. Thank you.</p>

答:
Check the below SO post

How to create nested array or multidimensional array

Multidimensional Arrays

multidimensional array

Objective C - Create a multi-dimensional array with the dimensions specified at initialisation

Multidimensional array in objective c

ContentLicense: CC BY-SA 3.0


问:
How do I insert values into a sql table using python3?
I'm trying to setup a MQTT client using the Paho library. With that there are no problems, but I'm trying to insert the received publishes in a sql database. I'm converting the received payload string into a dictionary and add a few entries. When executing the following code:

```<code>def insert_values(db_connection=None, topic=None, payload=None, time_received=None):
    query_1 = "SELECT topic_id FROM topics WHERE topic = %s"
    query_2 = """INSERT INTO measurements (start_time, end_time, value, max_value, min_value, time_received, topic_id)
                 VALUES (%(start_time)s, %(end_time)s, %(value)s, %(max_value)s, %(min_value)s, %(time_received)s,
                        %(topic_id)s)"""
    cursor = db_connection.cursor(prepared=True)
    topic_id = cursor.execute(query_1, topic)
    payload["time_received"] = time_received
    payload["topic_id"] = topic_id
    cursor.executemany(query_2, payload)
    db_connection.commit()
    db_disconnect(db_connection, cursor)
</code>```

I get the following error:

```<code>Caught exception in on_message: 1210: Incorrect number of arguments executing prepared statement
</code>```

The payload looks like this:

```<code>payload = {
        "Starttime:": 2020-02-18 10:11:22.2145563,
        "Endtime:": 2020-02-18 10:12:22.2145563,
        "Average Humidity:": 44.256241,
        "Number of Values:": 22,
        "Max Humidity:": 44.586214,
        "Min Humidity:": 44.012148521)
}
</code>```

Plus some additional info, like the time the payload was received. In the insert_values method I'm trying to get the topic_id from the table topics and write it into the payload.

Edit: The table in which the measurements are to be written looks like this:

```<code>CREATE TABLE IF NOT EXISTS measurements
(measurement_id INT AUTO_INCREMENT,
 start_time DATETIME,
 end_time DATETIME,
 value FLOAT,
 max_value FLOAT,
 min_value FLOAT,
 time_received DATETIME,
 topic_id INT,
 PRIMARY KEY (measurement_id),
 FOREIGN KEY (topic_id) REFERENCES topics(topic_id))
</code>```

答:
Your payload has 6 keys, and then you add another 2 that makes it 8
In your query you have only 7 arguments
I'm not sure but i think you forgot to add "Average Humidity"
EDIT : After seeing your table DESC</p>

```<code>    query_2 = """INSERT INTO measurements (start_time, end_time, value, max_value, min_value, time_received, topic_id)
             VALUES (%s,%s,%s,%s,%s,%s,%s)"""
cursor = db_connection.cursor(prepared=True)
topic_id = cursor.execute(query_1, topic)
payload["time_received"] = time_received
payload["topic_id"] = topic_id
payload.pop("Average Humidity:", None)
cursor.executemany(query_2, payload)
db_connection.commit()
db_disconnect(db_connection, cursor)
</code>```

Body:
I'm trying to setup a MQTT client using the Paho library. With that there are no problems, but I'm trying to insert the received publishes in a sql database. I'm converting the received payload string into a dictionary and add a few entries. When executing the following code:

def insert_values(db_connection=None, topic=None, payload=None, time_received=None):
    query_1 = "SELECT topic_id FROM topics WHERE topic = %s"
    query_2 = """INSERT INTO measurements (start_time, end_time, value, max_value, min_value, time_received, topic_id)
                 VALUES (%(start_time)s, %(end_time)s, %(value)s, %(max_value)s, %(min_value)s, %(time_received)s,
                        %(topic_id)s)"""
    cursor = db_connection.cursor(prepared=True)
    topic_id = cursor.execute(query_1, topic)
    payload["time_received"] = time_received
    payload["topic_id"] = topic_id
    cursor.executemany(query_2, payload)
    db_connection.commit()
    db_disconnect(db_connection, cursor)

I get the following error:

Caught exception in on_message: 1210: Incorrect number of arguments executing prepared statement

The payload looks like this:

payload = {
        "Starttime:": 2020-02-18 10:11:22.2145563,
        "Endtime:": 2020-02-18 10:12:22.2145563,
        "Average Humidity:": 44.256241,
        "Number of Values:": 22,
        "Max Humidity:": 44.586214,
        "Min Humidity:": 44.012148521)
}

Plus some additional info, like the time the payload was received. In the insert_values method I'm trying to get the topic_id from the table topics and write it into the payload.

Edit: The table in which the measurements are to be written looks like this:

CREATE TABLE IF NOT EXISTS measurements
(measurement_id INT AUTO_INCREMENT,
 start_time DATETIME,
 end_time DATETIME,
 value FLOAT,
 max_value FLOAT,
 min_value FLOAT,
 time_received DATETIME,
 topic_id INT,
 PRIMARY KEY (measurement_id),
 FOREIGN KEY (topic_id) REFERENCES topics(topic_id))

Body:
Your payload has 6 keys, and then you add another 2 that makes it 8
In your query you have only 7 arguments
I'm not sure but i think you forgot to add "Average Humidity"
EDIT : After seeing your table DESC

    query_2 = """INSERT INTO measurements (start_time, end_time, value, max_value, min_value, time_received, topic_id)
             VALUES (%s,%s,%s,%s,%s,%s,%s)"""
cursor = db_connection.cursor(prepared=True)
topic_id = cursor.execute(query_1, topic)
payload["time_received"] = time_received
payload["topic_id"] = topic_id
payload.pop("Average Humidity:", None)
cursor.executemany(query_2, payload)
db_connection.commit()
db_disconnect(db_connection, cursor)


问:
Issue with jwt-bearer on-behalf-of grant in Azure AD
So I have an Angular app that uses the adal-angular library to authenticate with an ASP.NET Core 2.0 Web API. The API then uses on-behalf-of flow to authenticate with another API using the users token like this MS article https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-protocols-oauth-on-behalf-of.

The issue I have is this is working fine in the DEV environment but I have now deployed a TST environment with separate App Registrations and I am receiving the following exception when I try and request the token using on-behalf-of

AADSTS240002: Input id_token cannot be used as 'urn:ietf:params:oauth:grant-type:jwt-bearer' grant.

The code I am using to request the token

```<code>public async Task<string> AcquireTokenAsync(string resource)
    {
        try
        {
            string accessToken = await _httpContextAccessor.HttpContext.GetTokenAsync(AuthenticationConstants.AccessToken);

            var credentials = new ClientCredential(_azureOptions.ClientId, _azureOptions.ClientSecret);
            var authContext = new AuthenticationContext($"{_azureOptions.Instance}{_azureOptions.TenantId}")
            {
                ExtendedLifeTimeEnabled = true
            };

            // On-behalf-of auth token request call
            var authResult = await authContext.AcquireTokenAsync(
                resource,
                credentials,
                new UserAssertion(accessToken));

            return authResult.AccessToken;
        }
        catch (AdalServiceException asex)
        {
            _logger.LogError(asex, $"Instance: {_azureOptions.Instance} Tenant: {_azureOptions.TenantId} ClientId: {_azureOptions.ClientId}");
            throw;
        }
        catch (System.Exception ex)
        {
            _logger.LogError(ex, ex.Message);
            throw;
        }
    }
</code>```

And I have used Fiddler  and it looks like all the correct parameters are being passed.

Any help would be very much appreciated. I have set knownClientApplications on the second API and I have granted permissions on the Angular backend API to the second API.

答:
For me, I got it to work by changing BOTH of the following to true:
oauth2AllowImplicitFlow
oauth2AllowIdTokenImplicitFlow

See here for more information.

Body:
So I have an Angular app that uses the adal-angular library to authenticate with an ASP.NET Core 2.0 Web API. The API then uses on-behalf-of flow to authenticate with another API using the users token like this MS article https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-protocols-oauth-on-behalf-of.

The issue I have is this is working fine in the DEV environment but I have now deployed a TST environment with separate App Registrations and I am receiving the following exception when I try and request the token using on-behalf-of

AADSTS240002: Input id_token cannot be used as 'urn:ietf:params:oauth:grant-type:jwt-bearer' grant.

The code I am using to request the token

public async Task<string> AcquireTokenAsync(string resource)
    {
        try
        {
            string accessToken = await _httpContextAccessor.HttpContext.GetTokenAsync(AuthenticationConstants.AccessToken);

            var credentials = new ClientCredential(_azureOptions.ClientId, _azureOptions.ClientSecret);
            var authContext = new AuthenticationContext($"{_azureOptions.Instance}{_azureOptions.TenantId}")
            {
                ExtendedLifeTimeEnabled = true
            };

            // On-behalf-of auth token request call
            var authResult = await authContext.AcquireTokenAsync(
                resource,
                credentials,
                new UserAssertion(accessToken));

            return authResult.AccessToken;
        }
        catch (AdalServiceException asex)
        {
            _logger.LogError(asex, $"Instance: {_azureOptions.Instance} Tenant: {_azureOptions.TenantId} ClientId: {_azureOptions.ClientId}");
            throw;
        }
        catch (System.Exception ex)
        {
            _logger.LogError(ex, ex.Message);
            throw;
        }
    }

And I have used Fiddler  and it looks like all the correct parameters are being passed.

Any help would be very much appreciated. I have set knownClientApplications on the second API and I have granted permissions on the Angular backend API to the second API.


问:
Error while splitting a column of lists into different columns
I have a dataframe named amplitude_df1 as shown below.

```<code>                                            amplitudes
0    [1.8224, 9.10515, 10.187, 4.67473, 1.60665, 1....
1    [4.40045, 15.4495, 27.3758, 17.6756, 3.21038, ...
2    [2.11535, 11.9202, 18.2254, 7.32574, 4.11506, ...
3    [3.51715, 5.90878, 14.3854, 11.5154, 8.16267, ...
4    [5.33236, 19.8225, 33.4585, 15.5712, 9.21001, ...
..                                                 ...
196  [1.18488, 2.8276, 9.20956, 17.0281, 9.59571, 3...
197  [0.878292, 2.50281, 2.9185, 9.55309, 9.55309, ...
198  [0.220521, 0.503399, 2.16432, 2.92407, 2.92407...
199  [0.572135, 2.4478, 4.80103, 4.65729, 3.54338, ...
200  [1.14716, 1.58989, 3.63487, 6.12651, 4.42284, ...

[201 rows x 1 columns]
</code>```

I was trying to split the amplitude column which contains lists into different columns as shown below:

```<code>amplitude_df=pd.DataFrame(amplitude_df1['amplitudes'].values.tolist(),columns=list(range(len(amplitude_df1["amplitudes"][0])))
</code>```

But the error pops up saying:

```<code>ValueError: Shape of passed values is (201, 1), indices imply (201, 49617)
</code>```

Any help appreciated.For any questions let me know in the comments

EDIT: This is my whole code as requested by an answerer

```<code>for filename in os.listdir(directory):
        if re.search("part-00001",filename):
            json_file_path = os.path.join(directory, filename)
            with open(json_file_path) as f:
                jsonData = json.load(f)
                #print(jsonData)
                if jsonData["channel"]== channel:
                    df = {"amplitudes":jsonData["amplitudes"],"time":jsonData["time"],
                          "channel":jsonData["channel"]}
                    df1 = pd.DataFrame(df,index=[0])
                    jsonNew = jsonNew.append(df1)

    jsonDF = jsonNew
    #sorting values with timestamp
    jsonSorted = jsonDF.sort_values("time")
    #resetting index after sorting
    newJson = jsonSorted.reset_index(drop=True)
    newJson_amp = newJson.drop(['time','channel'],axis=1)
    print(newJson_amp)
    amplitude_df1 = newJson_amp
    #mytry
    amplitude_df=pd.DataFrame(amplitude_df1['amplitudes'].values.tolist(),columns=list(range(len(amplitude_df1["amplitudes"][0])))
</code>```

This is what I want
Pandas split column of lists into multiple columns

答:
Try using .to_numpy() instead of .tolist(). (You will need to import numpy)
If that doesn't work, create a variable and reshape the amplitude_df1['amplitudes'].values.to_numpy() with the function .reshape()

Here is the doc: https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html

Regards

Body:
I have a dataframe named amplitude_df1 as shown below.

                                            amplitudes
0    [1.8224, 9.10515, 10.187, 4.67473, 1.60665, 1....
1    [4.40045, 15.4495, 27.3758, 17.6756, 3.21038, ...
2    [2.11535, 11.9202, 18.2254, 7.32574, 4.11506, ...
3    [3.51715, 5.90878, 14.3854, 11.5154, 8.16267, ...
4    [5.33236, 19.8225, 33.4585, 15.5712, 9.21001, ...
..                                                 ...
196  [1.18488, 2.8276, 9.20956, 17.0281, 9.59571, 3...
197  [0.878292, 2.50281, 2.9185, 9.55309, 9.55309, ...
198  [0.220521, 0.503399, 2.16432, 2.92407, 2.92407...
199  [0.572135, 2.4478, 4.80103, 4.65729, 3.54338, ...
200  [1.14716, 1.58989, 3.63487, 6.12651, 4.42284, ...

[201 rows x 1 columns]

I was trying to split the amplitude column which contains lists into different columns as shown below:

amplitude_df=pd.DataFrame(amplitude_df1['amplitudes'].values.tolist(),columns=list(range(len(amplitude_df1["amplitudes"][0])))

But the error pops up saying:

ValueError: Shape of passed values is (201, 1), indices imply (201, 49617)

Any help appreciated.For any questions let me know in the comments

EDIT: This is my whole code as requested by an answerer

for filename in os.listdir(directory):
        if re.search("part-00001",filename):
            json_file_path = os.path.join(directory, filename)
            with open(json_file_path) as f:
                jsonData = json.load(f)
                #print(jsonData)
                if jsonData["channel"]== channel:
                    df = {"amplitudes":jsonData["amplitudes"],"time":jsonData["time"],
                          "channel":jsonData["channel"]}
                    df1 = pd.DataFrame(df,index=[0])
                    jsonNew = jsonNew.append(df1)

    jsonDF = jsonNew
    #sorting values with timestamp
    jsonSorted = jsonDF.sort_values("time")
    #resetting index after sorting
    newJson = jsonSorted.reset_index(drop=True)
    newJson_amp = newJson.drop(['time','channel'],axis=1)
    print(newJson_amp)
    amplitude_df1 = newJson_amp
    #mytry
    amplitude_df=pd.DataFrame(amplitude_df1['amplitudes'].values.tolist(),columns=list(range(len(amplitude_df1["amplitudes"][0])))

This is what I want
Pandas split column of lists into multiple columns


问:
'list' objet is not callable when defining python function
I am trying to create a function composite to:
1)count how many times each character appears in the string;
2)pass the result to a dictionary with pairs of character and occurrence time;
3)and find out which character has the most occurrences

For function best_key(dictionary) I keep getting the error message ('list' object is not callable). Does anyone know why?

```<code>def count_frequency(st):
    d = {}
    for c in st:
        if c not in d:
            d[c] = 0
        d[c] = d[c]+1
    return d

def best_key(dictionary):
    ks=dictionary.keys()
    best_key_so_far = list(ks)[0] **TypeError: 'list' object is not callable**
    for k in ks:
        if dictionary[k]>dictionary[best_key_so_far]
            best_key_so_far=k
    return best_key_so_far

def final_one(s):
    freq=count_frequency(s)
    return best_key(freq)

print(final_one("567tfgffffbbbbb"))
</code>```

答:
I have checked your code, and it turns out it contains one or more syntax error.
Here is the correct code:

```<code>def count_frequency(st):
    d = {}
    for c in st:
        if c not in d:
            d[c] = 0
        d[c] = d[c]+1
    return d

def best_key(dictionary):
    ks = dictionary.keys()
    best_key_so_far = list(ks)[0]
    for k in ks:
        if dictionary[k] > dictionary[best_key_so_far]:
            best_key_so_far = k
    return best_key_so_far

def final_one(s):
    freq = count_frequency(s)
    return best_key(freq)
</code>```

And when you call,

```<code>print(final_one("567tfgffffbbbbb"))
</code>```

The output will be,

```<code>f
</code>```

Hope it helps you!

Body:
I am trying to create a function composite to:
1)count how many times each character appears in the string;
2)pass the result to a dictionary with pairs of character and occurrence time;
3)and find out which character has the most occurrences

For function best_key(dictionary) I keep getting the error message ('list' object is not callable). Does anyone know why?

def count_frequency(st):
    d = {}
    for c in st:
        if c not in d:
            d[c] = 0
        d[c] = d[c]+1
    return d

def best_key(dictionary):
    ks=dictionary.keys()
    best_key_so_far = list(ks)[0] **TypeError: 'list' object is not callable**
    for k in ks:
        if dictionary[k]>dictionary[best_key_so_far]
            best_key_so_far=k
    return best_key_so_far

def final_one(s):
    freq=count_frequency(s)
    return best_key(freq)

print(final_one("567tfgffffbbbbb"))

Body:
I have checked your code, and it turns out it contains one or more syntax error.
Here is the correct code:

def count_frequency(st):
    d = {}
    for c in st:
        if c not in d:
            d[c] = 0
        d[c] = d[c]+1
    return d

def best_key(dictionary):
    ks = dictionary.keys()
    best_key_so_far = list(ks)[0]
    for k in ks:
        if dictionary[k] > dictionary[best_key_so_far]:
            best_key_so_far = k
    return best_key_so_far

def final_one(s):
    freq = count_frequency(s)
    return best_key(freq)

And when you call,

print(final_one("567tfgffffbbbbb"))

The output will be,

f

Hope it helps you!


问:
Return inserted row
How do I return the row I just inserted including DB-generated identifier?
My SQL is just a standard dynamic SQL insert

```<code>insert into dbo.TableName (Col1, Col2) values (@Col1, @Col2);
</code>```

I have tried select from inserted, but inserted object is not a known object

```<code>insert into dbo.TableName (Col1, Col2) values (@Col1, @Col2); select * from inserted;
</code>```

I have tried using output, but I cannot do that, when there is a trigger on the table

```<code>insert into dbo.TableName (Col1, Col2) output inserted.* values (@Col1, @Col2);
</code>```

Any ideas?

答:
You can use OUTPUT clause:</p>

```<code>--Sample table
CREATE TABLE IdentityInsert
(
    ID int IDENTITY,
    A int
)

INSERT IdentityInsert OUTPUT inserted.* VALUES (3)
</code>```

Title: Return inserted row

Body:
How do I return the row I just inserted including DB-generated identifier?
My SQL is just a standard dynamic SQL insert

insert into dbo.TableName (Col1, Col2) values (@Col1, @Col2);

I have tried select from inserted, but inserted object is not a known object

insert into dbo.TableName (Col1, Col2) values (@Col1, @Col2); select * from inserted;

I have tried using output, but I cannot do that, when there is a trigger on the table

insert into dbo.TableName (Col1, Col2) output inserted.* values (@Col1, @Col2);

Any ideas?

Body:
You can use OUTPUT clause:

--Sample table
CREATE TABLE IdentityInsert
(
    ID int IDENTITY,
    A int
)

INSERT IdentityInsert OUTPUT inserted.* VALUES (3)


问:
Fetch only one value from API with PHP
I have recently been trying to get stock data from financialmodelingprep.com and I successfully found a code;

```<code>set_time_limit(0);

$url_info = "https://financialmodelingprep.com/api/v3/stock/real-time-price/AAPL";

$channel = curl_init();

curl_setopt($channel, CURLOPT_AUTOREFERER, TRUE);
curl_setopt($channel, CURLOPT_HEADER, 0);
curl_setopt($channel, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($channel, CURLOPT_URL, $url_info);
curl_setopt($channel, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($channel, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
curl_setopt($channel, CURLOPT_TIMEOUT, 0);
curl_setopt($channel, CURLOPT_CONNECTTIMEOUT, 0);
curl_setopt($channel, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($channel, CURLOPT_SSL_VERIFYPEER, FALSE);

$output = curl_exec($channel);

if (curl_error($channel)) {
    return 'error:' . curl_error($channel);
} else {
    echo $output;
}
</code>```

This code outputs: { "symbol" : "AAPL", "price" : 324.83 } And I was wondering how I could fetch only the "price" number (324.83) and store it in a php variable.
Thanks in advance.

答:
The output you're getting is in json format. Convert it to an array using json_decode() and then you can pull any value you'd like from the array:

```<code>$array = json_decode($output, true);
var_dump($array['price']);
</code>```

Title: Fetch only one value from API with PHP

Body:
I have recently been trying to get stock data from financialmodelingprep.com and I successfully found a code;

set_time_limit(0);

$url_info = "https://financialmodelingprep.com/api/v3/stock/real-time-price/AAPL";

$channel = curl_init();

curl_setopt($channel, CURLOPT_AUTOREFERER, TRUE);
curl_setopt($channel, CURLOPT_HEADER, 0);
curl_setopt($channel, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($channel, CURLOPT_URL, $url_info);
curl_setopt($channel, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($channel, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
curl_setopt($channel, CURLOPT_TIMEOUT, 0);
curl_setopt($channel, CURLOPT_CONNECTTIMEOUT, 0);
curl_setopt($channel, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($channel, CURLOPT_SSL_VERIFYPEER, FALSE);

$output = curl_exec($channel);

if (curl_error($channel)) {
    return 'error:' . curl_error($channel);
} else {
    echo $output;
}

This code outputs: { "symbol" : "AAPL", "price" : 324.83 } And I was wondering how I could fetch only the "price" number (324.83) and store it in a php variable.
Thanks in advance.

Body:
The output you're getting is in json format. Convert it to an array using json_decode() and then you can pull any value you'd like from the array:

$array = json_decode($output, true);
var_dump($array['price']);


问:
Javascript searchfunction
I got a problem here. The search is working almost. But when I am deleting something it doesnt appear again. (tried something like else {names[i].parentElement.style.display = "block"}). This didnt work.
And maybe someone could tell me what to do if someone hits enter and everthing gets resetted. Thanks to every answer.

function searchFunction() {
  const search = document.getElementById("myinput").value;
  const names = document.getElementsByClassName("names");
  console.log(search)
  for (var i = 0; i < names.length; i++) {
    if (names[i].innerHTML.toUpperCase().includes(search.toUpperCase()) == false) {
      names[i].parentElement.style.display = "none"
    }
  }

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form class="search">
    <input class="bar" type="search" name="search" placeholder="Nach Mitarbeiter suchen" autocomplete="off" id="myinput" oninput="searchFunction()"> echo "
    <div class='gridRow'>
        <p class='rowElements names'>" . $user . "</p>

        <p class='rowElements beer'>" . $beer . "</p>

        <p class='invisibleBullshit'>" . $email . "</p>

        <input type='number' min='0' class='rowElements inputSize' placeholder='0' name='beerSub-"
                    . $user ."'>

        <button class='rowElements btn btn-primary btn-sm inputSize' onclick='payBeer(".' "'.$user.'" '.",".' "'.$email.'" '.")'>
            Bezahlen
        </button>
    </div>
</form></code>```

答:
The easiest thing to do is switch between block and none based on whether the search term is found in the specified element.

Start typing "bob" or "john" in the example below to see the effect.

function searchFunction() {
  const search = document.getElementById("myinput").value;
  const names = document.getElementsByClassName("names");
  //console.log(search)
  for (var i = 0; i < names.length; i++) {
     names[i].parentElement.style.display =
        (names[i].innerHTML.toUpperCase().includes(search.toUpperCase())
            ? "block"
            : "none");
  }

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form class="search">
     <input class="bar" type="search" name="search" placeholder="Nach Mitarbeiter suchen"autocomplete="off" id="myinput" oninput="searchFunction()">
     <div class='gridRow'>
         <p class='rowElements names'>Bob</p>
         <p class='rowElements beer'>Beer1</p>
         <p class='invisibleBullshit'>bob@bob.com</p>
         <input type='number' min='0' class='rowElements inputSize' placeholder='0' name='beerSub-bob'>
         <button class='rowElements btn btn-primary btn-sm inputSize' onclick='payBeer("bob","bob@bob.com")'>
             Bezahlen
          </button>
     </div>
     <div class='gridRow'>
         <p class='rowElements names'>John</p>
         <p class='rowElements beer'>Beer2</p>
         <p class='invisibleBullshit'>john@john.com</p>
         <input type='number' min='0' class='rowElements inputSize' placeholder='0' name='beerSub-john'>
         <button class='rowElements btn btn-primary btn-sm inputSize' onclick='payBeer("john","john@john.com")'>
             Bezahlen
          </button>
     </div>
</form></code>```

Title: Javascript searchfunction

Body:
I got a problem here. The search is working almost. But when I am deleting something it doesnt appear again. (tried something like else {names[i].parentElement.style.display = "block"}). This didnt work.
And maybe someone could tell me what to do if someone hits enter and everthing gets resetted. Thanks to every answer.

function searchFunction() {
  const search = document.getElementById("myinput").value;
  const names = document.getElementsByClassName("names");
  console.log(search)
  for (var i = 0; i < names.length; i++) {
    if (names[i].innerHTML.toUpperCase().includes(search.toUpperCase()) == false) {
      names[i].parentElement.style.display = "none"
    }
  }

}

<form class="search">
    <input class="bar" type="search" name="search" placeholder="Nach Mitarbeiter suchen" autocomplete="off" id="myinput" oninput="searchFunction()"> echo "

" . $user . "

" . $beer . "

" . $email . "

        <input type='number' min='0' class='rowElements inputSize' placeholder='0' name='beerSub-"
                    . $user ."'>

        <button class='rowElements btn btn-primary btn-sm inputSize' onclick='payBeer(".' "'.$user.'" '.",".' "'.$email.'" '.")'>
            Bezahlen
        </button>

</form>

Body:
The easiest thing to do is switch between block and none based on whether the search term is found in the specified element.

Start typing "bob" or "john" in the example below to see the effect.

function searchFunction() {
  const search = document.getElementById("myinput").value;
  const names = document.getElementsByClassName("names");
  //console.log(search)
  for (var i = 0; i < names.length; i++) {
     names[i].parentElement.style.display =
        (names[i].innerHTML.toUpperCase().includes(search.toUpperCase())
            ? "block"
            : "none");
  }

}

<form class="search">
     <input class="bar" type="search" name="search" placeholder="Nach Mitarbeiter suchen"autocomplete="off" id="myinput" oninput="searchFunction()">
     <div class='gridRow'>
         <p class='rowElements names'>Bob</p>
         <p class='rowElements beer'>Beer1</p>
         <p class='invisibleBullshit'>bob@bob.com</p>
         <input type='number' min='0' class='rowElements inputSize' placeholder='0' name='beerSub-bob'>
         <button class='rowElements btn btn-primary btn-sm inputSize' onclick='payBeer("bob","bob@bob.com")'>
             Bezahlen
          </button>
     </div>
     <div class='gridRow'>
         <p class='rowElements names'>John</p>
         <p class='rowElements beer'>Beer2</p>
         <p class='invisibleBullshit'>john@john.com</p>
         <input type='number' min='0' class='rowElements inputSize' placeholder='0' name='beerSub-john'>
         <button class='rowElements btn btn-primary btn-sm inputSize' onclick='payBeer("john","john@john.com")'>
             Bezahlen
          </button>
     </div>
</form>


问:
issues with angular to call api input via parameters
I am trying to fetch data from the API server using angular 9 bypassing id in the input from to get the phone value from JSON in the API. in this mount that not working with me :(, I don't know what the problem even I use the same format in JSON API.
like this one

this.phone = this.results.address.phone
  Please, I need someone to guide me for the right answer.

thank you :)

I live a simple of my work down!

This is my app.component.ts

```<code>import { Component } from '@angular/core';
import { HttpClient } from  '@angular/common/http';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent {
  constructor(private _http: HttpClient){}
url='https://jsonplaceholder.typicode.com/users/1';
id='';
phone='';
results : any;
getsearcha(){
  this._http.get('https://jsonplaceholder.typicode.com/users/'+this.id)
  .subscribe(

    data => {
      this.results = data['results'];
      this.phone = this.results.address.phone
     console.log(this._http.get(this.url));
    })
}
}
</code>```

as well the is my app.component.html

```<code><h1> test app</h1>
<input type="text" [(ngModel)]=id>

<button (click)="getsearcha()">Click</button>
<hr>
phone{{phone}}
</code>```

https://stackblitz.com/edit/angular-dryp3b

答:
According to  jsonplacerholde.typicode.com/users/{{id}}, It not returning you any array, it is simple object so change subsribe function to below one

```<code>getsearcha(){
  this._http.get('https://jsonplaceholder.typicode.com/users/'+this.id)
  .subscribe((userData:any) => {
      this.phone = userData.phone;
    });
}
</code>```

Good to go

Body:
I am trying to fetch data from the API server using angular 9 bypassing id in the input from to get the phone value from JSON in the API. in this mount that not working with me :(, I don't know what the problem even I use the same format in JSON API.
like this one

this.phone = this.results.address.phone
  Please, I need someone to guide me for the right answer.

thank you :)

I live a simple of my work down!

This is my app.component.ts

import { Component } from '@angular/core';
import { HttpClient } from  '@angular/common/http';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent {
  constructor(private _http: HttpClient){}
url='https://jsonplaceholder.typicode.com/users/1';
id='';
phone='';
results : any;
getsearcha(){
  this._http.get('https://jsonplaceholder.typicode.com/users/'+this.id)
  .subscribe(

    data => {
      this.results = data['results'];
      this.phone = this.results.address.phone
     console.log(this._http.get(this.url));
    })
}
}

as well the is my app.component.html

 test app

<input type="text" [(ngModel)]=id>

<button (click)="getsearcha()">Click</button>

phone{{phone}}

https://stackblitz.com/edit/angular-dryp3b

Body:
According to  jsonplacerholde.typicode.com/users/{{id}}, It not returning you any array, it is simple object so change subsribe function to below one

getsearcha(){
  this._http.get('https://jsonplaceholder.typicode.com/users/'+this.id)
  .subscribe((userData:any) => {
      this.phone = userData.phone;
    });
}

Good to go


问:
Can we solve factorial of a number using map reduce program?
Can we solve the factorial of a number using map-reduce program? If yes then how mapper and reducer will interact?</p>

答:
I wouldn't use mapreduce for just one number, but rather billions of numbers

The factorial of any number can be found by a simple for loop

MapReduce doesn't change that fact

And this would be a map-only task since no reduction is needed


问:
UnboundLocalError: local variable 'csv_file' referenced before assignment
When I run my code I get these errors:

```<code>if not csv_file.name.endswith('.csv'):

</code>```

UnboundLocalError: local variable 'csv_file' referenced before
  assignment

views.py

```<code>import csv, io
from django.shortcuts import render
from django.contrib import messages
from .models import Profile

# Create your views here.# one parameter named request
def profile_upload(request):    # declaring template
    template = "profile_upload.html"
    data = Profile.objects.all()# prompt is a context variable that can have different values      depending on their context
    prompt = {
        'order': 'Order of the CSV should be product_title, sku, slug, image_path, price',
        'profiles': data
              }
    # GET request returns the value of the data with the specified key.
    if request.method == "GET":
        return render(request, template, prompt)
        csv_file = request.FILES['file']    # let's check if it is a csv file
    if not csv_file.name.endswith('.csv'):
        messages.error(request, 'THIS IS NOT A CSV FILE')
        data_set = csv_file.read().decode('UTF-8')    # setup a stream which is when we loop through each line we are able to handle a data in a stream
        io_string = io.StringIO(data_set)
        next(io_string)
        for column in csv.reader(io_string, delimiter=',', quotechar="|"):
            _, created = Profile.objects.update_or_create(
                name=column[0],
                email=column[1],
                address=column[2],
                phone=column[3],
                profile=column[4]
            )
        context = {}
        return render(request, template, context)

</code>```

I am not sure why I am getting this error, it would be great if anyone can help me figure out what I am doing wrong.

答: You will need to initialize the csv_file variable at the start of method, or anywhere before assigning or referencing the variable

Body:
When I run my code I get these errors:

if not csv_file.name.endswith('.csv'):

UnboundLocalError: local variable 'csv_file' referenced before
  assignment

views.py

import csv, io
from django.shortcuts import render
from django.contrib import messages
from .models import Profile

# Create your views here.# one parameter named request
def profile_upload(request):    # declaring template
    template = "profile_upload.html"
    data = Profile.objects.all()# prompt is a context variable that can have different values      depending on their context
    prompt = {
        'order': 'Order of the CSV should be product_title, sku, slug, image_path, price',
        'profiles': data
              }
    # GET request returns the value of the data with the specified key.
    if request.method == "GET":
        return render(request, template, prompt)
        csv_file = request.FILES['file']    # let's check if it is a csv file
    if not csv_file.name.endswith('.csv'):
        messages.error(request, 'THIS IS NOT A CSV FILE')
        data_set = csv_file.read().decode('UTF-8')    # setup a stream which is when we loop through each line we are able to handle a data in a stream
        io_string = io.StringIO(data_set)
        next(io_string)
        for column in csv.reader(io_string, delimiter=',', quotechar="|"):
            _, created = Profile.objects.update_or_create(
                name=column[0],
                email=column[1],
                address=column[2],
                phone=column[3],
                profile=column[4]
            )
        context = {}
        return render(request, template, context)

I am not sure why I am getting this error, it would be great if anyone can help me figure out what I am doing wrong.


问:
How to find a substring from some text in a file and store it in a bash variable?
I have a file named config.txt which has following data:

```<code>ABC_PATH=xxx/xxx
IMAGE=docker.name.net:3000/apache:1.8.109.1
NAMESPACE=xxx
</code>```

Now I am running a shell script in which I want to store 1.8.109.1 (this value may differ, rest will remain same) in a variable, maybe using sed, awk or any other linux tool.
How can I achieve that?

答:
The following will work.

ver="$(cat config.txt | grep apache: | cut -d: -f3)"

grep apache: will find the line that has the text 'apache:' in it.

-d specifies what delimiters to use. In this case : is set as the delimiter.
-f is used to select the specific field (array index, starting at 1) of the resulting list obtained after delimiting by :

Thus, -f3 selects the 3rd occurence of the delimited list.

The version info is now captured in the variable $ver

Body:
I have a file named config.txt which has following data:

ABC_PATH=xxx/xxx
IMAGE=docker.name.net:3000/apache:1.8.109.1
NAMESPACE=xxx

Now I am running a shell script in which I want to store 1.8.109.1 (this value may differ, rest will remain same) in a variable, maybe using sed, awk or any other linux tool.
How can I achieve that?


问:
how to grab data from an AJAX query and display them on a text field?
I have this autocomplete ajax query. it create a dropdown list of the results and once you click the result is grab by a text field. here's the screenshot

screentshot after I click the drop down item

but as you can see, vendor id text field is not complete. What I want is to also populate the vendor id text field with vendor Id from the query.

from My controller

```<code>public function search(Request $request){
    if($request->ajax()) {
        $data = Vendor::where('vendor_id', 'LIKE', $request->vendor.'%')
            ->get();
        $output = '';

        if (count($data)>0) {
            $output = '<ul class="list-group" style="display: block; position: relative; z-index: 1">';
            foreach ($data as $row){
                $output .= '<li class="list-group-item">'.$row->vendor_name.'</li>';
            }
            $output .= '</ul>';
        }
        else {
            $output .= '<li class="list-group-item">'.'No results'.'</li>';
        }
        return $output;
    }
}
</code>```

MY BLADE

```<code><input type="text" name="vendor_id" id="vendor_id" data-type="vendor_id" placeholder="Enter vendor ID" class="form-control autocomplete_txt">
<div id="vendor_list"></div>

<input type="text" name="vendor_name" id="vendor_name" placeholder="Vendor Name" class="form-control" readonly="true">

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    <script type="text/javascript">
        $(document).ready(function () {
            $('#vendor_id').on('keyup',function() {
                var query = $(this).val();
                $.ajax({
                    url:"{{ route('admin.search') }}",
                    type:"GET",
                    data:{'vendor':query},
                    success:function (data) {
                        $('#vendor_list').html(data);
                    }
                })
            });

            $(document).on('click', 'li', function(){
                var value = $(this).text();
                $('#vendor_name').val(value);
                $('#vendor_list').html("");
            });
        });
    </script>
</code>```

vendors table

How can I achieve this? Hope you can help me. Thank you so much in advance!

答:
Change your code of controller like this:

```<code>   public function search(Request $request){
    if($request->ajax()) {
        $data = Vendor::where('vendor_id', 'LIKE', $request->vendor.'%')
            ->get();
        $output = '';

        if (count($data)>0) {
            $output = '<ul class="list-group" style="display: block; position: relative; z-index: 1">';
            foreach ($data as $row){
                $output .= '<li class="list-group-item" id="'.$row->vendor_id.'">'.$row->vendor_name.'</li>';
            }
            $output .= '</ul>';
        }
        else {
            $output .= '<li class="list-group-item">'.'No results'.'</li>';
        }
        return $output;
    }
}
</code>```

And Jquery like this:

```<code>$(document).ready(function () {
    $('#vendor_id').on('keyup',function() {
        var query = $(this).val();
        $.ajax({
            url:"{{ route('admin.search') }}",
            type:"GET",
            data:{'vendor':query},
            success:function (data) {
                $('#vendor_list').html(data);
            }
        })
    });

    $(document).on('click', 'li', function(){
        var value = $(this).text();
        var id = $(this).attr('id');
        $('#vendor_name').val(value);
        $('#vendor_id').val(id);
        $('#vendor_list').html("");
    });
});
</code>```

This is updated code. check once

Body:
I have this autocomplete ajax query. it create a dropdown list of the results and once you click the result is grab by a text field. here's the screenshot

screentshot after I click the drop down item

but as you can see, vendor id text field is not complete. What I want is to also populate the vendor id text field with vendor Id from the query.

from My controller

public function search(Request $request){
    if($request->ajax()) {
        $data = Vendor::where('vendor_id', 'LIKE', $request->vendor.'%')
            ->get();
        $output = '';

        if (count($data)>0) {
            $output = '
';
            foreach ($data as $row){
                $output .= '
'.$row->vendor_name.'
';
            }
            $output .= '
';
        }
        else {
            $output .= '
'.'No results'.'
';
        }
        return $output;
    }
}

MY BLADE

<input type="text" name="vendor_id" id="vendor_id" data-type="vendor_id" placeholder="Enter vendor ID" class="form-control autocomplete_txt">

<input type="text" name="vendor_name" id="vendor_name" placeholder="Vendor Name" class="form-control" readonly="true">

vendors table

How can I achieve this? Hope you can help me. Thank you so much in advance!

Body:
Change your code of controller like this:

   public function search(Request $request){
    if($request->ajax()) {
        $data = Vendor::where('vendor_id', 'LIKE', $request->vendor.'%')
            ->get();
        $output = '';

        if (count($data)>0) {
            $output = '<ul class="list-group" style="display: block; position: relative; z-index: 1">';
            foreach ($data as $row){
                $output .= '<li class="list-group-item" id="'.$row->vendor_id.'">'.$row->vendor_name.'</li>';
            }
            $output .= '</ul>';
        }
        else {
            $output .= '<li class="list-group-item">'.'No results'.'</li>';
        }
        return $output;
    }
}

And Jquery like this:

$(document).ready(function () {
    $('#vendor_id').on('keyup',function() {
        var query = $(this).val();
        $.ajax({
            url:"{{ route('admin.search') }}",
            type:"GET",
            data:{'vendor':query},
            success:function (data) {
                $('#vendor_list').html(data);
            }
        })
    });

    $(document).on('click', 'li', function(){
        var value = $(this).text();
        var id = $(this).attr('id');
        $('#vendor_name').val(value);
        $('#vendor_id').val(id);
        $('#vendor_list').html("");
    });
});

This is updated code. check once


问:
Error dialog displayed when opening an excel file generated with EPPlus
I am creating an Excel file using the EPPlus library. When I create file and open up the file, the following pop up message shows:

We found a problem with some content in 'ExcelDemo.xlsx'. Do you want us to try to recover as much as we can? If you trust the source of this workbook, Click Yes

I am using following code

```<code>using (ExcelPackage pck = new ExcelPackage())
{
    //Create the worksheet
    ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Demo");

    //Load the datatable into the sheet, starting from cell A1. Print the column names on row 1
    ws.Cells[1, 2].Value = "Excel Download";

    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    Response.AddHeader("content-disposition", "attachment;  filename=ExcelDemo.xlsx");
    Response.BinaryWrite(pck.GetAsByteArray());
}
</code>```

Is there problem in my code or is this an Excel issue?

答:
A solution I came up with was just returning the file object in the controller. The first argument should be the byte array (file), the second argument is the content type, and the last argument is the filename (in my case "report.xlsx").

```<code>return File(file, "application/octet-stream", fileName);
</code>```

Hope this helped.

Body:
I am creating an Excel file using the EPPlus library. When I create file and open up the file, the following pop up message shows:

We found a problem with some content in 'ExcelDemo.xlsx'. Do you want us to try to recover as much as we can? If you trust the source of this workbook, Click Yes

I am using following code

using (ExcelPackage pck = new ExcelPackage())
{
    //Create the worksheet
    ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Demo");

    //Load the datatable into the sheet, starting from cell A1. Print the column names on row 1
    ws.Cells[1, 2].Value = "Excel Download";

    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    Response.AddHeader("content-disposition", "attachment;  filename=ExcelDemo.xlsx");
    Response.BinaryWrite(pck.GetAsByteArray());
}

Is there problem in my code or is this an Excel issue?

Body:
A solution I came up with was just returning the file object in the controller. The first argument should be the byte array (file), the second argument is the content type, and the last argument is the filename (in my case "report.xlsx").

return File(file, "application/octet-stream", fileName);

Hope this helped.


问:
Caller id faker
I want to develop an android application to fake my mobile number to outgoing call. How to do this in android? I havent seen any api/control available to do this? Does android allow this? Is it legal for all the countries? Please give me some insight in this.</p>

答:
I don't think you can "edit" your outbound caller id, because your network provider is the one sending it to the recipient. What you probably can do is hide it.

Here is another SO question regarding this:

android Outbound caller id - on/off

Title: Caller id faker


问:
flutter check if user id exists in cloud firestore collection
I am trying to get the user id and check if exists in flutter using firestore but I don't get the correct result.</p>

```<code> handlesearch() {

final form = formkey.currentState;

    final Future<QuerySnapshot> result =  Firestore.instance
        .collection('users')
        .where('userid', isEqualTo: form)
        .getDocuments();

    setState(() {

      searchresult = result;

    });

 buildsearch() {

    return AppBar(
      title: Container(
        padding: EdgeInsets.all(10.0),
        child: Column(
          children: <Widget>[
            Form(
              key: formkey,
              child: TextFormField(
                controller: searchcontroller,
                onSaved: (val) => userid = val,
                // onFieldSubmitted: handlesearch,
              ),

            ),
            RaisedButton(
              child: Text('submit'),
              onPressed: handlesearch,
            )
          ],

 @override
  Widget build(BuildContext context) {

Scaffold(

      appBar:buildsearch(),

      body:
return FutureBuilder(

        future: searchresult,
        builder: (BuildContext context, AsyncSnapshot snapshot) {

          if(snapshot.hasData){
            return buildexists();
          }
            return builddoesntexists();

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

答:
I don't understand why or how you would use formkey.currentState to get the user id.

Instead, you might want to use the form controller : searchcontroller.text

But since you're saving it in a custom variable, you could also use it : userid

N.B :  in your onSaved function, be sure to call setState to rebuild with the updated value :

```<code>onSaved: (val) => setState(() => userid = val);
</code>```

Body:
I am trying to get the user id and check if exists in flutter using firestore but I don't get the correct result.

 handlesearch() {

final form = formkey.currentState;

    final Future<QuerySnapshot> result =  Firestore.instance
        .collection('users')
        .where('userid', isEqualTo: form)
        .getDocuments();

    setState(() {

      searchresult = result;

    });

 buildsearch() {

    return AppBar(
      title: Container(
        padding: EdgeInsets.all(10.0),
        child: Column(
          children: <Widget>[
            Form(
              key: formkey,
              child: TextFormField(
                controller: searchcontroller,
                onSaved: (val) => userid = val,
                // onFieldSubmitted: handlesearch,
              ),

            ),
            RaisedButton(
              child: Text('submit'),
              onPressed: handlesearch,
            )
          ],

 @override
  Widget build(BuildContext context) {

Scaffold(

      appBar:buildsearch(),

      body:
return FutureBuilder(

        future: searchresult,
        builder: (BuildContext context, AsyncSnapshot snapshot) {

          if(snapshot.hasData){
            return buildexists();
          }
            return builddoesntexists();

        }
        );
      }
}

Body:
I don't understand why or how you would use formkey.currentState to get the user id.

Instead, you might want to use the form controller : searchcontroller.text

But since you're saving it in a custom variable, you could also use it : userid

N.B :  in your onSaved function, be sure to call setState to rebuild with the updated value :

onSaved: (val) => setState(() => userid = val);


问:
Are merges in Git symmetric?
Lets say we have two branches (B and C) that have diverged from a common ancestor A. Will merging from B to C produce the same result as merging from C to B?

```<code>  A
  |
 / \
B   C
</code>```

To clarify- I'm assuming that any manual merge conflict resolutions will occur in both directions. But will any automatic merges that occur result in the same code being chosen? This is what I'm assuming, since the commit dates are identical in both directions.

To further clarify - I know that the actual merging results in "mirror images" of each other based on the direction. I'm just asking about the automatically resolved conflicts.

答:
The content of the files after the merge is 'symmetric' (the same, whichever merge you do), but if you use GitHub or Bitbucket or your favourite local Git viewer to view the changes made at the merge, you will see that the file changes shown in the merge commit are different depending on which merge you did (in addition to the other differences mentioned above, and in my edit below):

```<code>git checkout b
git merge c
</code>```

The file changes shown in the merge will be the changes which were made on c since b and c diverged.

```<code>git checkout c
git merge b
</code>```

The file changes shown in the merge will be the changes which were made on b since b and c diverged.

EDIT:

Another difference is that if you later do git reset [--hard] HEAD~{n} to roll back by a number of commits, and this goes back past the merge point, then the branch it goes back down is different depending on which merge you did, and is always the branch you merged 'into' (the one checked out, in the examples above).

Title: Are merges in Git symmetric?

Body:
Lets say we have two branches (B and C) that have diverged from a common ancestor A. Will merging from B to C produce the same result as merging from C to B?

  A
  |
 / \
B   C

To clarify- I'm assuming that any manual merge conflict resolutions will occur in both directions. But will any automatic merges that occur result in the same code being chosen? This is what I'm assuming, since the commit dates are identical in both directions.

To further clarify - I know that the actual merging results in "mirror images" of each other based on the direction. I'm just asking about the automatically resolved conflicts.

Body:
The content of the files after the merge is 'symmetric' (the same, whichever merge you do), but if you use GitHub or Bitbucket or your favourite local Git viewer to view the changes made at the merge, you will see that the file changes shown in the merge commit are different depending on which merge you did (in addition to the other differences mentioned above, and in my edit below):

git checkout b
git merge c

The file changes shown in the merge will be the changes which were made on c since b and c diverged.

git checkout c
git merge b

The file changes shown in the merge will be the changes which were made on b since b and c diverged.

EDIT:

Another difference is that if you later do git reset [--hard] HEAD~{n} to roll back by a number of commits, and this goes back past the merge point, then the branch it goes back down is different depending on which merge you did, and is always the branch you merged 'into' (the one checked out, in the examples above).


问:
ASSIGN fails with variable from debugger path
I am trying to assign the value of this stucture path to a fieldsymbol, but this path does not work because it has a table in it's path.

But with in the debugger this value of this path is shown correctly.

Is there a way to dynamically assign a component of a table line to a fieldsymbol, by passing one path?
If not then I will just read the table line and then use the path to get the wanted value.

```<code>ls_struct (Struct)
    - SUPPLYCHAINTRADETRANSACTION (Struct)
        - INCL_SUPP_CHAIN_ITEM (Table)
            - ASSOCIATEDDOCUMENTLINEDOCUMENT (Element)

i_component_path = |IG_DDIC-SUPPLYCHAINTRADETRANSACTION-INCL_SUPP_CHAIN_ITEM[1]-ASSOCIATEDDOCUMENTLINEDOCUMENT|.
ASSIGN (i_component_path) TO FIELD-SYMBOL(<lg_value>).
IF <lg_value> IS NOT ASSIGNED.
    return.
ENDIF.

<lg_value> won't be assigned
</code>```

答:
This seems to be a rather unexpected limitation of the ASSIGN statement. Probably worth a ticket to SAP's ABAP language group to clarify whether it's even a bug.

While this works:

```<code>ASSIGN data-some_table[ 1 ]-some_field TO FIELD-SYMBOL(<lv_source>).
</code>```

the same expressed as a string doesn't:

```<code>ASSIGN (`data-some_table[ 1 ]-some_field`) TO FIELD-SYMBOL(<lv_source>).
</code>```

Alternative 1 for (name) of the ABAP keyword documentation for the ASSIGN statement says that "[t]he name in name is structured in the same way as if specified directly".

However, this declaration is immediately followed by "the content of name must be the name of a data object which may contain offsets and lengths, structure component selectors, and component selectors for assigning structured data objects and attributes in classes or objects", a list that does not include the table expressions we would need here.

Body:
I am trying to assign the value of this stucture path to a fieldsymbol, but this path does not work because it has a table in it's path.

But with in the debugger this value of this path is shown correctly.

Is there a way to dynamically assign a component of a table line to a fieldsymbol, by passing one path?
If not then I will just read the table line and then use the path to get the wanted value.

ls_struct (Struct)
    - SUPPLYCHAINTRADETRANSACTION (Struct)
        - INCL_SUPP_CHAIN_ITEM (Table)
            - ASSOCIATEDDOCUMENTLINEDOCUMENT (Element)

i_component_path = |IG_DDIC-SUPPLYCHAINTRADETRANSACTION-INCL_SUPP_CHAIN_ITEM[1]-ASSOCIATEDDOCUMENTLINEDOCUMENT|.
ASSIGN (i_component_path) TO FIELD-SYMBOL(<lg_value>).
IF <lg_value> IS NOT ASSIGNED.
    return.
ENDIF.

<lg_value> won't be assigned

Body:
This seems to be a rather unexpected limitation of the ASSIGN statement. Probably worth a ticket to SAP's ABAP language group to clarify whether it's even a bug.

While this works:

ASSIGN data-some_table[ 1 ]-some_field TO FIELD-SYMBOL(<lv_source>).

the same expressed as a string doesn't:

ASSIGN (`data-some_table[ 1 ]-some_field`) TO FIELD-SYMBOL(<lv_source>).

Alternative 1 for (name) of the ABAP keyword documentation for the ASSIGN statement says that "[t]he name in name is structured in the same way as if specified directly".

However, this declaration is immediately followed by "the content of name must be the name of a data object which may contain offsets and lengths, structure component selectors, and component selectors for assigning structured data objects and attributes in classes or objects", a list that does not include the table expressions we would need here.


问:
OpenGL Convert NV12 to RGB24 using shader
I tried to write an application to display YUV image in OpenGL. I was successfully converted YUV to RGB in C++ using this snippet (source)

```<code>static long int crv_tab[256];
static long int cbu_tab[256];
static long int cgu_tab[256];
static long int cgv_tab[256];
static long int tab_76309[256];
static unsigned char clp[1024];   //for clip in CCIR601

void init_yuv420p_table()
{
    long int crv,cbu,cgu,cgv;
    int i,ind;
    static int init = 0;

    if (init == 1) return;

    crv = 104597; cbu = 132201;  /* fra matrise i global.h */
    cgu = 25675;  cgv = 53279;

    for (i = 0; i < 256; i++)
    {
        crv_tab[i] = (i-128) * crv;
        cbu_tab[i] = (i-128) * cbu;
        cgu_tab[i] = (i-128) * cgu;
        cgv_tab[i] = (i-128) * cgv;
        tab_76309[i] = 76309*(i-16);
    }

    for (i = 0; i < 384; i++)
        clp[i] = 0;
    ind = 384;
    for (i = 0;i < 256; i++)
        clp[ind++] = i;
    ind = 640;
    for (i = 0;i < 384; i++)
        clp[ind++] = 255;

    init = 1;
}

void yuv420sp_to_rgb24(YUV_TYPE type, unsigned char* yuvbuffer,unsigned char* rgbbuffer, int width,int height)
{
    int y1, y2, u, v;
    unsigned char *py1, *py2;
    int i, j, c1, c2, c3, c4;
    unsigned char *d1, *d2;
    unsigned char *src_u;
    static int init_yuv420p = 0;

    src_u = yuvbuffer + width * height;   // u

    py1 = yuvbuffer;   // y
    py2 = py1 + width;
    d1 = rgbbuffer;
    d2 = d1 + 3 * width;

    init_yuv420p_table();

    for (j = 0; j < height; j += 2)
    {
        for (i = 0; i < width; i += 2)
        {
            if (type ==  FMT_NV12)
            {
                u = *src_u++;
                v = *src_u++;      // v紧跟u，在u的下一个位置
            }
            if (type == FMT_NV21)
            {
                v = *src_u++;
                u = *src_u++;      // u紧跟v，在v的下一个位置
            }

            c1 = crv_tab[v];
            c2 = cgu_tab[u];
            c3 = cgv_tab[v];
            c4 = cbu_tab[u];

            //up-left
            y1 = tab_76309[*py1++];
            *d1++ = clp[384+((y1 + c1)>>16)];
            *d1++ = clp[384+((y1 - c2 - c3)>>16)];
            *d1++ = clp[384+((y1 + c4)>>16)];

            //down-left
            y2 = tab_76309[*py2++];
            *d2++ = clp[384+((y2 + c1)>>16)];
            *d2++ = clp[384+((y2 - c2 - c3)>>16)];
            *d2++ = clp[384+((y2 + c4)>>16)];

            //up-right
            y1 = tab_76309[*py1++];
            *d1++ = clp[384+((y1 + c1)>>16)];
            *d1++ = clp[384+((y1 - c2 - c3)>>16)];
            *d1++ = clp[384+((y1 + c4)>>16)];

            //down-right
            y2 = tab_76309[*py2++];
            *d2++ = clp[384+((y2 + c1)>>16)];
            *d2++ = clp[384+((y2 - c2 - c3)>>16)];
            *d2++ = clp[384+((y2 + c4)>>16)];
        }
        d1  += 3*width;
        d2  += 3*width;
        py1 += width;
        py2 += width;
    }
}
</code>```

In order to make my application runs smoother, instead of doing the conversion on the CPU, I do it in the fragment shader.

I separate the YUV buffer into Y_Buffer[width*height], U_Buffer[width*height/4] and V_Buffer[width*height/4] from the interleaved UV_Buffer[width*height/2] and pass it to the fragment shader. (I intended to pass the Y_Buffer and the UV_Buffer with the type format GL_RED and GL_RG respectively by using glTexImage2D but somehow when I read the G channel of the UV_Texture in the fragment shader, it always returns 0).

Below is the conversion in the fragment shader:

```<code>uniform sampler2D textureY;
uniform sampler2D textureU;
uniform sampler2D textureV;
void main() {
    vec3 yuv, rgb;
    vec3 yuv2r = vec3(1.164, 0.0, 1.596);
    vec3 yuv2g = vec3(1.164, -0.391, -0.813);
    vec3 yuv2b = vec3(1.164, 2.018, 0.0);

    yuv.x = texture(textureY, texCoord).r - 0.0625;
    yuv.y = texture(textureU, texCoord).r - 0.5;
    yuv.z = texture(textureV, texCoord).r - 0.5;

    rgb.x = dot(yuv, yuv2r);
    rgb.y = dot(yuv, yuv2g);
    rgb.z = dot(yuv, yuv2b);

    FragColor = vec4(rgb, 1.0);
}
</code>```

But all I got is green and pink pixels. I'm quite a newbie in OpenGL. Can anyone point out where I may be wrong? Your help is appreciated.

Update: Add codes that load texture

```<code>FILE fp = fopen("nv21.raw", "rb");
unsigned char *yuvBuffer = new unsigned char[width*height*3/2];
fread(yuvBuffer, 1, width*height*3/2, fp);

unsigned char *vuBuffer = &yuvBuffer[width*height];

int bufSize = width*height/4;
unsigned char *uBuffer = new unsigned char[bufSize];
memset(uBuffer, 0, bufSize);
unsigned char *vBuffer = new unsigned char[bufSize];
memset(vBuffer, 0, bufSize);

unsigned char *uPtr, *vPtr;
uPtr = uBuffer;
vPtr = vBuffer;

for (int i = 0; i < bufSize; i++)
{
    *vPtr = *vuBuffer++;
    *uPtr = *vuBuffer++;
}

GLuint textureID[3];

glGenTextures(1, &textureID[0]);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, textureID[0]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, width, height, 0, GL_RED, GL_UNSIGNED_BYTE, &yuvBuffer[0]);
glBindTexture(0);

glGenTextures(1, &textureID[1]);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, textureID[1]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, width/2, height/2, 0, GL_RED, GL_UNSIGNED_BYTE, uBuffer);
glBindTexture(0);

glGenTextures(1, &textureID[2]);
glActiveTexture(GL_TEXTURE2);
glBindTexture(GL_TEXTURE_2D, textureID[2]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, width/2, height/2, 0, GL_RED, GL_UNSIGNED_BYTE, vBuffer);
glBindTexture(0);
</code>```

答:
By default the texture samplers in the shader program are associated to texture unit 0 (default value is 0).

You have to assign the index of the texture unit to the texture sampler uniforms, by glUniform1i. The texture unit is the binding point between the Sampler and the Texture object. e.g.:

GLint locTexY = glGetUniformLocation(program, "textureY");
GLint locTexU = glGetUniformLocation(program, "textureU");
GLint locTexV = glGetUniformLocation(program, "textureV");
```

<pre class="lang-cpp prettyprint-override"><code>glUseProgram(program);
glUniform1i(locTexY, 0); // corresponds to GL_TEXTURE0
glUniform1i(locTexU, 1); // corresponds to GL_TEXTURE1
glUniform1i(locTexV, 2); // corresponds to GL_TEXTURE2
</code>```

Since OpenGL 4.20, the Binding points can be set in-shader by Layout Qualifier:

layout(binding = 0) uniform sampler2D textureY;
layout(binding = 1) uniform sampler2D textureU;
layout(binding = 2) uniform sampler2D textureV;
```

Body:
I tried to write an application to display YUV image in OpenGL. I was successfully converted YUV to RGB in C++ using this snippet (source)

static long int crv_tab[256];
static long int cbu_tab[256];
static long int cgu_tab[256];
static long int cgv_tab[256];
static long int tab_76309[256];
static unsigned char clp[1024];   //for clip in CCIR601

void init_yuv420p_table()
{
    long int crv,cbu,cgu,cgv;
    int i,ind;
    static int init = 0;

    if (init == 1) return;

    crv = 104597; cbu = 132201;  /* fra matrise i global.h */
    cgu = 25675;  cgv = 53279;

    for (i = 0; i < 256; i++)
    {
        crv_tab[i] = (i-128) * crv;
        cbu_tab[i] = (i-128) * cbu;
        cgu_tab[i] = (i-128) * cgu;
        cgv_tab[i] = (i-128) * cgv;
        tab_76309[i] = 76309*(i-16);
    }

    for (i = 0; i < 384; i++)
        clp[i] = 0;
    ind = 384;
    for (i = 0;i < 256; i++)
        clp[ind++] = i;
    ind = 640;
    for (i = 0;i < 384; i++)
        clp[ind++] = 255;

    init = 1;
}

void yuv420sp_to_rgb24(YUV_TYPE type, unsigned char* yuvbuffer,unsigned char* rgbbuffer, int width,int height)
{
    int y1, y2, u, v;
    unsigned char *py1, *py2;
    int i, j, c1, c2, c3, c4;
    unsigned char *d1, *d2;
    unsigned char *src_u;
    static int init_yuv420p = 0;

    src_u = yuvbuffer + width * height;   // u

    py1 = yuvbuffer;   // y
    py2 = py1 + width;
    d1 = rgbbuffer;
    d2 = d1 + 3 * width;

    init_yuv420p_table();

    for (j = 0; j < height; j += 2)
    {
        for (i = 0; i < width; i += 2)
        {
            if (type ==  FMT_NV12)
            {
                u = *src_u++;
                v = *src_u++;      // v紧跟u，在u的下一个位置
            }
            if (type == FMT_NV21)
            {
                v = *src_u++;
                u = *src_u++;      // u紧跟v，在v的下一个位置
            }

            c1 = crv_tab[v];
            c2 = cgu_tab[u];
            c3 = cgv_tab[v];
            c4 = cbu_tab[u];

            //up-left
            y1 = tab_76309[*py1++];
            *d1++ = clp[384+((y1 + c1)>>16)];
            *d1++ = clp[384+((y1 - c2 - c3)>>16)];
            *d1++ = clp[384+((y1 + c4)>>16)];

            //down-left
            y2 = tab_76309[*py2++];
            *d2++ = clp[384+((y2 + c1)>>16)];
            *d2++ = clp[384+((y2 - c2 - c3)>>16)];
            *d2++ = clp[384+((y2 + c4)>>16)];

            //up-right
            y1 = tab_76309[*py1++];
            *d1++ = clp[384+((y1 + c1)>>16)];
            *d1++ = clp[384+((y1 - c2 - c3)>>16)];
            *d1++ = clp[384+((y1 + c4)>>16)];

            //down-right
            y2 = tab_76309[*py2++];
            *d2++ = clp[384+((y2 + c1)>>16)];
            *d2++ = clp[384+((y2 - c2 - c3)>>16)];
            *d2++ = clp[384+((y2 + c4)>>16)];
        }
        d1  += 3*width;
        d2  += 3*width;
        py1 += width;
        py2 += width;
    }
}

In order to make my application runs smoother, instead of doing the conversion on the CPU, I do it in the fragment shader.

I separate the YUV buffer into Y_Buffer[width*height], U_Buffer[width*height/4] and V_Buffer[width*height/4] from the interleaved UV_Buffer[width*height/2] and pass it to the fragment shader. (I intended to pass the Y_Buffer and the UV_Buffer with the type format GL_RED and GL_RG respectively by using glTexImage2D but somehow when I read the G channel of the UV_Texture in the fragment shader, it always returns 0).

Below is the conversion in the fragment shader:

uniform sampler2D textureY;
uniform sampler2D textureU;
uniform sampler2D textureV;
void main() {
    vec3 yuv, rgb;
    vec3 yuv2r = vec3(1.164, 0.0, 1.596);
    vec3 yuv2g = vec3(1.164, -0.391, -0.813);
    vec3 yuv2b = vec3(1.164, 2.018, 0.0);

    yuv.x = texture(textureY, texCoord).r - 0.0625;
    yuv.y = texture(textureU, texCoord).r - 0.5;
    yuv.z = texture(textureV, texCoord).r - 0.5;

    rgb.x = dot(yuv, yuv2r);
    rgb.y = dot(yuv, yuv2g);
    rgb.z = dot(yuv, yuv2b);

    FragColor = vec4(rgb, 1.0);
}

But all I got is green and pink pixels. I'm quite a newbie in OpenGL. Can anyone point out where I may be wrong? Your help is appreciated.

Update: Add codes that load texture

FILE fp = fopen("nv21.raw", "rb");
unsigned char *yuvBuffer = new unsigned char[width*height*3/2];
fread(yuvBuffer, 1, width*height*3/2, fp);

unsigned char *vuBuffer = &yuvBuffer[width*height];

int bufSize = width*height/4;
unsigned char *uBuffer = new unsigned char[bufSize];
memset(uBuffer, 0, bufSize);
unsigned char *vBuffer = new unsigned char[bufSize];
memset(vBuffer, 0, bufSize);

unsigned char *uPtr, *vPtr;
uPtr = uBuffer;
vPtr = vBuffer;

for (int i = 0; i < bufSize; i++)
{
    *vPtr = *vuBuffer++;
    *uPtr = *vuBuffer++;
}

GLuint textureID[3];

glGenTextures(1, &textureID[0]);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, textureID[0]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, width, height, 0, GL_RED, GL_UNSIGNED_BYTE, &yuvBuffer[0]);
glBindTexture(0);

glGenTextures(1, &textureID[1]);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, textureID[1]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, width/2, height/2, 0, GL_RED, GL_UNSIGNED_BYTE, uBuffer);
glBindTexture(0);

glGenTextures(1, &textureID[2]);
glActiveTexture(GL_TEXTURE2);
glBindTexture(GL_TEXTURE_2D, textureID[2]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, width/2, height/2, 0, GL_RED, GL_UNSIGNED_BYTE, vBuffer);
glBindTexture(0);

Body:
By default the texture samplers in the shader program are associated to texture unit 0 (default value is 0).

You have to assign the index of the texture unit to the texture sampler uniforms, by glUniform1i. The texture unit is the binding point between the Sampler and the Texture object. e.g.:

GLint locTexY = glGetUniformLocation(program, "textureY");
GLint locTexU = glGetUniformLocation(program, "textureU");
GLint locTexV = glGetUniformLocation(program, "textureV");

glUseProgram(program);
glUniform1i(locTexY, 0); // corresponds to GL_TEXTURE0
glUniform1i(locTexU, 1); // corresponds to GL_TEXTURE1
glUniform1i(locTexV, 2); // corresponds to GL_TEXTURE2

Since OpenGL 4.20, the Binding points can be set in-shader by Layout Qualifier:

layout(binding = 0) uniform sampler2D textureY;
layout(binding = 1) uniform sampler2D textureU;
layout(binding = 2) uniform sampler2D textureV;


问:
How to remove only extension from origin file with certain extension recursively in folder?
How to remove only extension from origin file with certain extension recursively in folder?

example, If I have

```<code>/foo/bar/index.html
/foo/bar/error.html
/foo/bar/static/hi.html
/foo/bar/static/me.jpg
/foo/bar/static/you.jpg
/foo/bar/build/yep.html
</code>```

And I expect follows after excute some command

```<code>/foo/bar/index
/foo/bar/error
/foo/bar/static/hi
/foo/bar/static/me.jpg
/foo/bar/static/you.jpg
/foo/bar/build/yep
</code>```

Thanks for the help.
Please tell some OS's command If command exist (windows, ubuntu/linux)

答:
As a command :</p>

```<code>ls | find *.html | for f in *.html; do mv $f $(echo $f|sed s/.html//);done
</code>```

Body:
How to remove only extension from origin file with certain extension recursively in folder?

example, If I have

/foo/bar/index.html
/foo/bar/error.html
/foo/bar/static/hi.html
/foo/bar/static/me.jpg
/foo/bar/static/you.jpg
/foo/bar/build/yep.html

And I expect follows after excute some command

/foo/bar/index
/foo/bar/error
/foo/bar/static/hi
/foo/bar/static/me.jpg
/foo/bar/static/you.jpg
/foo/bar/build/yep

Thanks for the help.
Please tell some OS's command If command exist (windows, ubuntu/linux)

Body:
As a command :

ls | find *.html | for f in *.html; do mv $f $(echo $f|sed s/.html//);done


问:
I can't compile opencv samples with VS2010 on vista
I am using visual studio 2010 on windows vista. I want to compile a sample file of OPENCV named "find_obj.cpp" created by liuliu.

Here is the address of source code.

https://code.ros.org/trac/opencv/browser/trunk/opencv/samples/c/find_obj.cpp

Other opencv codes works well but I couldn't compile this. please help

I've installed all of the libraries needed and opencv. Other opencv projects of mine are working fine.

My error is "unresolved externals"
here it is,

Error  14  error LNK1120: 11 unresolved externals

  Error   4   error LNK2019: unresolved external symbol "class cvflann::Logger & __cdecl cvflann::logger(void)" (?logger@cvflann@@YAAAVLogger@1@XZ) referenced in function "public: virtual void __thiscall cvflann::KDTreeIndexParams::print(void)const " (?print@KDTreeIndexParams@cvflann@@UBEXXZ

答:
I solved the problem. In this sample it uses flann functions and I added the opencv_flann220d.lib to libraries section in visual studio. Now, program compiles with no error.

And I learned that if you're getting "unresolved externals" error it is mostly because of missing of include directories or libraries.

greetings


答:
You could insert the row and then use SCOPE_IDENTITY() to get the ID of the row you inserted and return the row with that id from the table.

For example:

```<code>INSERT INTO tableA VALUES (a1, a2);

DECLARE @Id INT = SCOPE_IDENTITY();

SELECT * FROM tableA WHERE ID = @Id
</code>```

Title: Return inserted row

Body:
How do I return the row I just inserted including DB-generated identifier?
My SQL is just a standard dynamic SQL insert

insert into dbo.TableName (Col1, Col2) values (@Col1, @Col2);

I have tried select from inserted, but inserted object is not a known object

insert into dbo.TableName (Col1, Col2) values (@Col1, @Col2); select * from inserted;

I have tried using output, but I cannot do that, when there is a trigger on the table

insert into dbo.TableName (Col1, Col2) output inserted.* values (@Col1, @Col2);

Any ideas?

Body:
You could insert the row and then use SCOPE_IDENTITY() to get the ID of the row you inserted and return the row with that id from the table.

For example:

INSERT INTO tableA VALUES (a1, a2);

DECLARE @Id INT = SCOPE_IDENTITY();

SELECT * FROM tableA WHERE ID = @Id


问:
Change all Divs color when Clicking [ Javascript ]
I try to write a program to change all div color when clicking.
First, on a single click it changes each Div color  and everything works fine!
The problem comes when I add some code to change all div color when clicking the div element with attribute credit but is not working !!

let x = document.getElementById("container");
let y = x.children;

function myFunction() {
  for (let i = 0; i < y.length; i++) {
    let click = 0;
    y[i].onclick = function() {
      if (click == 0) {
        y[i].style.color = "red";
        click = 1;
      } else {
        y[i].style.color = "blue";
        click = 0;
      }

      //when clicking this div change color of all divs to yellow

      if (y[i].getAttribute("credit")) {
          y[i].style.color = "yellow";
        }
      }
    }
  }
  myFunction();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!doctype html>
<html lang="en">

<head>
  <!-- Required meta tags -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>clciks</title>
</head>

<body>
  <div id="container">
    <div value="one">This is Div 1</div>
    <div value="two">This is Div 2</div>
    <div credit="very good">This is Div 3</div>
  </div>
</body>

</html></code>```

答:
To achieve what you want you should iterate and set color on all the children if the clicked element has 'credit' attribute.
Considering other comments I have renamed the attributes with 'data-' prefix.
You can either give all div's a class name and iterate that way or you can just iterate on x.children, which ever is best suited for your scenario.

// update:
Updated the code to handle additional questions in comments

See working snippet below:

let x = document.getElementById("container");
let y = x.children;

// define your colors here
const colorsMap = {
 "setA": ["red","blue"],
 "setB": ["yellow", "orange"]
};

// generates a function to handle color change for the element
// the color sets specific to each element is defined as data-colors in html
function handleColorChange(ele) {
  const colorset = colorsMap[ele.getAttribute("data-colors") || "setA"];
  const value = ele.getAttribute("data-value");
  const credit = ele.getAttribute("data-credit") || false;

  let click = 0;

  return () => {
    // change below line if you don't need to loop on colors
    const color = colorset[click % colorset.length];
    click++;

    if (credit) {
      Object.values(x.children).forEach(
        function(child) { child.style.color = color; }
      );
    }
    else {
      ele.style.color = color;
    }
  }
}

// attach color changing functions
function myFunction() {
  for (let i = 0; i < y.length; i++) {
    let ele = y[i];
    ele.onclick = handleColorChange(ele);
  }
}

myFunction();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.color-test {
 cursor: pointer;
}</code>```

<!doctype html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>clciks</title>

This is Div 1

This is Div 2

This is Div 3

```

Body:
I try to write a program to change all div color when clicking.
First, on a single click it changes each Div color  and everything works fine!
The problem comes when I add some code to change all div color when clicking the div element with attribute credit but is not working !!

let x = document.getElementById("container");
let y = x.children;

function myFunction() {
  for (let i = 0; i < y.length; i++) {
    let click = 0;
    y[i].onclick = function() {
      if (click == 0) {
        y[i].style.color = "red";
        click = 1;
      } else {
        y[i].style.color = "blue";
        click = 0;
      }

      //when clicking this div change color of all divs to yellow

      if (y[i].getAttribute("credit")) {
          y[i].style.color = "yellow";
        }
      }
    }
  }
  myFunction();

<!doctype html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>clciks</title>

This is Div 1

This is Div 2

This is Div 3

Body:
To achieve what you want you should iterate and set color on all the children if the clicked element has 'credit' attribute.
Considering other comments I have renamed the attributes with 'data-' prefix.
You can either give all div's a class name and iterate that way or you can just iterate on x.children, which ever is best suited for your scenario.

// update:
Updated the code to handle additional questions in comments

See working snippet below:

let x = document.getElementById("container");
let y = x.children;

// define your colors here
const colorsMap = {
 "setA": ["red","blue"],
 "setB": ["yellow", "orange"]
};

// generates a function to handle color change for the element
// the color sets specific to each element is defined as data-colors in html
function handleColorChange(ele) {
  const colorset = colorsMap[ele.getAttribute("data-colors") || "setA"];
  const value = ele.getAttribute("data-value");
  const credit = ele.getAttribute("data-credit") || false;

  let click = 0;

  return () => {
    // change below line if you don't need to loop on colors
    const color = colorset[click % colorset.length];
    click++;

    if (credit) {
      Object.values(x.children).forEach(
        function(child) { child.style.color = color; }
      );
    }
    else {
      ele.style.color = color;
    }
  }
}

// attach color changing functions
function myFunction() {
  for (let i = 0; i < y.length; i++) {
    let ele = y[i];
    ele.onclick = handleColorChange(ele);
  }
}

myFunction();

.color-test {
 cursor: pointer;
}

<!doctype html>
<html lang="en">

<head>
  <!-- Required meta tags -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>clciks</title>
</head>

<body>
  <div id="container">
    <div class="color-test" data-value="one" data-colors="setA">This is Div 1</div>
    <div class="color-test" data-value="two" data-colors="setA">This is Div 2</div>
    <div class="color-test" data-credit="very good" data-colors="setB">This is Div 3</div>
  </div>
</body>

</html>


问:
Displaying dictionary values each in a UITableViewCell
My overall objective here is to create a UITableView that has alphabetical section titles based on the values in a dictionary.

I have a basic object which includes the fruit's name and description. I would like the names of the fruit to each be displayed on a UITableCell, under the cooresponding letter for the section title.

Ultimately, the tableview will look something like this: (where C P S are the section titles)

```<code>C------------
Clementine
Cherry
Coconut
P------------
Pear
Peach
S------------
Strawberry
</code>```

Here is my data:

```<code>var fruitModel = [String:Any]()

fruitModel = [
    "C" : [
    FruitModel(name: "Clementine", description: "Clementines are super tasty!"),
    FruitModel(name: "Cherry", description: "Cherry's are red."),
    FruitModel(name: "Coconut", description: "Nuts for coconuts!!!"),
    ],
    "P" : [
    FruitModel(name: "Pear", description: "Pears rock!"),
    FruitModel(name: "Peach", description: "Mmmm, Peach."),
    ],
    "S" : [
    FruitModel(name: "Strawberry", description: "A widely grown hybrid species of the genus Fragaria. It is cultivated worldwide for its fruit.")
    ]
]
</code>```

The part that's throwing me off is accessing the name string, inside the dictionary's value, and displaying it in cellForRowAt. The code below is where I am stuck:

cellForRowAt:

```<code>var allValues = Array(fruitModel.values)
cell.fruitNameLabel.text = (allValues[indexPath.row] as AnyObject).name // Cannot subscript a value of type 'inout Array<Any>'
</code>```

Once I figure out how to display the fruit names in each cell, I'll be able to get the section titles working. I just need assistance with my error that i'm getting. Thanks.

答:
Display for Array of dictionary values in table view in swift

```<code>var arrayDictionary = [[String:Any]]()

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cellTable = tableview.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell
            cellTable.labelTitle.text = arrayDictionary[indexPath.row]["name"] as? String
            cellTable.labelAuthor.text = arrayDictionary[indexPath.row]["region"] as? String
            cellTable.labelDescription.text = arrayDictionary[indexPath.row]["subregion"] as? String
            return cellTable
        }
</code>```

Body:
My overall objective here is to create a UITableView that has alphabetical section titles based on the values in a dictionary.

I have a basic object which includes the fruit's name and description. I would like the names of the fruit to each be displayed on a UITableCell, under the cooresponding letter for the section title.

Ultimately, the tableview will look something like this: (where C P S are the section titles)

C------------
Clementine
Cherry
Coconut
P------------
Pear
Peach
S------------
Strawberry

Here is my data:

var fruitModel = [String:Any]()

fruitModel = [
    "C" : [
    FruitModel(name: "Clementine", description: "Clementines are super tasty!"),
    FruitModel(name: "Cherry", description: "Cherry's are red."),
    FruitModel(name: "Coconut", description: "Nuts for coconuts!!!"),
    ],
    "P" : [
    FruitModel(name: "Pear", description: "Pears rock!"),
    FruitModel(name: "Peach", description: "Mmmm, Peach."),
    ],
    "S" : [
    FruitModel(name: "Strawberry", description: "A widely grown hybrid species of the genus Fragaria. It is cultivated worldwide for its fruit.")
    ]
]

The part that's throwing me off is accessing the name string, inside the dictionary's value, and displaying it in cellForRowAt. The code below is where I am stuck:

cellForRowAt:

var allValues = Array(fruitModel.values)
cell.fruitNameLabel.text = (allValues[indexPath.row] as AnyObject).name // Cannot subscript a value of type 'inout Array<Any>'

Once I figure out how to display the fruit names in each cell, I'll be able to get the section titles working. I just need assistance with my error that i'm getting. Thanks.

Body:
Display for Array of dictionary values in table view in swift

var arrayDictionary = [[String:Any]]()

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cellTable = tableview.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell
            cellTable.labelTitle.text = arrayDictionary[indexPath.row]["name"] as? String
            cellTable.labelAuthor.text = arrayDictionary[indexPath.row]["region"] as? String
            cellTable.labelDescription.text = arrayDictionary[indexPath.row]["subregion"] as? String
            return cellTable
        }


问:
How do I insert an uploaded image into an  tag/placeholder?
How do I insert an uploaded image into an html  tag?
Is it possible to create an  tag as placeholder for uploaded images?

I can select an image with "< input type="file" name="fileToUpload" id="fileToUpload" >" and after this i want to send that image to an img placeholder.

And is it possible to delete the uploaded image from the placeholder after the user closed the website?

Thanks a lot!

答:
You can try like this </p>

```<code><input type="file" id="docpicker" accept="image/*" onChange={updateImageDisplay} multiple></input>
<div class="previewContainer">
   <p>No files currently selected for upload</p>
</div>
</code>```

```<code>const updateImageDisplay = ss => {
  const input = document.querySelector('input');
  const previewContainer = document.querySelector('.previewContainer');
  [...input.files].forEach(file => {
    const image = document.createElement('img');
    image.src = URL.createObjectURL(file);
    previewContainer.appendChild(image);
  })
}
</code>```

Title: How do I insert an uploaded image into an <IMG> tag/placeholder?

Body:
You can try like this

<input type="file" id="docpicker" accept="image/*" onChange={updateImageDisplay} multiple></input>
<div class="previewContainer">
   <p>No files currently selected for upload</p>
</div>

const updateImageDisplay = ss => {
  const input = document.querySelector('input');
  const previewContainer = document.querySelector('.previewContainer');
  [...input.files].forEach(file => {
    const image = document.createElement('img');
    image.src = URL.createObjectURL(file);
    previewContainer.appendChild(image);
  })
}