问:
Laravel Controller Function Run Twice
I'm using laravel to controller my data when I create data it create twice.

Here is code in my food controller

```<code><?php

namespace App\Http\Controllers;

use App\Food;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class FoodController extends Controller
{
    //
    public function index()
    {
        error_log('geting food');
        return Food::all();
    }

    public function create()
    {
        $validator = Validator::make(request()->all(), [
            'food_name' => 'required|string|max:100',
            'food_type_id' => 'required|string|max:100|exists:food_types,id',
            'price' => 'required|numeric|between:0,99.99'
        ]);
        if ($validator->fails()) {
            return response()->json($validator->errors(), 400);
        }
        $food = Food::create(request()->all());

        error_log("Inserting");
        return $food;
    }
    public function getById($id){
        return Food::all()->find($id);
    }
    public function update(){
        $validator = Validator::make(request()->all(), [
            'id'=> 'required|integer',
            'food_name' => 'required|string|max:100',
            'food_type_id' => 'required|string|max:100|exists:food_types,id',
            'price' => 'required|numeric|between:0,99.99'
        ]);
        if ($validator->fails()) {
            return response()->json($validator->errors(), 400);
        }
        $food=Food::where('id',request('id'))->get()[0];
        $food->fill(request()->all());
        $food->save();
        return $food;
    }
}

</code>```

Here is the result after I request create once. I don't know what wrong of middleware or something else. It seem it do twice every single request.

Here is api my route

```<code><?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::post('login', 'UserController@authenticate');
Route::get('open', 'DataController@open');
Route::post('register', 'UserController@register');
Route::group(['middleware' => ['jwt.verify']], function () {

    Route::get('user', 'UserController@getAuthenticatedUser');

    Route::group(['prefix'=>'food-type'],function(){
        Route::get('/','FoodTypeController@index');
        Route::get('/getById/{id}','FoodTypeController@getById');
        Route::post('/create','FoodTypeController@create');
        Route::post('/update','FoodTypeController@update');
        Route::delete('/delete','FoodTypeController@delete');
    });
    Route::group(['prefix'=>'food'],function(){
        Route::get('/','FoodController@index');
        Route::get('/getById/{id}','FoodController@getById');
        Route::post('/create','FoodController@create');
        Route::post('/update','FoodController@update');
        Route::delete('/delete','FoodController@delete');
    });
    // Route::get('closed', 'DataController@closed');
});

</code>```

Here is my code in JWTMiddleware

```<code><?php

namespace App\Http\Middleware;

use Closure;
use Exception;
use Tymon\JWTAuth\Facades\JWTAuth;
use Tymon\JWTAuth\Http\Middleware\BaseMiddleware;

class JwtMiddleware extends BaseMiddleware
{

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */

    public function handle($request, Closure $next)
    {
        $response = $next($request);
        try {
            $user = JWTAuth::parseToken()->authenticate();
        } catch (Exception $e) {
            if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenInvalidException){
                return response()->json(['status' => 'Token is Invalid']);
            }else if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenExpiredException){
                return response()->json(['status' => 'Token is Expired']);
            }else{
                return response()->json(['status' => 'Authorization Token not found']);
            }
        }
        return $next($request);
    }
}

</code>```

Here is my post from postman

答:
Now I see that when I delete

```<code> $response = $next($request);
</code>```

from JwtMiddleware and then it work well thank you!.

Title: Laravel Controller Function Run Twice

Body:
I'm using laravel to controller my data when I create data it create twice.

Here is code in my food controller

<?php

namespace App\Http\Controllers;

use App\Food;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class FoodController extends Controller
{
    //
    public function index()
    {
        error_log('geting food');
        return Food::all();
    }

    public function create()
    {
        $validator = Validator::make(request()->all(), [
            'food_name' => 'required|string|max:100',
            'food_type_id' => 'required|string|max:100|exists:food_types,id',
            'price' => 'required|numeric|between:0,99.99'
        ]);
        if ($validator->fails()) {
            return response()->json($validator->errors(), 400);
        }
        $food = Food::create(request()->all());

        error_log("Inserting");
        return $food;
    }
    public function getById($id){
        return Food::all()->find($id);
    }
    public function update(){
        $validator = Validator::make(request()->all(), [
            'id'=> 'required|integer',
            'food_name' => 'required|string|max:100',
            'food_type_id' => 'required|string|max:100|exists:food_types,id',
            'price' => 'required|numeric|between:0,99.99'
        ]);
        if ($validator->fails()) {
            return response()->json($validator->errors(), 400);
        }
        $food=Food::where('id',request('id'))->get()[0];
        $food->fill(request()->all());
        $food->save();
        return $food;
    }
}

Here is the result after I request create once. I don't know what wrong of middleware or something else. It seem it do twice every single request.

Here is api my route

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::post('login', 'UserController@authenticate');
Route::get('open', 'DataController@open');
Route::post('register', 'UserController@register');
Route::group(['middleware' => ['jwt.verify']], function () {

    Route::get('user', 'UserController@getAuthenticatedUser');

    Route::group(['prefix'=>'food-type'],function(){
        Route::get('/','FoodTypeController@index');
        Route::get('/getById/{id}','FoodTypeController@getById');
        Route::post('/create','FoodTypeController@create');
        Route::post('/update','FoodTypeController@update');
        Route::delete('/delete','FoodTypeController@delete');
    });
    Route::group(['prefix'=>'food'],function(){
        Route::get('/','FoodController@index');
        Route::get('/getById/{id}','FoodController@getById');
        Route::post('/create','FoodController@create');
        Route::post('/update','FoodController@update');
        Route::delete('/delete','FoodController@delete');
    });
    // Route::get('closed', 'DataController@closed');
});

Here is my code in JWTMiddleware

<?php

namespace App\Http\Middleware;

use Closure;
use Exception;
use Tymon\JWTAuth\Facades\JWTAuth;
use Tymon\JWTAuth\Http\Middleware\BaseMiddleware;

class JwtMiddleware extends BaseMiddleware
{

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */

    public function handle($request, Closure $next)
    {
        $response = $next($request);
        try {
            $user = JWTAuth::parseToken()->authenticate();
        } catch (Exception $e) {
            if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenInvalidException){
                return response()->json(['status' => 'Token is Invalid']);
            }else if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenExpiredException){
                return response()->json(['status' => 'Token is Expired']);
            }else{
                return response()->json(['status' => 'Authorization Token not found']);
            }
        }
        return $next($request);
    }
}

Here is my post from postman

Body:
Now I see that when I delete

 $response = $next($request);

from JwtMiddleware and then it work well thank you!.


来源: stackexchange

问:
mysql syntax ERROR 1064 while creating a trigger
I am creating a trigger for my tables:-
bank
Bank(pin, deposit, withdraw, balance, accno*, sno)
and
balance
Balance(accno*,balance)

I want to update the value of balance in my balance table after insertion in the bank table.
 I am using a MySQL server (wamp64 mysql8.0.18)

```<code>mysql> create trigger update_account
    -> after insert on bank
    -> begin
    -> update balance as a
    -> set a.balance=(case
    -> when new.withdraw=1 then a.balance-new.withdraw
    -> else a.balance+new.withdraw
    -> end)
    -> where a.accno = new.accno;
</code>```

but the above code gives me the following error:-
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'update balance a
set a.balance = (case
when new.withdraw=1 then a.balance - new.' at line 3

答:
```<code>DELIMITER $$
DROP PROCEDURE my_procedure$$
create trigger update_account
after insert
on bank
for each row
begin
update balance as a
set a.balance= a.balance + new.withdraw + new.deposit
where a.accno=new.accno;
END$$
DELIMITER ;
</code>```

My code is now working
thank you all

ContentLicense: CC BY-SA 4.0

Body:
I am creating a trigger for my tables:-
bank
Bank(pin, deposit, withdraw, balance, accno*, sno)
and
balance
Balance(accno*,balance)

I want to update the value of balance in my balance table after insertion in the bank table.
 I am using a MySQL server (wamp64 mysql8.0.18)

mysql> create trigger update_account
    -> after insert on bank
    -> begin
    -> update balance as a
    -> set a.balance=(case
    -> when new.withdraw=1 then a.balance-new.withdraw
    -> else a.balance+new.withdraw
    -> end)
    -> where a.accno = new.accno;

but the above code gives me the following error:-
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'update balance a
set a.balance = (case
when new.withdraw=1 then a.balance - new.' at line 3

Body:
DELIMITER $$
DROP PROCEDURE my_procedure$$
create trigger update_account
after insert
on bank
for each row
begin
update balance as a
set a.balance= a.balance + new.withdraw + new.deposit
where a.accno=new.accno;
END$$
DELIMITER ;

My code is now working
thank you all


问:
Hyperledger Fabric: Exact meaning of "simulation" and "execution"
Hyperledger Fabric is known to employ an <execute-order> structure wherein a transaction is "executed" speculatively and then it is checked for correctness:

https://medium.com/@rahulmahadev/side-effects-due-to-speculative-execution-in-hyperledger-fabric-a0b7cd6ab1ea

Hyperledger Fabric execute-order diagram

In the execution block in the diagram above, what exactly a "simulation" does? How different from a simulation and an execution? Is there a possibility that a transaction is NOT executed if a simulation fails?

Your advice will be most appreciated!

答:
Transaction executions usually means to execute a function and afterwards apply changes to the database according to the transaction.

A simulation means to execute the function without applying the changes to the database, and instead record them.

Recall, most blockchains follow the order-execute model (like Bitcoin, Ethereum) where all nodes execute transactions and apply changes to their database immediately.

In contrast, Hyperledger Fabric executes the transactions on a subset of the peers of the network, and the results of the execution are recorded, cryptographically signed and then distributed to all peers via the ordering service.


问:
Unity error while building , JDK and SDK not found

Please Help,I have installed JDK and SDK for Unity, both manually and with unity hub, but all the time the message occurs while building, that JDK and SDK are invalid or not found.

答:
You need to download Android Studio (SDK) and also Oracle JDK.

If you still can't solve the problem, make sure you download
the following modules -
Android build support, Android SDK & NDK tools and Open JDK


问:
ViewBag.Message not showing ASP.NET MVC c#
I have a view named Index.cshtml and controller named HomeController and I can't seem to show the ViewBag.Message and ViewBag.FileUrl to the view. The code is working I just can't show the ViewBag.message when the file is successfully uploaded.

Here's my code below

Index.cshtml

```<code>@{
ViewBag.Title = "Upload a file to S3 Bucket";
}

<h2>@ViewBag.Title.</h2>
<h3>@ViewBag.Message</h3>
<h3>@ViewBag.FileUrl</h3>

<p>Use this area to browse image and upload to S3 bucket.</p>
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div>
    @Html.TextBox("file", "", new { type = "file" }) <br />
    <input type="submit" value="Upload" />
    @ViewBag.FileUrl
    @ViewBag.Message
</div>
}
</code>```

HomeController.cs

```<code>[HttpGet]
public ActionResult Index()
{
    return View();
}

[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
    var s3Client = new AmazonS3Client(accesskey, secretkey, bucketRegion);
    var result = "";
    var keyName = file.FileName;
    var fileTransferUtility = new TransferUtility(s3Client);

    try
    {
        if (file.ContentLength > 0)
        {
            var filePath = Path.Combine(Server.MapPath("~/App_Data"), Path.GetFileName(file.FileName));
            var fileTransferUtilityRequest = new TransferUtilityUploadRequest
            {
                BucketName = bucketName,
                FilePath = filePath,
                StorageClass = S3StorageClass.StandardInfrequentAccess,
                PartSize = 6291456, // 6 MB.
                Key = keyName,
                CannedACL = S3CannedACL.PublicRead
            };

            fileTransferUtilityRequest.Metadata.Add("param1", "Value1");
            fileTransferUtilityRequest.Metadata.Add("param2", "Value2");
            fileTransferUtility.Upload(fileTransferUtilityRequest);
            fileTransferUtility.Dispose();
        }
        result = string.Format("http://{0}.s3.amazonaws.com/{1}", bucketName, keyName);

        ViewBag.FileUrl = result;
        ViewBag.Message = "File Uploaded Successfully!!";
    }
    catch (AmazonS3Exception amazonS3Exception)
    {
        ViewBag.Message = "Error occurred: " + amazonS3Exception.Message;
    }

    return RedirectToAction("Index");
}
</code>```

答:
You are doing redirect the result so that value becomes null, instead of that use Tempdata in where assign a value and get it where you redirect,

```<code>catch (AmazonS3Exception amazonS3Exception)
{
    Tempdata["Message"]="Error occurred: " + amazonS3Exception.Message;
}
</code>```

and Index action method, try it like below ,

```<code>[HttpGet]
public ActionResult Index()
{
    ViewBag.Message= (string)Tempdata["Message"]
    return View();
}
</code>```

Body:
I have a view named Index.cshtml and controller named HomeController and I can't seem to show the ViewBag.Message and ViewBag.FileUrl to the view. The code is working I just can't show the ViewBag.message when the file is successfully uploaded.

Here's my code below

Index.cshtml

@{
ViewBag.Title = "Upload a file to S3 Bucket";
}

@ViewBag.Title.

@ViewBag.Message

@ViewBag.FileUrl

Use this area to browse image and upload to S3 bucket.

@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{

    @Html.TextBox("file", "", new { type = "file" })

    <input type="submit" value="Upload" />
    @ViewBag.FileUrl
    @ViewBag.Message

}

HomeController.cs

[HttpGet]
public ActionResult Index()
{
    return View();
}

[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
    var s3Client = new AmazonS3Client(accesskey, secretkey, bucketRegion);
    var result = "";
    var keyName = file.FileName;
    var fileTransferUtility = new TransferUtility(s3Client);

    try
    {
        if (file.ContentLength > 0)
        {
            var filePath = Path.Combine(Server.MapPath("~/App_Data"), Path.GetFileName(file.FileName));
            var fileTransferUtilityRequest = new TransferUtilityUploadRequest
            {
                BucketName = bucketName,
                FilePath = filePath,
                StorageClass = S3StorageClass.StandardInfrequentAccess,
                PartSize = 6291456, // 6 MB.
                Key = keyName,
                CannedACL = S3CannedACL.PublicRead
            };

            fileTransferUtilityRequest.Metadata.Add("param1", "Value1");
            fileTransferUtilityRequest.Metadata.Add("param2", "Value2");
            fileTransferUtility.Upload(fileTransferUtilityRequest);
            fileTransferUtility.Dispose();
        }
        result = string.Format("http://{0}.s3.amazonaws.com/{1}", bucketName, keyName);

        ViewBag.FileUrl = result;
        ViewBag.Message = "File Uploaded Successfully!!";
    }
    catch (AmazonS3Exception amazonS3Exception)
    {
        ViewBag.Message = "Error occurred: " + amazonS3Exception.Message;
    }

    return RedirectToAction("Index");
}

Body:
You are doing redirect the result so that value becomes null, instead of that use Tempdata in where assign a value and get it where you redirect,

catch (AmazonS3Exception amazonS3Exception)
{
    Tempdata["Message"]="Error occurred: " + amazonS3Exception.Message;
}

and Index action method, try it like below ,

[HttpGet]
public ActionResult Index()
{
    ViewBag.Message= (string)Tempdata["Message"]
    return View();
}


问:
DATEDIFF Function Issue in DAX
I am trying call another measure from datediff function, but I am getting below error.

Below is what I have done.

My SelectTime Measure definition is as below.

Also I have an Intermediate table called Interval, Though which I will be selecting the TimePeriod by putting it in a slicer.

Can someone please explain me what am I missing here, TIA.

答:
As far as I know, interval in DateDiff must be a constant, and can not be a variable. It's a limitation of DAX language which I hope Microsoft will improve at some point.

For now, you can use a different approach.

```<code>SelectTime = SELECTEDVALUE(Interval[TimePeriod])
</code>```

Then:

```<code>MyDateDiff =
VAR Start_Date = DATE(1984,11,01)
VAR End_Date = DATE(1089, 08, 08)
RETURN
SWITCH(
   [SelectTime],
    "Day", DATEDIFF(Start_Date, End_Date, DAY),
    "Month", DATEDIFF(Start_Date, End_Date, MONTH),
    "Week", DATEDIFF(Start_Date, End_Date, WEEK),
    DATEDIFF(Start_Date, End_Date, YEAR)
    )
</code>```

Title: DATEDIFF Function Issue in DAX

Body:
As far as I know, interval in DateDiff must be a constant, and can not be a variable. It's a limitation of DAX language which I hope Microsoft will improve at some point.

For now, you can use a different approach.

SelectTime = SELECTEDVALUE(Interval[TimePeriod])

Then:

MyDateDiff =
VAR Start_Date = DATE(1984,11,01)
VAR End_Date = DATE(1089, 08, 08)
RETURN
SWITCH(
   [SelectTime],
    "Day", DATEDIFF(Start_Date, End_Date, DAY),
    "Month", DATEDIFF(Start_Date, End_Date, MONTH),
    "Week", DATEDIFF(Start_Date, End_Date, WEEK),
    DATEDIFF(Start_Date, End_Date, YEAR)
    )


问:
Microsoft SysVAD Virtual Audio Device Driver (SYSVAD) cannot work
This driver (https://github.com/Microsoft/Windows-driver-samples/tree/master/audio/sysvad) is provided by Microsoft. And in its README, the last part, it says:

Locate an MP3 or other audio file on the target computer and
  double-click to play it. Then in the Sound dialog box, verify that
  there is activity in the volume level indicator associated with the
  SYSVAD (with APO Extensions) driver.

But in my target computer, the volume level indicator associated with the SYSVAD (with APO Extensions) driver does not change at all. And the target computer does not make any sound.

The same case to the mic, when set default mic to any of the sysvad mic array, the mic volume level will not change at all.

In my understanding, sysvad driver is virtual driver. So it will not really work. But why Microsoft README says: there is activity in the volume level indicator associated with the SYSVAD (with APO Extensions) driver.

答:
I am working on SysVad too and sure it works, for Mic you can test with vlc player
Try to open the virtual mic from VLC and then you will hear sound,  it's a sin wave generated by driver itself</p>


问:
Sorted a javascript array of objects by an object property
Hay, i have an array of objects and i need to sort them (either DESC or ASC) by a certain property of each object.

Here's the data

```<code>obj1 = new Object;
obj1.date = 1307010000;

obj2 = new Object;
obj2.date = 1306923600;

obj3 = new Object;
obj3.date = 1298974800;

obj4 = new Object;
obj4.date = 1306923600;

obj5 = new Object;
obj5.date = 1307096400;

data = [obj1,obj2,obj3,obj4,obj5];
</code>```

Now, i want to order the data array so that the objects are in order by date.

Can someone help me with this?

答:
try this:</p>

```<code>data.sort(function(a,b){
   return a.date - b.date; //to reverse b.date-a.date
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Hay, i have an array of objects and i need to sort them (either DESC or ASC) by a certain property of each object.

Here's the data

obj1 = new Object;
obj1.date = 1307010000;

obj2 = new Object;
obj2.date = 1306923600;

obj3 = new Object;
obj3.date = 1298974800;

obj4 = new Object;
obj4.date = 1306923600;

obj5 = new Object;
obj5.date = 1307096400;

data = [obj1,obj2,obj3,obj4,obj5];

Now, i want to order the data array so that the objects are in order by date.

Can someone help me with this?

Body:
try this:

data.sort(function(a,b){
   return a.date - b.date; //to reverse b.date-a.date
});


问:
How to use custom metrics in Keras model while using Grid Search CV?
I want to use R2 (Coefficient of determination) as metrics in my Keras model. For that, I have already defined a function (coeff_determination). This function as a metric works well without Grid Search CV but with grid search cv it gives an error like "The model is not configured to compute the accuracy. You should pass metrics=["accuracy"] to the model.compile() method". The code is given below.

```<code>def create_model():

    #CNN Architecture - Model 7
    model = Sequential()
    model.add(Convolution1D(filters=10, kernel_size=12, activation="relu", kernel_initializer="glorot_uniform", input_shape=(X_train.shape[1],1)))
    model.add(MaxPooling1D(pool_size=4, strides=2))
    model.add(BatchNormalization())
    model.add(Convolution1D(filters=16, kernel_size=12, activation='relu', kernel_initializer="glorot_uniform"))
    model.add(MaxPooling1D(pool_size=3, strides=2))
    model.add(BatchNormalization())
    model.add(Convolution1D(filters=22, kernel_size=12, activation='relu', kernel_initializer="glorot_uniform"))
    model.add(MaxPooling1D(pool_size=3, strides=2))
    model.add(BatchNormalization())
    model.add(Convolution1D(filters=28, kernel_size=12, activation='relu', kernel_initializer="glorot_uniform"))
    model.add(MaxPooling1D(pool_size=4, strides=2))
    model.add(BatchNormalization())
    model.add(Convolution1D(filters=34, kernel_size=12, activation='relu', kernel_initializer="glorot_uniform"))
    model.add(MaxPooling1D(pool_size=3, strides=2))
    model.add(BatchNormalization())
    model.add(Convolution1D(filters=40, kernel_size=12, activation='relu', kernel_initializer="glorot_uniform"))
    model.add(MaxPooling1D(pool_size=3, strides=2))
    model.add(BatchNormalization())
    model.add(Flatten())
    #model.add(Dropout(0.35))
    model.add(Dense(130, activation='relu'))
    #model.add(Dropout(0.35))
    model.add(Dense(130, activation='relu'))
    model.add(Dense(1, activation='linear'))
    history = History()
    model.compile(loss='mean_squared_error',optimizer= Adam(lr=0.0001), metrics=[coeff_determination])
    #model.fit(X_train,y_train, validation_data=(X_test,y_test), epochs=400, batch_size=30, callbacks=[history])
    return model

def coeff_determination(y_true, y_pred):
    SS_res = K.sum(K.square(y_true - y_pred))
    SS_tot = K.sum(K.square(y_true - K.mean(y_true)))
    return (1 - SS_res / (SS_tot + K.epsilon()))
# to reprduce the same results next time
seed = 7
np.random.seed(seed)
# Creating Keras model with Scikit learn wrap-up
model = KerasClassifier(build_fn=create_model, verbose=0)
# define the grid search parameters
batch_size = [20,30,40,80]
epochs = [100,200,300,400]
# Using make scorer to convert metric r_2 to a scorer
my_scorer = make_scorer(r2_score, greater_is_better=True)

# passing dictionaries of parameters to the GridSearchCV
param_grid = dict(batch_size=batch_size, epochs=epochs)
grid = GridSearchCV(estimator=model, scoring=my_scorer, param_grid=param_grid, n_jobs=1, cv=3)
grid_result = grid.fit(X_train, y_train)
# summarizing the results
print("Best: %f using %s" % (grid_result.best_score_, grid_result.best_params_))
means = grid_result.cv_results_['mean_test_score']
stds = grid_result.cv_results_['std_test_score']
params = grid_result.cv_results_['params']
for mean, stdev, param in zip(means, stds, params):
    print("%f (%f) with: %r" % (mean, stdev, param))
</code>```

答:
I think you need to feed your custom scoring function as the input for scoring param to GridSearchCV otherwise it will look out for the default estimator's scoring method which is accuracy.

From Documentation:

scoring: str, callable, list/tuple or dict, default=None
  A single str (see The scoring parameter: defining model evaluation rules) or a callable (see Defining your scoring strategy from metric functions) to evaluate the predictions on the test set.

For evaluating multiple metrics, either give a list of (unique) strings or a dict with names as keys and callables as values.

NOTE that when using custom scorers, each scorer should return a single value. Metric functions returning a list/array of values can be wrapped into multiple scorers that return one value each.

See Specifying multiple metrics for evaluation for an example.

If None, the estimator’s score method is used.

Body:
I want to use R2 (Coefficient of determination) as metrics in my Keras model. For that, I have already defined a function (coeff_determination). This function as a metric works well without Grid Search CV but with grid search cv it gives an error like "The model is not configured to compute the accuracy. You should pass metrics=["accuracy"] to the model.compile() method". The code is given below.

def create_model():

    #CNN Architecture - Model 7
    model = Sequential()
    model.add(Convolution1D(filters=10, kernel_size=12, activation="relu", kernel_initializer="glorot_uniform", input_shape=(X_train.shape[1],1)))
    model.add(MaxPooling1D(pool_size=4, strides=2))
    model.add(BatchNormalization())
    model.add(Convolution1D(filters=16, kernel_size=12, activation='relu', kernel_initializer="glorot_uniform"))
    model.add(MaxPooling1D(pool_size=3, strides=2))
    model.add(BatchNormalization())
    model.add(Convolution1D(filters=22, kernel_size=12, activation='relu', kernel_initializer="glorot_uniform"))
    model.add(MaxPooling1D(pool_size=3, strides=2))
    model.add(BatchNormalization())
    model.add(Convolution1D(filters=28, kernel_size=12, activation='relu', kernel_initializer="glorot_uniform"))
    model.add(MaxPooling1D(pool_size=4, strides=2))
    model.add(BatchNormalization())
    model.add(Convolution1D(filters=34, kernel_size=12, activation='relu', kernel_initializer="glorot_uniform"))
    model.add(MaxPooling1D(pool_size=3, strides=2))
    model.add(BatchNormalization())
    model.add(Convolution1D(filters=40, kernel_size=12, activation='relu', kernel_initializer="glorot_uniform"))
    model.add(MaxPooling1D(pool_size=3, strides=2))
    model.add(BatchNormalization())
    model.add(Flatten())
    #model.add(Dropout(0.35))
    model.add(Dense(130, activation='relu'))
    #model.add(Dropout(0.35))
    model.add(Dense(130, activation='relu'))
    model.add(Dense(1, activation='linear'))
    history = History()
    model.compile(loss='mean_squared_error',optimizer= Adam(lr=0.0001), metrics=[coeff_determination])
    #model.fit(X_train,y_train, validation_data=(X_test,y_test), epochs=400, batch_size=30, callbacks=[history])
    return model

def coeff_determination(y_true, y_pred):
    SS_res = K.sum(K.square(y_true - y_pred))
    SS_tot = K.sum(K.square(y_true - K.mean(y_true)))
    return (1 - SS_res / (SS_tot + K.epsilon()))
# to reprduce the same results next time
seed = 7
np.random.seed(seed)
# Creating Keras model with Scikit learn wrap-up
model = KerasClassifier(build_fn=create_model, verbose=0)
# define the grid search parameters
batch_size = [20,30,40,80]
epochs = [100,200,300,400]
# Using make scorer to convert metric r_2 to a scorer
my_scorer = make_scorer(r2_score, greater_is_better=True)

# passing dictionaries of parameters to the GridSearchCV
param_grid = dict(batch_size=batch_size, epochs=epochs)
grid = GridSearchCV(estimator=model, scoring=my_scorer, param_grid=param_grid, n_jobs=1, cv=3)
grid_result = grid.fit(X_train, y_train)
# summarizing the results
print("Best: %f using %s" % (grid_result.best_score_, grid_result.best_params_))
means = grid_result.cv_results_['mean_test_score']
stds = grid_result.cv_results_['std_test_score']
params = grid_result.cv_results_['params']
for mean, stdev, param in zip(means, stds, params):
    print("%f (%f) with: %r" % (mean, stdev, param))


问:
Change Extension of Library?
Is there a way to change a shared library's extension, only on windows from ".dll" to something else?

```<code>add_library(mylib SHARED <src>)
</code>```

So instead of creating a mylib.dll file i need it to be something else like mylib.dla.

答:
set(CMAKE_STATIC_LIBRARY_SUFFIX ".dla")

will change all suffixes but will work for you as well

Title: Change Extension of Library?

Body:
Is there a way to change a shared library's extension, only on windows from ".dll" to something else?

add_library(mylib SHARED <src>)

So instead of creating a mylib.dll file i need it to be something else like mylib.dla.


问:
Performance issue in Xpath grammar file using antlr
I am running into a performance issue while creating the grammar for Xpath.

The whole grammar was working fine till we added support for the xpaths like:

```<code>((div)[1]//span)[1]
</code>```

or

```<code>((//div)[1]/div)[last()]
</code>```

After adding support for this in the grammar file, the above xpaths started working fine but other xpaths started giving performance issues.

Like this one :

```<code>//label[normalize-space(.)='Phone']/parent::lightning-input/parent::slot/parent::slot/parent::span/parent::div/parent::force-record-layout-item/parent::slot/parent::force-record-layout-row/parent::slot/parent::div/parent::div/parent::div/parent::force-record-layout-section/parent::slot/parent::force-record-layout-block/parent::forcegenerated-detailpanel_contact___012b0000000jhhvia4___full___view___recordlayout2/parent::records-lwc-record-layout/parent::slot/parent::records-record-layout-event-broker/parent::div/parent::div/following-sibling::force-form-footer//button
</code>```

which started taking 30 seconds in parsing (it took 170ms earlier).

These were the lines of code added/modified in the attached grammar file which started giving performance issue:

```<code>union
 : expressions+=pathExpression (WS? operator='|' WS? expressions+=pathExpression)*
 ;

pathExpression
 : expressionAtom
 | expressionAtom nodeSet
 ;

expressionAtom
 : functionCall
 | nodeSet
 | literal
 | parenthesis
 ;
</code>```

Earlier it was:

```<code>union
 : expressions+=expressionAtom (WS? operator='|' WS? expressions+=expressionAtom)*
 ;

expressionAtom
 : functionCall
 | nodeSet
 | literal
 | parenthesis
 ;
</code>```

and used to give no performance issues.

On debugging the XpathParser I figured out that it is because the DFAState has** requiresFullContext as true **in this case.

The documentation states that the true value of this “Indicates that this state was created during SLL prediction that discovered a conflict between the configurations in the state.”

Can you help me resolve this issue and what is causing it to search the full context which takes time?

答:
I don't know Antlr well, but how about replacing

```<code>pathExpression
 : expressionAtom
 | expressionAtom nodeSet
 ;
</code>```

with

```<code>pathExpression
 : expressionAtom nodeSet?
 ;
</code>```

Body:
I am running into a performance issue while creating the grammar for Xpath.

The whole grammar was working fine till we added support for the xpaths like:

((div)[1]//span)[1]

or

((//div)[1]/div)[last()]

After adding support for this in the grammar file, the above xpaths started working fine but other xpaths started giving performance issues.

Like this one :

//label[normalize-space(.)='Phone']/parent::lightning-input/parent::slot/parent::slot/parent::span/parent::div/parent::force-record-layout-item/parent::slot/parent::force-record-layout-row/parent::slot/parent::div/parent::div/parent::div/parent::force-record-layout-section/parent::slot/parent::force-record-layout-block/parent::forcegenerated-detailpanel_contact___012b0000000jhhvia4___full___view___recordlayout2/parent::records-lwc-record-layout/parent::slot/parent::records-record-layout-event-broker/parent::div/parent::div/following-sibling::force-form-footer//button

which started taking 30 seconds in parsing (it took 170ms earlier).

These were the lines of code added/modified in the attached grammar file which started giving performance issue:

union
 : expressions+=pathExpression (WS? operator='|' WS? expressions+=pathExpression)*
 ;

pathExpression
 : expressionAtom
 | expressionAtom nodeSet
 ;

expressionAtom
 : functionCall
 | nodeSet
 | literal
 | parenthesis
 ;

Earlier it was:

union
 : expressions+=expressionAtom (WS? operator='|' WS? expressions+=expressionAtom)*
 ;

expressionAtom
 : functionCall
 | nodeSet
 | literal
 | parenthesis
 ;

and used to give no performance issues.

On debugging the XpathParser I figured out that it is because the DFAState has** requiresFullContext as true **in this case.

The documentation states that the true value of this “Indicates that this state was created during SLL prediction that discovered a conflict between the configurations in the state.”

Can you help me resolve this issue and what is causing it to search the full context which takes time?

Body:
I don't know Antlr well, but how about replacing

pathExpression
 : expressionAtom
 | expressionAtom nodeSet
 ;

with

pathExpression
 : expressionAtom nodeSet?
 ;


问:
Can't change nav-link color in bootstrap 4
```<code><nav id="section_navbar" class="navbar navbar-expand-lg fixed-top">
        <div class="mx-auto my-2 order-0 order-md-1 position-relative">
            <div id="top_logo" class="container-fluid">
                <span>VirtualQR</span>
            </div>
        </div>
        <div class="navbar-collapse collapse w-100 dual-collapse2 order-2 order-md-1">
            <ul class="navbar-nav ml-auto">
                <li class="nav-item">
                    <a class="nav-link" href="#section_navbar">Home</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#section_howdoesitwork">How does it work?</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#section_pricing">Pricings</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#section_contact">Contacts</a>
                </li>
            </ul>
</code>```

I can't get the nav-link to change color. I've tried other posts solutions but couldn't get it to work anyways.
I don't know if it has something to do with my code.

答:
Put this code in your external CSS file

```<code>.nav-link {
  color: red;
}
</code>```

OR

Put it as internal css like below

```<code><head>
    <style>
           .nav-link {
              color: red;
            }

    </style>
</head>
</code>```

OR

put it as inline CSS like below

```<code><a class="nav-link" href="#section_navbar" style="color: red;">Home</a>
</code>```

Body:
                VirtualQR

                    Home

                    How does it work?

                    Pricings

                    Contacts

I can't get the nav-link to change color. I've tried other posts solutions but couldn't get it to work anyways.
I don't know if it has something to do with my code.

Body:
Put this code in your external CSS file

.nav-link {
  color: red;
}

OR

Put it as internal css like below

<head>
    <style>
           .nav-link {
              color: red;
            }

    </style>
</head>

OR

put it as inline CSS like below

<a class="nav-link" href="#section_navbar" style="color: red;">Home</a>


问:
Error in Google BigQuery <EOF>
I am new to Google BigQuery. I need help with the query error:

"Encountered " "WITH" "with "" at line 1, column 1. Was expecting:
  EOF"

```<code>with
  t1 as
  (
    select
    date(USEC_TO_TIMESTAMP(event_dim.timestamp_micros)) date, event_dim.name
    from
    [myfoody-1313:it_rawfish_myfoody_ANDROID.app_events_20160727]
    where
    event_dim.name='pv_detail' and event_dim.params.key='item_id' and
    event_dim.params.value.string_value='31'
  )
  select
  date(d) as day, count(event_dim.name)
from
  generate_series(current_date - interval '6 day', current_date, '1 day') d
  left join t1 on t1.date = d
group by day
order by day;
</code>```

答:
Your query syntax is wrong so i fix that and try #standardsql while writing any query, in this way you don't need to do any setting changes. Try below code and add in ur whole query.

standardSQL

with
  t1 as
  (
    select
    date((current_timestamp())) date,
    'xyz' name
--     from

--     where
--     event_dim.name='pv_detail' and event_dim.params.key='item_id' and
--     event_dim.params.value.string_value='31'
  )

select
  cast(d as date) day,
  count(name)
from  UNNEST(GENERATE_DATE_ARRAY(date_sub(CURRENT_DATE(), INTERVAL 6 day), date_sub(current_date(), INTERVAL 1 day))) d
  left join t1 on t1.date = cast(d as date)
group by 1
order by 1;

Title: Error in Google BigQuery <EOF>

Body:
I am new to Google BigQuery. I need help with the query error:

"Encountered " "WITH" "with "" at line 1, column 1. Was expecting:
  EOF"

with
  t1 as
  (
    select
    date(USEC_TO_TIMESTAMP(event_dim.timestamp_micros)) date, event_dim.name
    from
    [myfoody-1313:it_rawfish_myfoody_ANDROID.app_events_20160727]
    where
    event_dim.name='pv_detail' and event_dim.params.key='item_id' and
    event_dim.params.value.string_value='31'
  )
  select
  date(d) as day, count(event_dim.name)
from
  generate_series(current_date - interval '6 day', current_date, '1 day') d
  left join t1 on t1.date = d
group by day
order by day;


问:
SQLiteBlobTooBigException - Huawei devices, Android 9 and 10
I get android.database.sqlite.SQLiteBlobTooBigException only for Huawei family devices, Android 9 and 10

Crash by devices

In onUpgrade method I want to add new colum to table

```<code> @Override
 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
...
        case 43:
               addColumn(db, TABLE_LESSONS, _SPEED_GAME_EASY_FINISHED, " INTEGER DEFAULT 0");
               addColumn(db, TABLE_LESSONS, _SPEED_GAME_HARD_FINISHED, " INTEGER DEFAULT 0");
               addColumn(db, TABLE_LESSONS, _MEMORY_GAME_EASY_FINISHED, " INTEGER DEFAULT 0");
...
}
</code>```

```<code>    private void addColumn(SQLiteDatabase db, String table, String column, String columnType) {
        boolean isColumnExist = false;
        AbstractWindowedCursor cursor = null;
        String selectQuery = "SELECT * FROM " + table + " LIMIT 0,1";

        try {
            cursor = getSqlCursorWithIncreasedWindowSize(db.rawQuery(selectQuery, null));

            if (cursor.moveToFirst()) {
                isColumnExist = cursor.getColumnIndex(column) != -1;
            }

            if (!isColumnExist) {
                db.execSQL("ALTER TABLE " + table + " ADD COLUMN " + column + columnType);
            }

        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }
</code>```

I tried to increase cursor window size, but it did not help

```<code>fun getSqlCursorWithIncreasedWindowSize(cursor: Cursor): AbstractWindowedCursor {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
        val cw = CursorWindow(null, 10000L)
        (cursor as AbstractWindowedCursor).window = cw
    }
    return cursor as AbstractWindowedCursor
}
</code>```

TABLE_LESSONS contains 10 columns of integers, longs and short text

Problem occurs in cursor.moveToFirst()

```<code>java.lang.RuntimeException:
  at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:3430)
  at android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:3614)
  at android.app.servertransaction.LaunchActivityItem.execute (LaunchActivityItem.java:86)
  at android.app.servertransaction.TransactionExecutor.executeCallbacks (TransactionExecutor.java:108)
  at android.app.servertransaction.TransactionExecutor.execute (TransactionExecutor.java:68)
  at android.app.ActivityThread$H.handleMessage (ActivityThread.java:2199)
  at android.os.Handler.dispatchMessage (Handler.java:112)
  at android.os.Looper.loop (Looper.java:216)
  at android.app.ActivityThread.main (ActivityThread.java:7625)
  at java.lang.reflect.Method.invoke (Method.java)
  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:524)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:987)
Caused by: android.database.sqlite.SQLiteBlobTooBigException:
  at android.database.sqlite.SQLiteConnection.nativeExecuteForCursorWindow (SQLiteConnection.java)
  at android.database.sqlite.SQLiteConnection.executeForCursorWindow (SQLiteConnection.java:904)
  at android.database.sqlite.SQLiteSession.executeForCursorWindow (SQLiteSession.java:851)
  at android.database.sqlite.SQLiteQuery.fillWindow (SQLiteQuery.java:62)
  at android.database.sqlite.SQLiteCursor.fillWindow (SQLiteCursor.java:149)
  at android.database.sqlite.SQLiteCursor.getCount (SQLiteCursor.java:137)
  at android.database.AbstractCursor.moveToPosition (AbstractCursor.java:220)
  at android.database.AbstractCursor.moveToFirst (AbstractCursor.java:259)
  at com.kkk.english_words.data.local.db.DatabaseHelper.addColumn (DatabaseHelper.java:31)
  at com.kkk.english_words.data.local.db.DatabaseHelper.onUpgrade (DatabaseHelper.java:161)
  at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked (SQLiteOpenHelper.java:417)
  at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase (SQLiteOpenHelper.java:313)
  at com.kkk.english_words.data.local.db.DatabaseHelper.getDb (DatabaseHelper.java:2)
  at com.kkk.english_words.data.local.db.DatabaseHelper.getActivityTimeDbHelper (DatabaseHelper.java:2)
  at com.kkk.english_words.data.local.db.DatabaseHelper.getActivityTimeDbHelper (DatabaseHelper.java:1)
  at com.kkk.english_words.ui.main.MainActivity.onCreate (MainActivity.java:187)
  at android.app.Activity.performCreate (Activity.java:7458)
  at android.app.Activity.performCreate (Activity.java:7448)
  at android.app.Instrumentation.callActivityOnCreate (Instrumentation.java:1286)
  at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:3409)
  at android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:3614)
  at android.app.servertransaction.LaunchActivityItem.execute (LaunchActivityItem.java:86)
  at android.app.servertransaction.TransactionExecutor.executeCallbacks (TransactionExecutor.java:108)
  at android.app.servertransaction.TransactionExecutor.execute (TransactionExecutor.java:68)
  at android.app.ActivityThread$H.handleMessage (ActivityThread.java:2199)
  at android.os.Handler.dispatchMessage (Handler.java:112)
  at android.os.Looper.loop (Looper.java:216)
  at android.app.ActivityThread.main (ActivityThread.java:7625)
  at java.lang.reflect.Method.invoke (Method.java)
  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:524)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:987)
</code>```

Do you have any ideas on how to fix it?

Regards

答:
The crash doesn't happen when creating the column, it happens when fetching data, which is too big to fit in a Cursor.

If you want to check if a column exists, I suggest querying sqlite_master table instead (https://www.sqlite.org/faq.html#q7).

As a rule of thumb I don't suggest keeping data in the megabytes in a SQLite single record in Android. If you have no choice than to store this data locally I would suggest you write this data to a file and store its path in the database instead.

Body:
I get android.database.sqlite.SQLiteBlobTooBigException only for Huawei family devices, Android 9 and 10

Crash by devices

In onUpgrade method I want to add new colum to table

 @Override
 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
...
        case 43:
               addColumn(db, TABLE_LESSONS, _SPEED_GAME_EASY_FINISHED, " INTEGER DEFAULT 0");
               addColumn(db, TABLE_LESSONS, _SPEED_GAME_HARD_FINISHED, " INTEGER DEFAULT 0");
               addColumn(db, TABLE_LESSONS, _MEMORY_GAME_EASY_FINISHED, " INTEGER DEFAULT 0");
...
}

    private void addColumn(SQLiteDatabase db, String table, String column, String columnType) {
        boolean isColumnExist = false;
        AbstractWindowedCursor cursor = null;
        String selectQuery = "SELECT * FROM " + table + " LIMIT 0,1";

        try {
            cursor = getSqlCursorWithIncreasedWindowSize(db.rawQuery(selectQuery, null));

            if (cursor.moveToFirst()) {
                isColumnExist = cursor.getColumnIndex(column) != -1;
            }

            if (!isColumnExist) {
                db.execSQL("ALTER TABLE " + table + " ADD COLUMN " + column + columnType);
            }

        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }

I tried to increase cursor window size, but it did not help

fun getSqlCursorWithIncreasedWindowSize(cursor: Cursor): AbstractWindowedCursor {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
        val cw = CursorWindow(null, 10000L)
        (cursor as AbstractWindowedCursor).window = cw
    }
    return cursor as AbstractWindowedCursor
}

TABLE_LESSONS contains 10 columns of integers, longs and short text

Problem occurs in cursor.moveToFirst()

java.lang.RuntimeException:
  at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:3430)
  at android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:3614)
  at android.app.servertransaction.LaunchActivityItem.execute (LaunchActivityItem.java:86)
  at android.app.servertransaction.TransactionExecutor.executeCallbacks (TransactionExecutor.java:108)
  at android.app.servertransaction.TransactionExecutor.execute (TransactionExecutor.java:68)
  at android.app.ActivityThread$H.handleMessage (ActivityThread.java:2199)
  at android.os.Handler.dispatchMessage (Handler.java:112)
  at android.os.Looper.loop (Looper.java:216)
  at android.app.ActivityThread.main (ActivityThread.java:7625)
  at java.lang.reflect.Method.invoke (Method.java)
  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:524)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:987)
Caused by: android.database.sqlite.SQLiteBlobTooBigException:
  at android.database.sqlite.SQLiteConnection.nativeExecuteForCursorWindow (SQLiteConnection.java)
  at android.database.sqlite.SQLiteConnection.executeForCursorWindow (SQLiteConnection.java:904)
  at android.database.sqlite.SQLiteSession.executeForCursorWindow (SQLiteSession.java:851)
  at android.database.sqlite.SQLiteQuery.fillWindow (SQLiteQuery.java:62)
  at android.database.sqlite.SQLiteCursor.fillWindow (SQLiteCursor.java:149)
  at android.database.sqlite.SQLiteCursor.getCount (SQLiteCursor.java:137)
  at android.database.AbstractCursor.moveToPosition (AbstractCursor.java:220)
  at android.database.AbstractCursor.moveToFirst (AbstractCursor.java:259)
  at com.kkk.english_words.data.local.db.DatabaseHelper.addColumn (DatabaseHelper.java:31)
  at com.kkk.english_words.data.local.db.DatabaseHelper.onUpgrade (DatabaseHelper.java:161)
  at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked (SQLiteOpenHelper.java:417)
  at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase (SQLiteOpenHelper.java:313)
  at com.kkk.english_words.data.local.db.DatabaseHelper.getDb (DatabaseHelper.java:2)
  at com.kkk.english_words.data.local.db.DatabaseHelper.getActivityTimeDbHelper (DatabaseHelper.java:2)
  at com.kkk.english_words.data.local.db.DatabaseHelper.getActivityTimeDbHelper (DatabaseHelper.java:1)
  at com.kkk.english_words.ui.main.MainActivity.onCreate (MainActivity.java:187)
  at android.app.Activity.performCreate (Activity.java:7458)
  at android.app.Activity.performCreate (Activity.java:7448)
  at android.app.Instrumentation.callActivityOnCreate (Instrumentation.java:1286)
  at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:3409)
  at android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:3614)
  at android.app.servertransaction.LaunchActivityItem.execute (LaunchActivityItem.java:86)
  at android.app.servertransaction.TransactionExecutor.executeCallbacks (TransactionExecutor.java:108)
  at android.app.servertransaction.TransactionExecutor.execute (TransactionExecutor.java:68)
  at android.app.ActivityThread$H.handleMessage (ActivityThread.java:2199)
  at android.os.Handler.dispatchMessage (Handler.java:112)
  at android.os.Looper.loop (Looper.java:216)
  at android.app.ActivityThread.main (ActivityThread.java:7625)
  at java.lang.reflect.Method.invoke (Method.java)
  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:524)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:987)

Do you have any ideas on how to fix it?

Regards


问:
How to remove first 10 characters from a string?
How to ignore the first 10 characters of a string?

Input:

```<code>str = "hello world!";
</code>```

Output:

```<code>d!
</code>```

答:
Starting from C# 8, you simply can use Range Operator. It's the more efficient and better way to handle such cases.</p>

```<code>string AnString = "Hello World!";
AnString = AnString[10..];
</code>```

Body:
How to ignore the first 10 characters of a string?

Input:

str = "hello world!";

Output:

d!

Body:
Starting from C# 8, you simply can use Range Operator. It's the more efficient and better way to handle such cases.

string AnString = "Hello World!";
AnString = AnString[10..];


问:
Update documents in a collection if one of the document field value exists in array
I have a collection1 with collection1Column and another column presentInArray1,

```<code>--------------------------------------------
| collection1Column | presentInArray1      |
--------------------------------------------
| A                 | null                 |
| B                 | null                 |
| C                 | null                 |
| D                 | null                 |
| E                 | null                 |
--------------------------------------------
</code>```

I have an array1 like this:

```<code>let array1 = ['A', 'C', 'D'];
</code>```

Now I need to update collection1's column presentInArray1 only if an exact match of collection1Column is found in array1. In the example given - the matches are A, C & D.

One possible javascript solution I have thought is the following:

Get all the values from both the collection & array.

Once the values are available, take up one by one values from collection1's collection1Column  and iterate on array1 to find a match.

Once the match is found, will update the presentInArray1 with true

In this scenario - How do I update documents in the collection collection1 if one of the document field collection1Column value exists in array1?

Also, here is the code I have tried so far:

```<code>collection1.update({
    'collection1Column': {
      $in: array1
    }
  }, {
    $set: {
      'presentInArray1': true
    }
  }, {
    multi: true
  },
  function(err, result) {
    if (err) throw err;
  });
</code>```

This also seems to be not working. I'm not sure why:

```<code>{"result":{"n":217,"nModified":0,"opTime":{"ts":"6833283007906840577","t":13},"electionId":"7fffffff000000000000000d","ok":1,"$clusterTime":{"clusterTime":"6833283007906840577","signature":{"hash":"W1KNoy0a9d2iTU3OiIa2jlc4y00=","keyId":"6803936209337843714"}},"operationTime":"6833283007906840577"},"connection":{"id":5,"host":"cluster0-shard-00-01-foobar.mongodb.net","port":27017},"modifiedCount":0,"upsertedId":null,"upsertedCount":0,"matchedCount":217,"n":217,"nModified":0,"opTime":{"ts":"6833283007906840577","t":13},"electionId":"7fffffff000000000000000d","ok":1,"$clusterTime":{"clusterTime":"6833283007906840577","signature":{"hash":"W1KNoy0a9d2iTU3OiIa2jlc4y00=","keyId":"6803936209337843714"}},"operationTime":"6833283007906840577"}
</code>```

This looks very expensive in terms of memory and performance to me.

Please suggest!

In simple words, how to perform V Lookup in MongoDB?

MongoDB server version: 4.2.6

答:
```<code>collection1.update({
    'array1': $collection1Column
  }, {
    $set: {
      'presentInArray1': true
    }
  }, {
    multi: true
  },
  function(err, result) {
    if (err) throw err;
  });
</code>```

Assuming collection1Column is not array type

If the field holds an array, then the $in operator selects the documents whose field holds an array that contains at least one element that matches a value in the specified array (e.g. , , etc.)

For more Details: https://docs.mongodb.com/manual/reference/operator/query/in/

Body:
I have a collection1 with collection1Column and another column presentInArray1,

--------------------------------------------
| collection1Column | presentInArray1      |
--------------------------------------------
| A                 | null                 |
| B                 | null                 |
| C                 | null                 |
| D                 | null                 |
| E                 | null                 |
--------------------------------------------

I have an array1 like this:

let array1 = ['A', 'C', 'D'];

Now I need to update collection1's column presentInArray1 only if an exact match of collection1Column is found in array1. In the example given - the matches are A, C & D.

One possible javascript solution I have thought is the following:

Get all the values from both the collection & array.

Once the values are available, take up one by one values from collection1's collection1Column  and iterate on array1 to find a match.

Once the match is found, will update the presentInArray1 with true

In this scenario - How do I update documents in the collection collection1 if one of the document field collection1Column value exists in array1?

Also, here is the code I have tried so far:

collection1.update({
    'collection1Column': {
      $in: array1
    }
  }, {
    $set: {
      'presentInArray1': true
    }
  }, {
    multi: true
  },
  function(err, result) {
    if (err) throw err;
  });

This also seems to be not working. I'm not sure why:

{"result":{"n":217,"nModified":0,"opTime":{"ts":"6833283007906840577","t":13},"electionId":"7fffffff000000000000000d","ok":1,"$clusterTime":{"clusterTime":"6833283007906840577","signature":{"hash":"W1KNoy0a9d2iTU3OiIa2jlc4y00=","keyId":"6803936209337843714"}},"operationTime":"6833283007906840577"},"connection":{"id":5,"host":"cluster0-shard-00-01-foobar.mongodb.net","port":27017},"modifiedCount":0,"upsertedId":null,"upsertedCount":0,"matchedCount":217,"n":217,"nModified":0,"opTime":{"ts":"6833283007906840577","t":13},"electionId":"7fffffff000000000000000d","ok":1,"$clusterTime":{"clusterTime":"6833283007906840577","signature":{"hash":"W1KNoy0a9d2iTU3OiIa2jlc4y00=","keyId":"6803936209337843714"}},"operationTime":"6833283007906840577"}

This looks very expensive in terms of memory and performance to me.

Please suggest!

In simple words, how to perform V Lookup in MongoDB?

MongoDB server version: 4.2.6

Body:
collection1.update({
    'array1': $collection1Column
  }, {
    $set: {
      'presentInArray1': true
    }
  }, {
    multi: true
  },
  function(err, result) {
    if (err) throw err;
  });

Assuming collection1Column is not array type

If the field holds an array, then the $in operator selects the documents whose field holds an array that contains at least one element that matches a value in the specified array (e.g. , , etc.)

For more Details: https://docs.mongodb.com/manual/reference/operator/query/in/


问:
Need to convert a date 09/01/2009 to a CHAR TYPE FORMAT
I need to convert a date 09/01/2009 to a CHAR TYPE FORMAT. The result should have 6 digits.

I knew the TO_CHAR function does it,but its not working for me.

The Date is given as 03/06/08

```<code>SELECT TO_CHAR(030608, 'DD MONTH,YYYY')
 FROM dual;
</code>```

This gives errors-syntax mainly.

It is Oracle database and I have to get the STRING. For example a number like -'200901'

答:
```<code>to_char(sysdate, 'yyyymm'); would return '201106'
</code>```

Oracle's default format for DATE is "DD-MON-YY".  To convert a particular date, you could write

```<code>to_char('02-Jun-11', 'yyyymm'); should return '201106'
</code>```

but better:

```<code>to_char(to_date('09/01/2009', 'dd/mm/yyyy'), 'yyyymm'); should return '200901'
</code>```

See http://infolab.stanford.edu/~ullman/fcdb/oracle/or-time.html

Body:
I need to convert a date 09/01/2009 to a CHAR TYPE FORMAT. The result should have 6 digits.

I knew the TO_CHAR function does it,but its not working for me.

The Date is given as 03/06/08

SELECT TO_CHAR(030608, 'DD MONTH,YYYY')
 FROM dual;

This gives errors-syntax mainly.

It is Oracle database and I have to get the STRING. For example a number like -'200901'

Body:
to_char(sysdate, 'yyyymm'); would return '201106'

Oracle's default format for DATE is "DD-MON-YY".  To convert a particular date, you could write

to_char('02-Jun-11', 'yyyymm'); should return '201106'

but better:

to_char(to_date('09/01/2009', 'dd/mm/yyyy'), 'yyyymm'); should return '200901'

See http://infolab.stanford.edu/~ullman/fcdb/oracle/or-time.html


问:
Retrieving data with foreign keys laravel react
I have two table in mysql one called category with id and name (e.g 1 Dress)

```<code>public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->timestamps();
        });
    }
</code>```

Second table called clothes with foreign key category_id (e.g 1, Black Dress, very cool,10.99,/images.img1,10,1)

```<code>public function up()
    {
        Schema::create('clothes', function (Blueprint $table) {
         $table->increment('id');
        $table->string('item');
        $table->string('description');
        $table->double('price');
        $table->string('img');
        $table->integer('stock');
        $table->integer('category_id');

        });
        Schema::table('clothes', function($table) {
            $table->foreign('category_id')->references('id')->on('categories');
        });
    }
</code>```

So what I am trying is with react fetch information with name category.

```<code>componentDidMount(){
        axios.get('product')
        .then(response => {
          this.setState({ products: response.data });
        })
        .catch(function (error) {
          console.log(error);
        })

render(){
    return (
        <div className="container">
        <h5>Products</h5>
        <br />

<div className="row justify-content-center">
             {this.state.products.map((data,mykey)=>
          <div  className="card"  key={mykey}>
             <img className="card-img-top" src={data.img}></img>
             <div className="card-body">
             <h4 className="card-title"><b>{data.item}</b></h4>
             <p className="card-text">{data.description}</p>
             <ul className="list-group list-group-flush">
    <li className="list-group-item"><b>Price: {data.price}$</b></li>
    <li className="list-group-item"><p>{data.category_id} <Button>Yess</Button></p></li>
  </ul>

    </div>

</div>

            )}
           </div>
        </div>

    )
  }
</code>```

In web.php

```<code>Route::get('product', function(){ return App\Clothes::all(); });
</code>```

In this way I am getting just the number of category but I want to get the name of category.

I would appreciate any type of idea or help to get the name of category not just id.

UPDATE::
Clothes.php

```<code>class Clothes extends Model
{
    //
    protected $fillable = [
        'id', 'item','description','price','img','stock', 'category_id'
    ];

}
</code>```

Category.php

```<code>class Category extends Model
{
    //
    protected $fillable = [
        'id', 'name'
    ];
}
</code>```

答:
You need to fetch categories as well:

```<code>Route::get('product', function(){ return App\Clothes::with('category')->get(); });
</code>```

This would work if models and relations properly defined.

In cloths model add this:

```<code>public function category()
{
    return $this->belongsTo('App\Category', 'category_id' );
}
</code>```

In category model add this:

```<code>public function clothes()
{
    return $this->hasMany('App\Clothes', 'category_id' );
}
</code>```

Body:
I have two table in mysql one called category with id and name (e.g 1 Dress)

public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->timestamps();
        });
    }

Second table called clothes with foreign key category_id (e.g 1, Black Dress, very cool,10.99,/images.img1,10,1)

public function up()
    {
        Schema::create('clothes', function (Blueprint $table) {
         $table->increment('id');
        $table->string('item');
        $table->string('description');
        $table->double('price');
        $table->string('img');
        $table->integer('stock');
        $table->integer('category_id');

        });
        Schema::table('clothes', function($table) {
            $table->foreign('category_id')->references('id')->on('categories');
        });
    }

So what I am trying is with react fetch information with name category.

componentDidMount(){
        axios.get('product')
        .then(response => {
          this.setState({ products: response.data });
        })
        .catch(function (error) {
          console.log(error);
        })

render(){
    return (

Products

             {this.state.products.map((data,mykey)=>

{data.item}

{data.description}

Price: {data.price}$

{data.category_id} <Button>Yess</Button>

            )}

    )
  }

In web.php

Route::get('product', function(){ return App\Clothes::all(); });

In this way I am getting just the number of category but I want to get the name of category.

I would appreciate any type of idea or help to get the name of category not just id.

UPDATE::
Clothes.php

class Clothes extends Model
{
    //
    protected $fillable = [
        'id', 'item','description','price','img','stock', 'category_id'
    ];

}

Category.php

class Category extends Model
{
    //
    protected $fillable = [
        'id', 'name'
    ];
}

Body:
You need to fetch categories as well:

Route::get('product', function(){ return App\Clothes::with('category')->get(); });

This would work if models and relations properly defined.

In cloths model add this:

public function category()
{
    return $this->belongsTo('App\Category', 'category_id' );
}

In category model add this:

public function clothes()
{
    return $this->hasMany('App\Clothes', 'category_id' );
}


问:
React hooks - fetching data from api and passing to a component
So basically, I'm trying to fetch data from api and pass it to Component.

I create usePosition hook to get my positon from browser, and then get response from api. I really don't know how to wait with useEffect for my position, when i'm executing this code now I'm getting always log 'no position'.

```<code>const usePosition = () => {
    const [error, setError] = useState(null);
  const [position, setPosition] = useState();

  useEffect(() => {
    const geo = navigator.geolocation;
        if(!geo) {
            setError('Geolocation is not supported.');
            return;
        }

        const handleSuccess = position => {
            const { latitude, longitude } = position.coords;
            setPosition({
                latitude,
                longitude
            });
        };

        const handleError = error => {
            setError(error.message);
        };

        geo.getCurrentPosition(handleSuccess, handleError);

    }, []);

    return { position, error };
}

function App() {
  const {position, error} = usePositon();
  const [weather, setWeather] = useState([]);

  useEffect(() => {
    if(position) {
      const URL = `https://api.openweathermap.org/data/2.5/onecall?lat=${position.latitude}&lon=${position.longitude}&exclude=current,minutely,daily&units=metric&lang=pl&appid=${API_KEY}`;

      const fetchData = async () => {
        const result = await fetch(URL)
          .then(res => res.json())
          .then(data => data);
        setWeather(result.hourly);
      }
      fetchData();
    } else {
      console.log('no position');
    }
  }, []);

  return (
      <div className="App">
        <div>
          <Swiper weather={weather}/>
        </div>
      </div>
    )
}
</code>```

答:
It's all because of [] empty dependencies list down in App's useEffect. It runs exactly once on mount, when usePosition has not requested anything yet. And once it successes later and returns different { error, position } App does not react.

How to solve? Provide things as dependencies:

```<code>useEffect(() => {
    if(position) {
      const URL = `https://api.openweathermap.org/data/2.5/onecall?lat=${position.latitude}&lon=${position.longitude}&exclude=current,minutely,daily&units=metric&lang=pl&appid=${API_KEY}`;

      const fetchData = async () => {
        const result = await fetch(URL)
          .then(res => res.json())
          .then(data => data);
        setWeather(result.hourly);
      }
      fetchData();
    } else {
      console.log('no position');
    }
  }, [position, error]);
</code>```

Body:
So basically, I'm trying to fetch data from api and pass it to Component.

I create usePosition hook to get my positon from browser, and then get response from api. I really don't know how to wait with useEffect for my position, when i'm executing this code now I'm getting always log 'no position'.

const usePosition = () => {
    const [error, setError] = useState(null);
  const [position, setPosition] = useState();

  useEffect(() => {
    const geo = navigator.geolocation;
        if(!geo) {
            setError('Geolocation is not supported.');
            return;
        }

        const handleSuccess = position => {
            const { latitude, longitude } = position.coords;
            setPosition({
                latitude,
                longitude
            });
        };

        const handleError = error => {
            setError(error.message);
        };

        geo.getCurrentPosition(handleSuccess, handleError);

    }, []);

    return { position, error };
}

function App() {
  const {position, error} = usePositon();
  const [weather, setWeather] = useState([]);

  useEffect(() => {
    if(position) {
      const URL = `https://api.openweathermap.org/data/2.5/onecall?lat=${position.latitude}&lon=${position.longitude}&exclude=current,minutely,daily&units=metric&lang=pl&appid=${API_KEY}`;

      const fetchData = async () => {
        const result = await fetch(URL)
          .then(res => res.json())
          .then(data => data);
        setWeather(result.hourly);
      }
      fetchData();
    } else {
      console.log('no position');
    }
  }, []);

  return (

          <Swiper weather={weather}/>

    )
}

Body:
It's all because of [] empty dependencies list down in App's useEffect. It runs exactly once on mount, when usePosition has not requested anything yet. And once it successes later and returns different { error, position } App does not react.

How to solve? Provide things as dependencies:

useEffect(() => {
    if(position) {
      const URL = `https://api.openweathermap.org/data/2.5/onecall?lat=${position.latitude}&lon=${position.longitude}&exclude=current,minutely,daily&units=metric&lang=pl&appid=${API_KEY}`;

      const fetchData = async () => {
        const result = await fetch(URL)
          .then(res => res.json())
          .then(data => data);
        setWeather(result.hourly);
      }
      fetchData();
    } else {
      console.log('no position');
    }
  }, [position, error]);


问:
Matching regex for adb gfxinfo logs
I am trying to grep the information from the adb dumpsys gfxinfo logs

The pattern i used is

```<code>\d+\s?(?=\()?
</code>```

The string text may contain following information

```<code>Janky frames: 2 (100.00%)
</code>```

or

```<code>Janky frames: 2
</code>```

In both the cases i need the ouput as 2.

But the regex above used matches the 100 too.

答:
You could use something like this

```<code>\d+(?=\s*\()|\d+$
</code>```

It matches a number which must be followed by optional whitespace character and an opening bracket (non-matching). It also matches a number at the end of the line.

Title: Matching regex for adb gfxinfo logs

Body:
I am trying to grep the information from the adb dumpsys gfxinfo logs

The pattern i used is

\d+\s?(?=\()?

The string text may contain following information

Janky frames: 2 (100.00%)

or

Janky frames: 2

In both the cases i need the ouput as 2.

But the regex above used matches the 100 too.

Body:
You could use something like this

\d+(?=\s*\()|\d+$

It matches a number which must be followed by optional whitespace character and an opening bracket (non-matching). It also matches a number at the end of the line.


问:
SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81
I am currently new to robot framework.I am currently using latest window version of chrome and chromedriver which is 80 but when i try to run the test it gives the message "SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81" in pycharm but currently beta version of 81 is only available. I have tried uninstalling everthing and reinstalling it again but nothing works can anyone help me with this.Thank you!

Screenshots below:

答:
Chrome version is updating everyday so you need use exact chromedriver version according chrome version
https://chromedriver.chromium.org/downloads in this website you can download chromedrivers</p>


问:
Using SYCL 1.2 in MacOS
I want to start using SYCL,  but so far I found that one needs to install ComputeCpp and it only supports Ubuntu, CentOS, and Windows. What are the alternatives for using SYCL on MacOS Catalina?</p>

答:
ComputeCpp is one of several SYCL implementations, the full list is here.

None of the implementations currently support macOS, this is mainly because Apple plans to drop support for OpenCL and only provide support for Metal as its interface to hardware. You can however dual boot your Apple machine with Linux and use that to develop with any of the SYCL implementations (including ComputeCpp).

Title: Using SYCL 1.2 in MacOS


问:
Setup gRPC DB-less API gateway: 415 Unsupported Media Type
I am current setup kong for my project. originally, server is monolith architecture), my team want to separate it into microservice. As my project using gRPC to communicate between client and server, I am thinking of using an API gateway support gRPC. I find Kong in Google and Medium suggested. and I have set it up with DB-less mode. I use docker-compose to run. Below is what I did:

Here is docker-compose.yml

```<code>version: '3'
networks:
    kong-net:
        driver: bridge
services:
    gateway:
        image: kong:2.0.2
        networks:
            - kong-net
        volumes:
            - ./../kong:/var/lib/docker/volumes/kong-vol/_data
        environment:
            KONG_SSL:                       "off"
            KONG_DATABASE:                  "off"
            KONG_DECLARATIVE_CONFIG:        /var/lib/docker/volumes/kong-vol/_data/kong.yml
            #KONG_SSL_CERT:                  /
            #KONG_SSL_CERT_KEY:              /
            KONG_PROXY_LISTEN:              0.0.0.0:8000, 0.0.0.0:8443 ssl, 0.0.0.0:9080 http2, 0.0.0.0:9081 http2 ssl
            KONG_ADMIN_LISTEN:              127.0.0.1:8001, 127.0.0.1:8444 ssl
        ports:
            - "8000:8000"
            - "8443:8443"
            - "8001:8001"
            - "8444:8444"
            - "9080:9080"
            - "9081:9081"
        healthcheck:
            test: ["CMD", "kong", "health"]
            interval: 5s
            timeout: 2s
            retries: 15
        restart: on-failure
    appserver:
        image: saigonparkingmap/appserver:v1.0
        networks:
            - kong-net
        ports:
            - "9090:9090"
            - "9999:9999"
        depends_on:
            - gateway
</code>```

Here is kong.yml

```<code>services:
    -   name: appserver
        url: http://localhost:8001/services
        protocol: grpc
        host: appserser
        port: 9999
        connect_timeout: 30000
        write_timeout: 30000
        read_timeout: 30000
        routes:
            -   name: parking-lot-service
                protocols:
                    - grpc
                paths:
                    - /com.bht.parkingmap.api.proto.parkinglot.ParkingLotService/
</code>```

And I faced 415 Unsupported Media Type Error response from Kong.

Here is what I received from client console:

```<code>Caused by: io.grpc.StatusRuntimeException: UNKNOWN: HTTP status code 415
invalid content-type: text/html; charset=UTF-8
headers: Metadata(:status=415,content-type=text/html; charset=UTF-8,content-length=144,date=Sun, 29 Mar 2020 23:24:57 GMT,access-control-allow-origin=*,server=kong/2.0.2,x-kong-admin-latency=381,x-kong-upstream-latency=381,x-kong-proxy-latency=2,via=kong/2.0.2)
DATA-----------------------------
<html>
<head><title>415 Unsupported Media Type</title></head>
<body>
<center><h1>415 Unsupported Media Type</h1></center>
</body>
</html>

    at io.grpc.stub.ClientCalls.toStatusRuntimeException(ClientCalls.java:240)
    at io.grpc.stub.ClientCalls.getUnchecked(ClientCalls.java:221)
    at io.grpc.stub.ClientCalls.blockingUnaryCall(ClientCalls.java:140)
    at com.bht.parkingmap.api.proto.parkinglot.ParkingLotServiceGrpc$ParkingLotServiceBlockingStub.getParkingLotById
</code>```

And here is what I received from Kong Docker Container:

```<code>gateway_1    | 2020/03/29 23:24:56 [warn] 23#0: *490 a client request body is buffered to a temporary file /usr/local/kong/client_body_temp/0000000001, client: 172.20.0.1, server: kong, request: "POST /com.bht.parkingmap.api.proto.parkinglot.ParkingLotService/getParkingLotById HTTP/2.0", host: "localhost:9080"
gateway_1    | 127.0.0.1 - - [29/Mar/2020:23:24:57 +0000] "POST /services/com.bht.parkingmap.api.proto.parkinglot.ParkingLotService/getParkingLotById HTTP/1.1" 415 144 "-" "grpc-java-netty/1.27.2"
gateway_1    | 172.20.0.1 - - [29/Mar/2020:23:24:57 +0000] "POST /com.bht.parkingmap.api.proto.parkinglot.ParkingLotService/getParkingLotById HTTP/2.0" 415 144 "-" "grpc-java-netty/1.27.2"
</code>```

I use a stub of ManagedChannel from client call to Kong gateway port 9080 and look forward it will come to service server listening on port 9999.

Client (Stub) ----> Kong :9080 ----> Service :9999

Did I miss something in the configuration or I misunderstand anything about the grpc gateway ?
I am looking forward to receive your support ! Thank you very much.

答:
There is something wrong with your kong.yml.
The url key in the Kong Service is shorthand for the protocol://host:port properties.

I got it working by doing this one in my kong.yml:

```<code>_format_version: "1.1"

services:
  - name: grpc
    protocol: grpc
    host: host.docker.internal
    port: 9797
    routes:
      - name: catch-all-grpc-requests
        paths:
          - /
        protocols:
          - grpc
</code>```

This is the equivalent by using the url shorthand. This will produce the same effect as above:

```<code>_format_version: "1.1"

services:
  - name: grpc
    url: grpc://host.docker.internal:9797
    routes:
      - name: catch-all-grpc-requests
        paths:
          - /
        protocols:
          - grpc
</code>```

This is assuming that my gRPC server is running in my localhost at port 9797.

I used host.docker.internal so that my Kong Docker container can reach my also Dockerized gRPC Server which I exposed to :9797.

And then I grpcurl'd like so:

```<code>grpcurl -v -d '{"name": "Ken"}' -plaintext localhost:9080 facade.GreetingService/SayHello
</code>```

So what happened was:

Client (grpcurl) -> Kong HTTP2 proxy listener (:9080) -> gRPC Server (:9797)

Source: https://konghq.com/blog/manage-grpc-services-kong/

Body:
I am current setup kong for my project. originally, server is monolith architecture), my team want to separate it into microservice. As my project using gRPC to communicate between client and server, I am thinking of using an API gateway support gRPC. I find Kong in Google and Medium suggested. and I have set it up with DB-less mode. I use docker-compose to run. Below is what I did:

Here is docker-compose.yml

version: '3'
networks:
    kong-net:
        driver: bridge
services:
    gateway:
        image: kong:2.0.2
        networks:
            - kong-net
        volumes:
            - ./../kong:/var/lib/docker/volumes/kong-vol/_data
        environment:
            KONG_SSL:                       "off"
            KONG_DATABASE:                  "off"
            KONG_DECLARATIVE_CONFIG:        /var/lib/docker/volumes/kong-vol/_data/kong.yml
            #KONG_SSL_CERT:                  /
            #KONG_SSL_CERT_KEY:              /
            KONG_PROXY_LISTEN:              0.0.0.0:8000, 0.0.0.0:8443 ssl, 0.0.0.0:9080 http2, 0.0.0.0:9081 http2 ssl
            KONG_ADMIN_LISTEN:              127.0.0.1:8001, 127.0.0.1:8444 ssl
        ports:
            - "8000:8000"
            - "8443:8443"
            - "8001:8001"
            - "8444:8444"
            - "9080:9080"
            - "9081:9081"
        healthcheck:
            test: ["CMD", "kong", "health"]
            interval: 5s
            timeout: 2s
            retries: 15
        restart: on-failure
    appserver:
        image: saigonparkingmap/appserver:v1.0
        networks:
            - kong-net
        ports:
            - "9090:9090"
            - "9999:9999"
        depends_on:
            - gateway

Here is kong.yml

services:
    -   name: appserver
        url: http://localhost:8001/services
        protocol: grpc
        host: appserser
        port: 9999
        connect_timeout: 30000
        write_timeout: 30000
        read_timeout: 30000
        routes:
            -   name: parking-lot-service
                protocols:
                    - grpc
                paths:
                    - /com.bht.parkingmap.api.proto.parkinglot.ParkingLotService/

And I faced 415 Unsupported Media Type Error response from Kong.

Here is what I received from client console:

Caused by: io.grpc.StatusRuntimeException: UNKNOWN: HTTP status code 415
invalid content-type: text/html; charset=UTF-8
headers: Metadata(:status=415,content-type=text/html; charset=UTF-8,content-length=144,date=Sun, 29 Mar 2020 23:24:57 GMT,access-control-allow-origin=*,server=kong/2.0.2,x-kong-admin-latency=381,x-kong-upstream-latency=381,x-kong-proxy-latency=2,via=kong/2.0.2)
DATA-----------------------------

<title>415 Unsupported Media Type</title>

415 Unsupported Media Type

    at io.grpc.stub.ClientCalls.toStatusRuntimeException(ClientCalls.java:240)
    at io.grpc.stub.ClientCalls.getUnchecked(ClientCalls.java:221)
    at io.grpc.stub.ClientCalls.blockingUnaryCall(ClientCalls.java:140)
    at com.bht.parkingmap.api.proto.parkinglot.ParkingLotServiceGrpc$ParkingLotServiceBlockingStub.getParkingLotById

And here is what I received from Kong Docker Container:

gateway_1    | 2020/03/29 23:24:56 [warn] 23#0: *490 a client request body is buffered to a temporary file /usr/local/kong/client_body_temp/0000000001, client: 172.20.0.1, server: kong, request: "POST /com.bht.parkingmap.api.proto.parkinglot.ParkingLotService/getParkingLotById HTTP/2.0", host: "localhost:9080"
gateway_1    | 127.0.0.1 - - [29/Mar/2020:23:24:57 +0000] "POST /services/com.bht.parkingmap.api.proto.parkinglot.ParkingLotService/getParkingLotById HTTP/1.1" 415 144 "-" "grpc-java-netty/1.27.2"
gateway_1    | 172.20.0.1 - - [29/Mar/2020:23:24:57 +0000] "POST /com.bht.parkingmap.api.proto.parkinglot.ParkingLotService/getParkingLotById HTTP/2.0" 415 144 "-" "grpc-java-netty/1.27.2"

I use a stub of ManagedChannel from client call to Kong gateway port 9080 and look forward it will come to service server listening on port 9999.

Client (Stub) ----> Kong :9080 ----> Service :9999

Did I miss something in the configuration or I misunderstand anything about the grpc gateway ?
I am looking forward to receive your support ! Thank you very much.

Body:
There is something wrong with your kong.yml.
The url key in the Kong Service is shorthand for the protocol://host:port properties.

I got it working by doing this one in my kong.yml:

_format_version: "1.1"

services:
  - name: grpc
    protocol: grpc
    host: host.docker.internal
    port: 9797
    routes:
      - name: catch-all-grpc-requests
        paths:
          - /
        protocols:
          - grpc

This is the equivalent by using the url shorthand. This will produce the same effect as above:

_format_version: "1.1"

services:
  - name: grpc
    url: grpc://host.docker.internal:9797
    routes:
      - name: catch-all-grpc-requests
        paths:
          - /
        protocols:
          - grpc

This is assuming that my gRPC server is running in my localhost at port 9797.

I used host.docker.internal so that my Kong Docker container can reach my also Dockerized gRPC Server which I exposed to :9797.

And then I grpcurl'd like so:

grpcurl -v -d '{"name": "Ken"}' -plaintext localhost:9080 facade.GreetingService/SayHello

So what happened was:

Client (grpcurl) -> Kong HTTP2 proxy listener (:9080) -> gRPC Server (:9797)

Source: https://konghq.com/blog/manage-grpc-services-kong/


问:
IOS Expo Push Notifications when app is in foreground
reading from the expo docs:

For iOS, you would be wise to handle push notifications that are
  received while the app is foregrounded, because otherwise the user
  will never see them. Notifications that arrive while the app are
  foregrounded on iOS do not show up in the system notification list. A
  common solution is to just show the notification manually. For
  example, if you get a message on Messenger for iOS, have the app
  foregrounded, but do not have that conversation open, you will see the
  notification slide down from the top of the screen with a custom
  notification UI.

What I don't understand is what is the best approach for that? is there an Expo API for showing such messages? or should I create an alert component of my own? It is not really clear from the docs.

Thanks.

答:
App.json :</p>

```<code>{
  "expo": {
    "notification": {
      "iosDisplayInForeground": true
    }
}
</code>```

Body:
App.json :

{
  "expo": {
    "notification": {
      "iosDisplayInForeground": true
    }
}


问:
What is the difference (if any) between a route and an endpoint in the context of a RESTful API?

Question

I have a probably rather simple question, but I'm unable to find an answer with nice explanations:

What is the difference (if any) between a route and an endpoint in the context of a RESTful API developed within a Node.js / Express application (but these concepts may be broader?!)?

(Does it relate to URLs in some way?)

Example

For example, in this article: https://medium.com/@purposenigeria/build-a-restful-api-with-node-js-and-express-js-d7e59c7a3dfb we can read:

We imported express which we installed at the beginning of the course, app.get makes a get request to the server with the route/endpoint provided as the first parameter, the endpoint is meant to return all the todos in the database.

These concepts are used interchangeably, which makes me confused.

(please note that I'm a 100% beginner with REST API, nodejs and express but I try to do my best to learn).

Edit

The two first answers chronologically speaking make me even more confused as they are perfectly antagonistic.

答:
Routes and endpoints are associated concepts - you can't really have one without the other.

What is an endpoint?

Generally speaking, an "endpoint" is one end of a communication channel where one system interacts with another system. This term is also used similarly in networking.

For a typical web API, endpoints are URLs, and they are described in the API's documentation so programmers know how to use/consume them. For example, a particular web API may have this endpoint:

GET https://my-api.com/Library/Books
```

<p>This would return a list of all books in the library.</p>

<h1>What is a route?</h1>

<p>A "route" is typically code that matches incoming request paths to resources. In other words, it defines the URL and what code will be executed. A route path might contain regular expressions, patterns, parameters, and involve validation. For example, consider this route path:</p>

<pre class="lang-none prettyprint-override"><code>"{controller}/{action}/{id?}"
</code>```

In ASP.NET, pattern matching is applied, so GET https://my-api.com/Library/Books/341 would call the Books public method on the Library class, passing a parameter of 341. Routing frameworks can be very flexible and versatile.

The simplest example of an endpoint is to put a file you want to be consumed (say data.json) inside the public_html folder of your web server. It can be reached by GET https://my-api.com/data.json. The routing is handled by the web server out of the box and no routing code is required.

Some good things to read next:

Express.js - Routing

Wordpress Developer Resources - Routes and Endpoints

When to use "client-side routing" or "server-side routing"?

Body:
Routes and endpoints are associated concepts - you can't really have one without the other.

What is an endpoint?

Generally speaking, an "endpoint" is one end of a communication channel where one system interacts with another system. This term is also used similarly in networking.

For a typical web API, endpoints are URLs, and they are described in the API's documentation so programmers know how to use/consume them. For example, a particular web API may have this endpoint:

GET https://my-api.com/Library/Books

This would return a list of all books in the library.

What is a route?

A "route" is typically code that matches incoming request paths to resources. In other words, it defines the URL and what code will be executed. A route path might contain regular expressions, patterns, parameters, and involve validation. For example, consider this route path:

"{controller}/{action}/{id?}"

In ASP.NET, pattern matching is applied, so GET https://my-api.com/Library/Books/341 would call the Books public method on the Library class, passing a parameter of 341. Routing frameworks can be very flexible and versatile.

The simplest example of an endpoint is to put a file you want to be consumed (say data.json) inside the public_html folder of your web server. It can be reached by GET https://my-api.com/data.json. The routing is handled by the web server out of the box and no routing code is required.

Some good things to read next:

Express.js - Routing

Wordpress Developer Resources - Routes and Endpoints

When to use "client-side routing" or "server-side routing"?


问:
Combining different repositories as a single maven project
I have few standalone projects which are built in sbt and few are in maven.
These projects are available in github as seperate repositories.
Now the task is to keep all these projects into a single repository.

My plan is to keep all these projects as different packages into a single maven project and store this into a single repo. I am using IntelliJ as IDE.
How can I achieve this? Or is there any easy way to achieve this, other than just copying all repos into a single one?
Can we keep both sbt build and maven build file together in one project or do we need to migrate all the sbt builds to maven?

Any leads appreciated!

答:
If you want to combine them into a single Maven repository then obviously you will need to convert Sbt projects into a Maven ones. To convert you may consider using makePom from SBT. See also this SO thread.

Can we keep both sbt build and maven build file together in one project or do we need to migrate all the sbt builds to maven?

You can. In IDE then you will need to choose if you would like to open such project (module) as a Maven or SBT based.


问:
is there some method in OpenCL to count kernel time like cuda's time function
In cuda there is a function named time() in kernel to test latency between some functions; for example,

```<code>__global__ void kmulu_dep512() {
start_time = clock();
repeat256(t *= t2 ; t2 *= t ; )
stop_time = clock();
}
</code>```

I cannot find OpenCL have similar function, is there some method to workround in OpenCL in order to get the similar effect?

答:
AFAIK, there is no such built-in in OpenCL, but you can do that via host API: look for information about event profiling info in OpenCL.

Briefly, you will need to create a command queue with profiling info enabled and then query command start/end time points from the event corresponding to a kernel you are interested in:

```<code>g_cmd_queue = clCreateCommandQueue(... CL_QUEUE_PROFILING_ENABLE, NULL);
clEnqueueNDRangeKernel(g_cmd_queue, ..., &perf_event);
clWaitForEvents(1, &perf_event);
cl_ulong start = 0, end = 0;
clGetEventProfilingInfo(perf_event, CL_PROFILING_COMMAND_START, sizeof(cl_ulong), &start, NULL);
clGetEventProfilingInfo(perf_event, CL_PROFILING_COMMAND_END, sizeof(cl_ulong), &end, NULL);
</code>```

Body:
In cuda there is a function named time() in kernel to test latency between some functions; for example,

__global__ void kmulu_dep512() {
start_time = clock();
repeat256(t *= t2 ; t2 *= t ; )
stop_time = clock();
}

I cannot find OpenCL have similar function, is there some method to workround in OpenCL in order to get the similar effect?

Body:
AFAIK, there is no such built-in in OpenCL, but you can do that via host API: look for information about event profiling info in OpenCL.

Briefly, you will need to create a command queue with profiling info enabled and then query command start/end time points from the event corresponding to a kernel you are interested in:

g_cmd_queue = clCreateCommandQueue(... CL_QUEUE_PROFILING_ENABLE, NULL);
clEnqueueNDRangeKernel(g_cmd_queue, ..., &perf_event);
clWaitForEvents(1, &perf_event);
cl_ulong start = 0, end = 0;
clGetEventProfilingInfo(perf_event, CL_PROFILING_COMMAND_START, sizeof(cl_ulong), &start, NULL);
clGetEventProfilingInfo(perf_event, CL_PROFILING_COMMAND_END, sizeof(cl_ulong), &end, NULL);


问:
How to get innerHTML attribute value "r" in this code?
I'm using D3.js for my personal project.

But, I faced with some troubles.

```<code>        bubble.nodes(root)
        svg = d3.select("svg").attr("class", "bubble")

        var node = svg.selectAll(".node")
            .data(bubble.nodes(root)
                .filter(function(d) {
                    return !d.children;
                }))
            .enter()
            .append("g")
            .attr("class", "node")
            .attr("transform", function(d) {
                return "translate(" + d.x + "," + d.y + ")";
            })
</code>```

In the picture, I want to get "r" value in the circle.
How can I get this value?
Also, this circle is one part of bubble chart node.

答:
Using vanilla JS...  getElementsByTagName('circle'), then getAttribute('r') to find the value of r

let circle = document.getElementsByTagName('circle');
let target = circle[0].getAttribute('r');
console.log(target);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><circle r="0.75847397430597"></circle></code>```

Body:
I'm using D3.js for my personal project.

But, I faced with some troubles.

        bubble.nodes(root)
        svg = d3.select("svg").attr("class", "bubble")

        var node = svg.selectAll(".node")
            .data(bubble.nodes(root)
                .filter(function(d) {
                    return !d.children;
                }))
            .enter()
            .append("g")
            .attr("class", "node")
            .attr("transform", function(d) {
                return "translate(" + d.x + "," + d.y + ")";
            })

In the picture, I want to get "r" value in the circle.
How can I get this value?
Also, this circle is one part of bubble chart node.

Body:
Using vanilla JS...  getElementsByTagName('circle'), then getAttribute('r') to find the value of r

let circle = document.getElementsByTagName('circle');
let target = circle[0].getAttribute('r');
console.log(target);

<circle r="0.75847397430597"></circle>


问:
How to handle date error with months in datetime.replace in python?
I have the date object which is as follows. Date: 2025-11-30. If I add 3 month to it using following code, it will raise an Exception as follows.

code:

```<code>def get_next_n_month_forward(date, n):
    if date.month + n > 12:
        next_month = date.replace(year=date.year + 1,
                                  month=(date.month + n) % 12)
    else:
        next_month = date.replace(month=(date.month + n))
    return next_month
</code>```

exception:

```<code>ValueError: day is out of range for month
</code>```

As far as I can understand from error it is because february does not have 30th day.

Question: How can I make it set to the last day of the month? !Note: In my case it would be 29th or 28th of February.

答:
You can use timedelta object to increase and decrease dates

```<code>from datetime import timedelta
import datetime
d = datetime.datetime.today()
new_d = d + timedelta(days=1)
</code>```

In order to set the date to the last day of month, you can set the date to the 1st of the next month and then decrease it by 1 day:

```<code>from datetime import timedelta
import datetime
day = datetime.datetime.today()
prev_month_last_day = day.replace(day=1) - timedelta(days=1)
</code>```

Body:
I have the date object which is as follows. Date: 2025-11-30. If I add 3 month to it using following code, it will raise an Exception as follows.

code:

def get_next_n_month_forward(date, n):
    if date.month + n > 12:
        next_month = date.replace(year=date.year + 1,
                                  month=(date.month + n) % 12)
    else:
        next_month = date.replace(month=(date.month + n))
    return next_month

exception:

ValueError: day is out of range for month

As far as I can understand from error it is because february does not have 30th day.

Question: How can I make it set to the last day of the month? !Note: In my case it would be 29th or 28th of February.

Body:
You can use timedelta object to increase and decrease dates

from datetime import timedelta
import datetime
d = datetime.datetime.today()
new_d = d + timedelta(days=1)

In order to set the date to the last day of month, you can set the date to the 1st of the next month and then decrease it by 1 day:

from datetime import timedelta
import datetime
day = datetime.datetime.today()
prev_month_last_day = day.replace(day=1) - timedelta(days=1)


问:
xpath assertionfor soap web service in jmeter
I need to test using JMeter XPath, I have an response text

```<code><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
   <soap:Body>
      <ns2:createIndexResponse xmlns:ns2="http://webservice.example.com/">
         <example>
            <name>foer</name>
         </example>
      </ns2:createIndexResponse>
   </soap:Body>
</soap:Envelope>
</code>```

And I need to test if the name is equal to foer,  I used XPath assertion as /example/name/entry[@key='name']/text()='foer' but I get:

```<code>No Nodes Matched `/example/name/entry[@key='name']/text()='foer'
</code>```

答:
in your example xml there is no entry element and no @key attribute. Plus the example element is not the root element.

try this instead for just testing the existence:

```<code>//example/name/text() = "foer"
</code>```

or for selecting the example element:

```<code>//example[name/text() = "foer"]
</code>```

Body:
I need to test using JMeter XPath, I have an response text

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
   <soap:Body>
      <ns2:createIndexResponse xmlns:ns2="http://webservice.example.com/">
         <example>
            <name>foer</name>
         </example>
      </ns2:createIndexResponse>
   </soap:Body>
</soap:Envelope>

And I need to test if the name is equal to foer,  I used XPath assertion as /example/name/entry[@key='name']/text()='foer' but I get:

No Nodes Matched `/example/name/entry[@key='name']/text()='foer'

Body:
in your example xml there is no entry element and no @key attribute. Plus the example element is not the root element.

try this instead for just testing the existence:

//example/name/text() = "foer"

or for selecting the example element:

//example[name/text() = "foer"]