问:
get model using string
I'm trying to access a Model in Laravel app through its Class Name, but I'm getting the following error:

```<code>Class 'Asset' not found
</code>```

Though, I've already imported this Model.
Here's my code:

```<code><?php
namespace App\Services;
use App\Models\Asset as Asset;
use App\Models\Benefit\BenefitGroup as BenefitGroup;
use App\Models\Benefit\EmployeeDependent as EmployeeDependent;
use App\Models\Country as Country;
use App\Models\Employee\Education as Education;
use App\Models\Employee\EducationType as EducationType;
use App\Models\Employee\Employee as Employee;
use App\Models\Employee\EmployeeVisa as EmployeeVisa;
use App\Models\Employee\VisaType as VisaType;
use App\Models\Note as Note;
use App\Models\PaidTimeOff\Policy as Policy;
use App\Models\PaidTimeOff\TimeOffType as TimeOffType;
use Illuminate\Database\Eloquent\Model;
class ACLService
{
    public function getDefaultPermissions($roleType)
    {
        //Array to append all default permissions in single array without extra indexing
        $permissions=[];
        $models=['Asset', 'Employee', 'Education', 'EducationType', 'VisaType', 'EmployeeVisa', 'BenefitGroup', 'EmployeeDependent',
            'Policy', 'TimeOffType','Country', 'Note'];
        foreach ($models as $model) {
            $permissions=$this->getModelPermissions($model, $roleType, $permissions);
        }
    }
    public function getModelPermissions($model, $roleType, $currentPermissions)
    {
        $data=$model::getDefaultPermissionsForThisModel($roleType, $currentPermissions);
        return $data;
    }
}
</code>```

If I pass

```<code>App\Models\Asset
</code>```

instead of

```<code>Asset
</code>```

then the error gets resolved but I don't want to pass data in this format because it'll increase the work amount if we ever get to change (in future) the Model's location in the project.

This is an incomplete project and we'll definitely change the models' location.

I'm looking for a cleaner solution.

答:
Use the ::class constant to get the correctly namespaced class name. This will also make it easier if you ever move the files. Smart IDE's will be able to detect the reference.

```<code>$models=[
    Asset::class,
    Employee::class,
    ...
];
</code>```

This presumes all classes have been imported at the top of your PHP file.

Title: get model using string

Body:
I'm trying to access a Model in Laravel app through its Class Name, but I'm getting the following error:

Class 'Asset' not found

Though, I've already imported this Model.
Here's my code:

<?php
namespace App\Services;
use App\Models\Asset as Asset;
use App\Models\Benefit\BenefitGroup as BenefitGroup;
use App\Models\Benefit\EmployeeDependent as EmployeeDependent;
use App\Models\Country as Country;
use App\Models\Employee\Education as Education;
use App\Models\Employee\EducationType as EducationType;
use App\Models\Employee\Employee as Employee;
use App\Models\Employee\EmployeeVisa as EmployeeVisa;
use App\Models\Employee\VisaType as VisaType;
use App\Models\Note as Note;
use App\Models\PaidTimeOff\Policy as Policy;
use App\Models\PaidTimeOff\TimeOffType as TimeOffType;
use Illuminate\Database\Eloquent\Model;
class ACLService
{
    public function getDefaultPermissions($roleType)
    {
        //Array to append all default permissions in single array without extra indexing
        $permissions=[];
        $models=['Asset', 'Employee', 'Education', 'EducationType', 'VisaType', 'EmployeeVisa', 'BenefitGroup', 'EmployeeDependent',
            'Policy', 'TimeOffType','Country', 'Note'];
        foreach ($models as $model) {
            $permissions=$this->getModelPermissions($model, $roleType, $permissions);
        }
    }
    public function getModelPermissions($model, $roleType, $currentPermissions)
    {
        $data=$model::getDefaultPermissionsForThisModel($roleType, $currentPermissions);
        return $data;
    }
}

If I pass

App\Models\Asset

instead of

Asset

then the error gets resolved but I don't want to pass data in this format because it'll increase the work amount if we ever get to change (in future) the Model's location in the project.

This is an incomplete project and we'll definitely change the models' location.

I'm looking for a cleaner solution.

Body:
Use the ::class constant to get the correctly namespaced class name. This will also make it easier if you ever move the files. Smart IDE's will be able to detect the reference.

$models=[
    Asset::class,
    Employee::class,
    ...
];

This presumes all classes have been imported at the top of your PHP file.


来源: stackexchange

问:
Angular Tree Shaking: How exactly does it work?
We are currently trying to optimize a complex angular application (performance & bundle size).

We found that we have partially unused components, but we are not 100% sure about them. Anyway... The question we are currently asking is how exactly does tree shaking work in Angular?

Question 1) If there are entries inside the declarations, imports or providers array of a module, but the module is not used anywhere, are they also removed with tree shaking or are they included in the final bundle?

Example:

```<code>@NgModule({
  imports: [
    FirstModule,
    SecondModule  // Is not used anymore (probably) but imported here
  ],
  declarations: [SampleComponent] // Is not used anymore (probably) but imported here
})
export class SampleModule {
}
</code>```

Info: The routes to those modules/components are already deleted.

Question 2) Is it sufficient to only remove these components from the routing modules so that the tree shaking process is successful?

Question 3) What should be in place for the treeshaking process to work optimally?

Used Angular Version 8.2

答: You can use webpack-bundle-analyzer which will help you visualize the size and the different used components in your final output file. This way you can be sure if a module is used or not and then you can safely delete it.</p>

ContentLicense: CC BY-SA 4.0

Body:
We are currently trying to optimize a complex angular application (performance & bundle size).

We found that we have partially unused components, but we are not 100% sure about them. Anyway... The question we are currently asking is how exactly does tree shaking work in Angular?

Question 1) If there are entries inside the declarations, imports or providers array of a module, but the module is not used anywhere, are they also removed with tree shaking or are they included in the final bundle?

Example:

@NgModule({
  imports: [
    FirstModule,
    SecondModule  // Is not used anymore (probably) but imported here
  ],
  declarations: [SampleComponent] // Is not used anymore (probably) but imported here
})
export class SampleModule {
}

Info: The routes to those modules/components are already deleted.

Question 2) Is it sufficient to only remove these components from the routing modules so that the tree shaking process is successful?

Question 3) What should be in place for the treeshaking process to work optimally?

Used Angular Version 8.2


问:
images on Heroku Deploy not showing up
I'm having an issue where only 1 of my images shows up when deploying to Heroku whereas all show up on localhost. The one that shows up is

```<code><div class="hero-wrap ftco-degree-bg" style="background-image: url('images/bg_1.jpg');" data-stellar-background-ratio="0.5">
</code>```

Where I'm pulling the image with url(), but every other instance where I try to do this in the code (three different attempts):

```<code><a class="img" id="albumPhoto1" style="background-image: url('../images/greenPurplegrad.jpg');"></a>
<a class="img" id="albumPhoto2" style="background-image: url('./images/yellowPinkgrad.jpg');"></a>
<a class="img" id="albumPhoto3" style="background-image: url('images/pinkBluegrad.jpg');"></a>
</code>```

But if I set the url as

```<code>style="background-image: url('images/bg_1.jpg");"
</code>```

(the same as the first image that shows up) the image will show. Obviously I don't want all the same image, so I'd like some help in seeing where I went wrong.

Here's an image of the images folder to show I have all these images in the correct location:
Images Folder

Yes, all of them are .jpg

The web app can be found here: My Web App on Heroku
If you just press the search-icon, right below it some images (as seen above) should pop up, but they don't

EDIT:
Added image of file structure:
Public folder with HTML and images folder

EDIT 2:
Something weird to note is that if I change any image to the bg_1.jpg, it will show up, but if I change the section with bg_1.jpg to any other image, it won't show up on the background. So I believe my images may be corrupted somehow even though I can see them in the folder.

答:
I believe it is because of a dynamic address, when you type "../image.jpg" or "image.jpg", you are defining a static address, this is practical for local application, but not for PHP .. .

I don't know exactly if this is the center of the problem, but try this: background: url ("/path/to/file/image.jpg")

when you type the first "/" you are taking the current file and having it search from this file.

Title: images on Heroku Deploy not showing up

Body:
I'm having an issue where only 1 of my images shows up when deploying to Heroku whereas all show up on localhost. The one that shows up is

Where I'm pulling the image with url(), but every other instance where I try to do this in the code (three different attempts):

But if I set the url as

style="background-image: url('images/bg_1.jpg");"

(the same as the first image that shows up) the image will show. Obviously I don't want all the same image, so I'd like some help in seeing where I went wrong.

Here's an image of the images folder to show I have all these images in the correct location:
Images Folder

Yes, all of them are .jpg

The web app can be found here: My Web App on Heroku
If you just press the search-icon, right below it some images (as seen above) should pop up, but they don't

EDIT:
Added image of file structure:
Public folder with HTML and images folder

EDIT 2:
Something weird to note is that if I change any image to the bg_1.jpg, it will show up, but if I change the section with bg_1.jpg to any other image, it won't show up on the background. So I believe my images may be corrupted somehow even though I can see them in the folder.


问:
Why is html5 postMessage not working for me?
I use a few lines of javascript to create an iframe element, and then I'd like to send it a message, like this:

```<code>function loadiframe (callback) {
    var body = document.getElementsByTagName('body')[0];
    var iframe = document.createElement('iframe');
    iframe.id = 'iframe';
    iframe.seamless = 'seamless';
    iframe.src = 'http://localhost:3000/iframe.html';
    body.appendChild(iframe);
    callback();
}

loadiframe(function() {
    cpframe = document.getElementById('iframe').contentWindow;
    cpframe.postMessage('please get this message','http://localhost:3000');
    console.log('posted');
})
</code>```

And then, inside http://localhost:3000/iframe.html (the source of the iframe) is something like this:

```<code><!DOCTYPE html>
<html>
<head>
<title>does not work</title>
<script>
window.addEventListener("message", receiveMessage, false);
function receiveMessage(event) {
  if (event.origin == "http://localhost:3000") {
    document.write(JSON.stringify(event));
    document.write(typeof event);
  }
}
</script>
</head>
<body>
</body>
</html>
</code>```

But nothing happens... I even tried to not use the safety check for origin, but even like that nothing happens... Like it never got the message...

Am I in some kind of async problem ? I tried to make sure the iframe was loaded before the postMessage went away...

EDIT1: Also, no errors show on the console...

EDIT2: I tried it in Google Chrome 11 and Firefox 4

Thank you in advance.

答:
There are two possible problems:

You're calling callback before the child frame has loaded - try it in the load event or do it in a setTimeout

I've never managed to get postMessage to work with anything other that '*' as the origin.  If I put a URL in there I get a security warning "Security Error: Content at http://xxx/ may not load data from http://yyy/", except only in the error console (Ctrl + Shift + J) not in any other place.  I suspect there's some other stuff that needs set up somewhere for that to work, but I've not yet figured out what.

Here's a jsfiddle with a slightly modified version of your code loading a document off my domain, works for me in Firefox and Chrome.

ContentLicense: CC BY-SA 3.0

Body:
I use a few lines of javascript to create an iframe element, and then I'd like to send it a message, like this:

function loadiframe (callback) {
    var body = document.getElementsByTagName('body')[0];
    var iframe = document.createElement('iframe');
    iframe.id = 'iframe';
    iframe.seamless = 'seamless';
    iframe.src = 'http://localhost:3000/iframe.html';
    body.appendChild(iframe);
    callback();
}

loadiframe(function() {
    cpframe = document.getElementById('iframe').contentWindow;
    cpframe.postMessage('please get this message','http://localhost:3000');
    console.log('posted');
})

And then, inside http://localhost:3000/iframe.html (the source of the iframe) is something like this:

<!DOCTYPE html>

<title>does not work</title>

But nothing happens... I even tried to not use the safety check for origin, but even like that nothing happens... Like it never got the message...

Am I in some kind of async problem ? I tried to make sure the iframe was loaded before the postMessage went away...

EDIT1: Also, no errors show on the console...

EDIT2: I tried it in Google Chrome 11 and Firefox 4

Thank you in advance.


问:
Is it possible to read File from same folder where Azure function exists
In my Azure C# function I need to read a .txt file. I make the .txt file in Visual studio and set it to "copy Always".

Now I am using this code to read the file

```<code>var dir = System.IO.Path.GetDirectoryName(
    System.Reflection.Assembly.GetEntryAssembly().Location);

var path = System.IO.Path.Combine(dir, "twinkle.txt");
</code>```

this code doesn't work. When I open the folder which is the value of dir. It lead me to this directory ""C:\Users{username}\AppData\Local\Azure.Functions.Cli\1.0.9""

How I can store a simple txt file in Azure function. Or I need Azure Storage for this.

Anything else I can do to get this done.

Update for showing file copied

答:
Here is a useful link: https://github.com/Azure/azure-functions-host/wiki/Retrieving-information-about-the-currently-running-function

There is the possibility of a hard coded way:

```<code>File.ReadAllText("d:\home\site\wwwroot\NameOfYourFunction" + "/path/to/file.ext");
</code>```

Body:
In my Azure C# function I need to read a .txt file. I make the .txt file in Visual studio and set it to "copy Always".

Now I am using this code to read the file

var dir = System.IO.Path.GetDirectoryName(
    System.Reflection.Assembly.GetEntryAssembly().Location);

var path = System.IO.Path.Combine(dir, "twinkle.txt");

this code doesn't work. When I open the folder which is the value of dir. It lead me to this directory ""C:\Users{username}\AppData\Local\Azure.Functions.Cli\1.0.9""

How I can store a simple txt file in Azure function. Or I need Azure Storage for this.

Anything else I can do to get this done.

Update for showing file copied

Body:
Here is a useful link: https://github.com/Azure/azure-functions-host/wiki/Retrieving-information-about-the-currently-running-function

There is the possibility of a hard coded way:

File.ReadAllText("d:\home\site\wwwroot\NameOfYourFunction" + "/path/to/file.ext");


问:
Azure DevOps - Select distinct IterationPath (workitems table)
I am trying to make in Python a distinct of all the possibilities of the IterationPath field and I am not able to obtain such data. I tried to use UNNEST to get the array it is in but I was unsuccessful. Can anyone help me with this?</p>

```<code>query_wiql = Wiql(query="""\
SELECT distinct [System.IterationPath] FROM workitems
""")
</code>```

答:
Try to use Classification Nodes to get all paths:

Get one iteration, as example root: https://dev.azure.com/<org>/<team project name>/_apis/wit/classificationnodes/Iterations?api-version=5.1. Classification Nodes - Get an iteration.

Check the hasChildren property. If it's true get this iteration with children (add depth to request). Example to get child for Iteration 1:  https://dev.azure.com/<org>/<team project name>/_apis/wit/classificationnodes/Iterations/Iteration 1?$depth=1&api-version=5.1?api-version=5.1

Or try to pass depth with your iteration tree level. Example to get 10 levels of children from the root: https://dev.azure.com/<org>/<team project name>/_apis/wit/classificationnodes/Iterations?$depth=10&api-version=5.1

Body:
I am trying to make in Python a distinct of all the possibilities of the IterationPath field and I am not able to obtain such data. I tried to use UNNEST to get the array it is in but I was unsuccessful. Can anyone help me with this?

query_wiql = Wiql(query="""\
SELECT distinct [System.IterationPath] FROM workitems
""")


问:
Extracting value from an object
I'm working on a discord bot, using discord.js.

I've been working on this command for too long without finding a solution, so I come here to ask for help.
Here is my problem, maybe it's really simple to solve to you, and that would be great :D
I want to create a command that sends a random gif, based on a keyword.
I'm using a node module called giphy-random.

```<code>        (async () => {
            const API_KEY = "hidden";

            const gif = await giphyRandom(API_KEY, {
                tag: "kawaii"
            });
            console.log(gif)
          }
</code>```

I would like to be able to get only the value 'url' of the const which is defined by the function (i'm maybe wrong in my words, I'm a beginner) in order to send it in a channel.

答:
You can simply access field like this:</p>

```<code>            const API_KEY = "hidden";

            const gif = await giphyRandom(API_KEY, {
                tag: "kawaii"
            });

           const {url} = gif.data; // equal to const url = gif.data.url

            console.log(gif);
          }
</code>```

Title: Extracting value from an object

Body:
I'm working on a discord bot, using discord.js.

I've been working on this command for too long without finding a solution, so I come here to ask for help.
Here is my problem, maybe it's really simple to solve to you, and that would be great :D
I want to create a command that sends a random gif, based on a keyword.
I'm using a node module called giphy-random.

        (async () => {
            const API_KEY = "hidden";

            const gif = await giphyRandom(API_KEY, {
                tag: "kawaii"
            });
            console.log(gif)
          }

I would like to be able to get only the value 'url' of the const which is defined by the function (i'm maybe wrong in my words, I'm a beginner) in order to send it in a channel.

Body:
You can simply access field like this:

            const API_KEY = "hidden";

            const gif = await giphyRandom(API_KEY, {
                tag: "kawaii"
            });

           const {url} = gif.data; // equal to const url = gif.data.url

            console.log(gif);
          }


问:
VBS Loop Through Accb files in folder and run saves imports/exports
Just learning some VBS and struggling a little with how to work a specific command for Access Exports/Imports.

In short, I need to loop through all .accb files in a folder. (I think I have that nailed)
For each of the files found, I need to open the file and run all saved imports, THEN saved exports.

I'll attach my code so far.

```<code>Dim objFSO, objFolder, objFile
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder("X:\Path\Path")

For Each objFile in objFolder.Files
    If LCase(objFSO.GetExtentionName(objFile.Name)) = "accb" Then

    'Loop for Opening Access DB and running all imports, then exports
    'Close Access DB

Next

Set objFolder = Nothing
Set objFile = Nothing
Set objFSO = Nothing
</code>```

I've not managed to get very far with looping through the saved Imports/Exports in Access though and I've done a power of googling.

I can write each import/export command explicitly, but I'd much rather this script wouldn't have to be updated each time I added a new import or export.

```<code>Set objAccess = CreateObject("Access.Application")

objAccess.OpenCurrentDatabase "Path"

objAccess.DoCmd.RunSavedImportExport "xxxx"
objAccess.DoCmd.RunSavedImportExport "yyyy"

objAccess.CloseCurrentDatabase

ObjAccess.Quit
'Access.Application.Quit
Set ObjAccess = Nothing
</code>```

I think the only way I can force it to run Imports first is via naming standards.
Lets say each Import/Export has the following naming standard.
I- name
E- name

I think another two For/If loops are required here, but unsure how to go about it.

Any thoughts?

Thank you Andre,

I'll update again when I've managed to test.
But this is what I now have.

```<code>Dim objFSO, objFolder, objFile
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder("X:\Path\Path")

For Each objFile in objFolder.Files
    If LCase(objFSO.GetExtentionName(objFile.Name)) = "accb" Then

    Set objAccess = CreateObject("Access.Application")

    objAccess.OpenCurrentDatabase "Path"

    Dim i As Integer
    For i = 0 To CurrentProject.ImportExportSpecifications.count - 1
    Debug.Print CurrentProject.ImportExportSpecifications(i).name
    If Left(CurrentProject.ImportExportSpecifications(i).name,2) = "I-" Then
    DoCmd.RunSavedImportExport CurrentProject.ImportExportSpecifications(i).name

    Next i

    Dim z As Integer
    For z = 0 To CurrentProject.ImportExportSpecifications.count - 1
    Debug.Print CurrentProject.ImportExportSpecifications(z).name
    If Left(CurrentProject.ImportExportSpecifications(z).name,2) = "-" Then
    DoCmd.RunSavedImportExport CurrentProject.ImportExportSpecifications(z).name

    Next z

 Set i = Nothing
 Set z = Nothing

    objAccess.CloseCurrentDatabase

    ObjAccess.Quit
    Set ObjAccess = Nothing

Next

Set objFolder = Nothing
Set objFile = Nothing
Set objFSO = Nothing
</code>```

Update #3 :

Ok, my code currently looks like this.

```<code>option explicit

dim objFSO, objFolder, objFile, Access

Set objShell = CreateObject(“WScript.Shell”)

ScriptPath = WScript.ScriptFullName

Set objFSO = Server.CreateObject("Scripting.FileSystemObject")

Set ScriptFile = objFSO.GetFile(ScriptPath)

ScriptFolder = objFSO.GetParentFolderName(ScriptFile)

Set objFolder = ScriptFolder

For Each objFile in objFolder.Files
    If LCase(objFSO.GetExtentionName(objFile.Name)) = "accdb" Then
    Set Access = objFolder & objFile.Name
    Set objAccess = CreateObject("Access.Application")

    objAccess.OpenCurrentDatabase Access

    Dim i As Integer
    For i = 0 To CurrentProject.ImportExportSpecifications.count - 1
    Debug.Print CurrentProject.ImportExportSpecifications(i).name
    If Left(CurrentProject.ImportExportSpecifications(i).name,2) = "I-" Then
    DoCmd.RunSavedImportExport CurrentProject.ImportExportSpecifications(i).name

    Next i

    Dim z As Integer
    For z = 0 To CurrentProject.ImportExportSpecifications.count - 1
    Debug.Print CurrentProject.ImportExportSpecifications(z).name
    If Left(CurrentProject.ImportExportSpecifications(z).name,2) = "E-" Then
    DoCmd.RunSavedImportExport CurrentProject.ImportExportSpecifications(z).name

    Next z

 Set i = Nothing
 Set z = Nothing

    objAccess.CloseCurrentDatabase

    ObjAccess.Quit
    Set ObjAccess = Nothing
    Set Access = Nothing
    Set objFile = Nothing

Next

Set objFolder = Nothing
Set objFSO = Nothing
</code>```

The intention is to identify the folder the script is in, loop through the .accdb files and run all their imports then exports.
Im getting an error on line 1 and I cant for the life of me figure out why!?!
"Microsoft VBScript compilation error"

Any thoughts?

Alternatively, is there a better way to do this all together?

Thanks!

答:
```<code>Option Explicit
Dim objFSO, objFolder, objFile, oAccess, objShell, ScriptPath, ScriptFile, ScriptFolder, objAccess

Set objShell = CreateObject("WScript.Shell")

ScriptPath = WScript.ScriptFullName

Set objFSO = Server.CreateObject("Scripting.FileSystemObject")

Set ScriptFile = objFSO.GetFile(ScriptPath)

ScriptFolder = objFSO.GetParentFolderName(ScriptFile)

Set objFolder = ScriptFolder

For Each objFile in objFolder.Files
    If LCase(objFSO.GetExtentionName(objFile.Name)) = "accdb" Then
    Set oAccess = objFolder & objFile.Name
    Set objAccess = CreateObject("Access.Application")

    objAccess.OpenCurrentDatabase oAccess

    Dim i
    For i = 0 To CurrentProject.ImportExportSpecifications.count - 1
    Debug.Print CurrentProject.ImportExportSpecifications(i).name
    If Left(CurrentProject.ImportExportSpecifications(i).name,2) = "I-" Then
    DoCmd.RunSavedImportExport CurrentProject.ImportExportSpecifications(i).name
    End If

    **Next i**

    Dim z As Integer
    For z = 0 To CurrentProject.ImportExportSpecifications.count - 1
    Debug.Print CurrentProject.ImportExportSpecifications(z).name
    If Left(CurrentProject.ImportExportSpecifications(z).name,2) = "E-" Then
    DoCmd.RunSavedImportExport CurrentProject.ImportExportSpecifications(z).name
    End If

    Next z

 Set i = Nothing
 Set z = Nothing

    objAccess.CloseCurrentDatabase

    ObjAccess.Quit
    Set ObjAccess = Nothing
    Set oAccess = Nothing
    Set objFile = Nothing

Next

Set objFolder = Nothing
Set objFSO = Nothing
</code>```

Ok, I've moved on a little bit and played about with different encoding.
I'm currently using ANSI.

Im now getting an error on Line 31. char 7.

"Next i" for reference.
Unexpected end of Statement.

Any help?

Thanks,

Body:
Just learning some VBS and struggling a little with how to work a specific command for Access Exports/Imports.

In short, I need to loop through all .accb files in a folder. (I think I have that nailed)
For each of the files found, I need to open the file and run all saved imports, THEN saved exports.

I'll attach my code so far.

Dim objFSO, objFolder, objFile
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder("X:\Path\Path")

For Each objFile in objFolder.Files
    If LCase(objFSO.GetExtentionName(objFile.Name)) = "accb" Then

    'Loop for Opening Access DB and running all imports, then exports
    'Close Access DB

Next

Set objFolder = Nothing
Set objFile = Nothing
Set objFSO = Nothing

I've not managed to get very far with looping through the saved Imports/Exports in Access though and I've done a power of googling.

I can write each import/export command explicitly, but I'd much rather this script wouldn't have to be updated each time I added a new import or export.

Set objAccess = CreateObject("Access.Application")

objAccess.OpenCurrentDatabase "Path"

objAccess.DoCmd.RunSavedImportExport "xxxx"
objAccess.DoCmd.RunSavedImportExport "yyyy"

objAccess.CloseCurrentDatabase

ObjAccess.Quit
'Access.Application.Quit
Set ObjAccess = Nothing

I think the only way I can force it to run Imports first is via naming standards.
Lets say each Import/Export has the following naming standard.
I- name
E- name

I think another two For/If loops are required here, but unsure how to go about it.

Any thoughts?

Thank you Andre,

I'll update again when I've managed to test.
But this is what I now have.

Dim objFSO, objFolder, objFile
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder("X:\Path\Path")

For Each objFile in objFolder.Files
    If LCase(objFSO.GetExtentionName(objFile.Name)) = "accb" Then

    Set objAccess = CreateObject("Access.Application")

    objAccess.OpenCurrentDatabase "Path"

    Dim i As Integer
    For i = 0 To CurrentProject.ImportExportSpecifications.count - 1
    Debug.Print CurrentProject.ImportExportSpecifications(i).name
    If Left(CurrentProject.ImportExportSpecifications(i).name,2) = "I-" Then
    DoCmd.RunSavedImportExport CurrentProject.ImportExportSpecifications(i).name

    Next i

    Dim z As Integer
    For z = 0 To CurrentProject.ImportExportSpecifications.count - 1
    Debug.Print CurrentProject.ImportExportSpecifications(z).name
    If Left(CurrentProject.ImportExportSpecifications(z).name,2) = "-" Then
    DoCmd.RunSavedImportExport CurrentProject.ImportExportSpecifications(z).name

    Next z

 Set i = Nothing
 Set z = Nothing

    objAccess.CloseCurrentDatabase

    ObjAccess.Quit
    Set ObjAccess = Nothing

Next

Set objFolder = Nothing
Set objFile = Nothing
Set objFSO = Nothing

Update #3 :

Ok, my code currently looks like this.

option explicit

dim objFSO, objFolder, objFile, Access

Set objShell = CreateObject(“WScript.Shell”)

ScriptPath = WScript.ScriptFullName

Set objFSO = Server.CreateObject("Scripting.FileSystemObject")

Set ScriptFile = objFSO.GetFile(ScriptPath)

ScriptFolder = objFSO.GetParentFolderName(ScriptFile)

Set objFolder = ScriptFolder

For Each objFile in objFolder.Files
    If LCase(objFSO.GetExtentionName(objFile.Name)) = "accdb" Then
    Set Access = objFolder & objFile.Name
    Set objAccess = CreateObject("Access.Application")

    objAccess.OpenCurrentDatabase Access

    Dim i As Integer
    For i = 0 To CurrentProject.ImportExportSpecifications.count - 1
    Debug.Print CurrentProject.ImportExportSpecifications(i).name
    If Left(CurrentProject.ImportExportSpecifications(i).name,2) = "I-" Then
    DoCmd.RunSavedImportExport CurrentProject.ImportExportSpecifications(i).name

    Next i

    Dim z As Integer
    For z = 0 To CurrentProject.ImportExportSpecifications.count - 1
    Debug.Print CurrentProject.ImportExportSpecifications(z).name
    If Left(CurrentProject.ImportExportSpecifications(z).name,2) = "E-" Then
    DoCmd.RunSavedImportExport CurrentProject.ImportExportSpecifications(z).name

    Next z

 Set i = Nothing
 Set z = Nothing

    objAccess.CloseCurrentDatabase

    ObjAccess.Quit
    Set ObjAccess = Nothing
    Set Access = Nothing
    Set objFile = Nothing

Next

Set objFolder = Nothing
Set objFSO = Nothing

The intention is to identify the folder the script is in, loop through the .accdb files and run all their imports then exports.
Im getting an error on line 1 and I cant for the life of me figure out why!?!
"Microsoft VBScript compilation error"

Any thoughts?

Alternatively, is there a better way to do this all together?

Thanks!

Body:
Option Explicit
Dim objFSO, objFolder, objFile, oAccess, objShell, ScriptPath, ScriptFile, ScriptFolder, objAccess

Set objShell = CreateObject("WScript.Shell")

ScriptPath = WScript.ScriptFullName

Set objFSO = Server.CreateObject("Scripting.FileSystemObject")

Set ScriptFile = objFSO.GetFile(ScriptPath)

ScriptFolder = objFSO.GetParentFolderName(ScriptFile)

Set objFolder = ScriptFolder

For Each objFile in objFolder.Files
    If LCase(objFSO.GetExtentionName(objFile.Name)) = "accdb" Then
    Set oAccess = objFolder & objFile.Name
    Set objAccess = CreateObject("Access.Application")

    objAccess.OpenCurrentDatabase oAccess

    Dim i
    For i = 0 To CurrentProject.ImportExportSpecifications.count - 1
    Debug.Print CurrentProject.ImportExportSpecifications(i).name
    If Left(CurrentProject.ImportExportSpecifications(i).name,2) = "I-" Then
    DoCmd.RunSavedImportExport CurrentProject.ImportExportSpecifications(i).name
    End If

    **Next i**

    Dim z As Integer
    For z = 0 To CurrentProject.ImportExportSpecifications.count - 1
    Debug.Print CurrentProject.ImportExportSpecifications(z).name
    If Left(CurrentProject.ImportExportSpecifications(z).name,2) = "E-" Then
    DoCmd.RunSavedImportExport CurrentProject.ImportExportSpecifications(z).name
    End If

    Next z

 Set i = Nothing
 Set z = Nothing

    objAccess.CloseCurrentDatabase

    ObjAccess.Quit
    Set ObjAccess = Nothing
    Set oAccess = Nothing
    Set objFile = Nothing

Next

Set objFolder = Nothing
Set objFSO = Nothing

Ok, I've moved on a little bit and played about with different encoding.
I'm currently using ANSI.

Im now getting an error on Line 31. char 7.

"Next i" for reference.
Unexpected end of Statement.

Any help?

Thanks,


问:
How to implement a scheduled job as a microservice
I have a Spring Boot application which provides REST API for Angular web interface.

There is also a scheduled job that is currently in this Spring Boot application. The job is to fill in the database with some enities, let's say books (they are taken from an external source, more specifically, from a web-site). I want to place this job into a separate microservice.

The question is whether the microservice should work directly with the shared database or access the main application via REST. In the first case some (if not the all) models and services will be shared, it doesn't look good. But in the second case each access to database will go through the first application. Is that ok?

答:
Check out SOLID design principle.

S - is for Single Responsibility

There's also a pattern in microservice architecture with the very same name: Single Responsibility Principle

The single responsibility principle is one of the principles defined
  as part of the SOLID design pattern. It implies that a unit, either a
  class, a function, or a microservice, should have one and only one
  responsibility.

At no point in time, one microservice should have more than one
  responsibility.

You should decide which microservice should do what based on your application design, you definitely know it better than we do.

But having read your description I'd suggest the following:

your current database-microservice should be connected to DB and accept HTTP requests to save books in the database;

your new cronjob-microservice should start the job in time, get books from the website and send HTTP request to the database-microservice, hence it shouldn't be connected to the database.


问:
How to catch errors that occurred while sending an email in Alfresco's Activiti 6?
I need to send emails, and I use a service task for it:

```<code><serviceTask id="SendEmail_1" name="Sending a notification by email" activiti:type="mail">
  <documentation></documentation>
  <extensionElements>
    <activiti:field name="to">
      <activiti:expression><![CDATA[${to}]]></activiti:expression>
    </activiti:field>
    <activiti:field name="subject">
      <activiti:expression><![CDATA[${subject}]]></activiti:expression>
    </activiti:field>
    <activiti:field name="text">
      <activiti:expression><![CDATA[${body}]]></activiti:expression>
    </activiti:field>
    <activiti:field name="ignoreException">
      <activiti:string><![CDATA[true]]></activiti:string>
    </activiti:field>
    <activiti:field name="charset">
      <activiti:string><![CDATA[utf8]]></activiti:string>
    </activiti:field>
  </extensionElements>
</serviceTask>
</code>```

I also need to catch the errors that occur when sending mail. In the user guide, I read that in order to get a description of the error, you need to read from the variables of the process the value of the variable "exceptionVariableName". As you can see above, I added this to the service task, but so far I have not seen that it works. I tried to give him non-existent addresses of recipients, but there was no error. Does it even work? When does it work? Or is there another mechanism for getting error descriptions?

PS I use Activiti 6.0.0.

PSS I tried to add the block below in the "extensionElements" tag:

```<code><activiti:field name="exceptionVariableName">
  <activiti:string><![CDATA[error]]></activiti:string>
</activiti:field>
</code>```

And it also did not help me (for example, if the recipients are not correct).

PSSS I specified the wrong smtp server host (while creating the process configuration bean), and I got the error description (the Java code for receiving it is presented below), but it is uninformative.

```<code>public void logEmailSending(DelegateExecution execution) {
    Object error = execution.getVariable("error");
    if (error != null)
        logger.error("An error occurred while sending the email: " + error);
}
</code>```

it almost solved my problem, but, as I wrote above, I would like to be more concrete by mistake, and it still does not catch the error in the recipients addresses

答:
We hit the same wall in Activiti BPM 6.0.0. We solved our problem with the following steps.

Implementing a new service task e. g. SendEmailServiceTask which extends org.activiti.engine.impl.bpmn.behavior.MailActivityBehavior. This was necessary in order to override the method handleException which takes care of exception handling.

From the Activiti documentation 8.5.6. Email Task note that the mail task is not an official task of the BPMN 2.0 spec (and it does not have a dedicated icon as a consequence). Hence, in Activiti the mail task is implemented as a dedicated service task.

In our service task implementation we took care of:

Catching the EmailException, SendFailedException due to errors on SMTP.

Parsing informative data from exception and logging into application logs and user action journals.

Setting our custom BPM process variables in order to control the further execution flow.

Modifying the BPMN process definition, more precisely replacing the mail task activiti with our new service task from point 1.

In order to reproduce the same functionality of default mail task provided by Activiti we had to set class fields from, bcc, subject and text. The same values were set as on previously defined mail task.

And most important we had to set ignoreException to true in order to prevent BPM engine to throw ActivitiException due to exceptions on SMTP (invalid recipient, SMTP server domain, etc.) while sending email to the recipient.

Our business requirement was to either sucessfully send mail to all recipients in bcc field or fail. For this reason we didn't model our service task as multiinstance element.

I am absolutely aware there exist other solutions for this particular problem. We managed to solve it as described above.

Body:
I need to send emails, and I use a service task for it:

<serviceTask id="SendEmail_1" name="Sending a notification by email" activiti:type="mail">
  <documentation></documentation>
  <extensionElements>
    <activiti:field name="to">
      <activiti:expression><![CDATA[${to}]]></activiti:expression>
    </activiti:field>
    <activiti:field name="subject">
      <activiti:expression><![CDATA[${subject}]]></activiti:expression>
    </activiti:field>
    <activiti:field name="text">
      <activiti:expression><![CDATA[${body}]]></activiti:expression>
    </activiti:field>
    <activiti:field name="ignoreException">
      <activiti:string><![CDATA[true]]></activiti:string>
    </activiti:field>
    <activiti:field name="charset">
      <activiti:string><![CDATA[utf8]]></activiti:string>
    </activiti:field>
  </extensionElements>
</serviceTask>

I also need to catch the errors that occur when sending mail. In the user guide, I read that in order to get a description of the error, you need to read from the variables of the process the value of the variable "exceptionVariableName". As you can see above, I added this to the service task, but so far I have not seen that it works. I tried to give him non-existent addresses of recipients, but there was no error. Does it even work? When does it work? Or is there another mechanism for getting error descriptions?

PS I use Activiti 6.0.0.

PSS I tried to add the block below in the "extensionElements" tag:

<activiti:field name="exceptionVariableName">
  <activiti:string><![CDATA[error]]></activiti:string>
</activiti:field>

And it also did not help me (for example, if the recipients are not correct).

PSSS I specified the wrong smtp server host (while creating the process configuration bean), and I got the error description (the Java code for receiving it is presented below), but it is uninformative.

public void logEmailSending(DelegateExecution execution) {
    Object error = execution.getVariable("error");
    if (error != null)
        logger.error("An error occurred while sending the email: " + error);
}

it almost solved my problem, but, as I wrote above, I would like to be more concrete by mistake, and it still does not catch the error in the recipients addresses


问:
Job of Spring batch start automatically when application start. How to avoid id?
I'm doing a simple project in Spring to understand how Spring batch work. My project work but the job is executed when the application start and I do not want that. There is a way to avoid it?

I am already able to start the task when I want (for example go to a certain URL mapped by a @RestController). The only problem is that the batch job start when the application start too.

However my configuration code for Spring batch is:

```<code>@Configuration
@EnableBatchProcessing
public class BatchConfiguration {
    @Autowired
    public JobBuilderFactory jobBuilderFactory;

    @Autowired
    public StepBuilderFactory stepBuilderFactory;

    @Bean
    public FlatFileItemReader<Person> reader() {
      return new FlatFileItemReaderBuilder<Person>()
        .name("personItemReader")
        .resource(new ClassPathResource("sample-data.csv"))
        .delimited()
        .names(new String[]{"firstName", "lastName"})
        .fieldSetMapper(new BeanWrapperFieldSetMapper<Person>() {{
          setTargetType(Person.class);
        }})
        .build();
    }

    @Bean
    public PersonItemProcessor processor() {
      return new PersonItemProcessor();
    }

    @Bean
    public JdbcBatchItemWriter<Person> writer(DataSource dataSource) {
      return new JdbcBatchItemWriterBuilder<Person>()
        .itemSqlParameterSourceProvider(new BeanPropertyItemSqlParameterSourceProvider<>())
        .sql("INSERT INTO people (first_name, last_name) VALUES (:firstName, :lastName)")
        .dataSource(dataSource)
        .build();
    }

    @Bean
    public Job importUserJob(JobCompletionNotificationListener listener, Step step1) {
      return jobBuilderFactory.get("importUserJob")
        .incrementer(new RunIdIncrementer())
        .listener(listener)
        .start(step1)
//      .flow(step1)
//      .end()
        .build();
    }

    @Bean
    public Step step1(JdbcBatchItemWriter<Person> writer) {
      return stepBuilderFactory.get("step1")
        .<Person, Person> chunk(10)
        .reader(reader())
        .processor(processor())
        .writer(writer)
        .build();
    }
}
</code>```

I have a github repository public for this project:
https://github.com/Mazzotta13/SpringBatch.git

Thanks in advance.

答:
In your  application.properties add this

```<code>spring.batch.job.enabled=false
</code>```

Hope useful

Body:
I'm doing a simple project in Spring to understand how Spring batch work. My project work but the job is executed when the application start and I do not want that. There is a way to avoid it?

I am already able to start the task when I want (for example go to a certain URL mapped by a @RestController). The only problem is that the batch job start when the application start too.

However my configuration code for Spring batch is:

@Configuration
@EnableBatchProcessing
public class BatchConfiguration {
    @Autowired
    public JobBuilderFactory jobBuilderFactory;

    @Autowired
    public StepBuilderFactory stepBuilderFactory;

    @Bean
    public FlatFileItemReader<Person> reader() {
      return new FlatFileItemReaderBuilder<Person>()
        .name("personItemReader")
        .resource(new ClassPathResource("sample-data.csv"))
        .delimited()
        .names(new String[]{"firstName", "lastName"})
        .fieldSetMapper(new BeanWrapperFieldSetMapper<Person>() {{
          setTargetType(Person.class);
        }})
        .build();
    }

    @Bean
    public PersonItemProcessor processor() {
      return new PersonItemProcessor();
    }

    @Bean
    public JdbcBatchItemWriter<Person> writer(DataSource dataSource) {
      return new JdbcBatchItemWriterBuilder<Person>()
        .itemSqlParameterSourceProvider(new BeanPropertyItemSqlParameterSourceProvider<>())
        .sql("INSERT INTO people (first_name, last_name) VALUES (:firstName, :lastName)")
        .dataSource(dataSource)
        .build();
    }

    @Bean
    public Job importUserJob(JobCompletionNotificationListener listener, Step step1) {
      return jobBuilderFactory.get("importUserJob")
        .incrementer(new RunIdIncrementer())
        .listener(listener)
        .start(step1)
//      .flow(step1)
//      .end()
        .build();
    }

    @Bean
    public Step step1(JdbcBatchItemWriter<Person> writer) {
      return stepBuilderFactory.get("step1")
        .<Person, Person> chunk(10)
        .reader(reader())
        .processor(processor())
        .writer(writer)
        .build();
    }
}

I have a github repository public for this project:
https://github.com/Mazzotta13/SpringBatch.git

Thanks in advance.

Body:
In your  application.properties add this

spring.batch.job.enabled=false

Hope useful


问:
Grep for exact match when there is no more words
I have two strings like below:

Word

More than one word

How to use grep to match only with the first one?
I would like to have results when there is no more characters around the word I'm searching for.
When there is a string like the second one, it should find nothing.

Is it possible to achieve with grep?

答:
The -x option says the regex needs to match the entire line.

```<code>grep -x 'Word' file
</code>```

Body:
The -x option says the regex needs to match the entire line.

grep -x 'Word' file


问:
SPFx: Add a new item to existing List Folder (using pnp)
Does anyone know how to add a new item to a List Folder in Sharepoint Framework?

In this way I can add the item to the list MyList:

```<code>let list = pnp.sp.web.lists.getByTitle("MyList");

list.items.add({
      Title: "itemName"
      }).then(r => {

      console.log(r);
})
</code>```

But I need it being created inside the folder MyList\MyFolder.

I have tried retrieving the folder in this way:

var folder= sp.web.lists.getByTitle("MyList").rootFolder.folders.getByName("MyFolder");

but I cannot find a way to add items inside.

答:
As Jackson wrote, it seems that it's not possibile to add an item to a List Folder with the sp-pnp-js library.

So, doing some searches I have found that it is possible to use addValidateUpdateItemUsingPath for this purpose:

```<code>const _spPageContextInfo=this.context.pageContext.legacyPageContext;
const webUrl = _spPageContextInfo.webAbsoluteUrl;

const listPath=webUrl+"/Lists/MyListInternalName";
const folderName="MyFolderName";

sp.site.rootWeb.lists.getByTitle("MyList").addValidateUpdateItemUsingPath([
    { FieldName: 'Column1', FieldValue: 'Value1'},
    { FieldName: 'Column2', FieldValue: 'Value2'}]
  ,`${listPath}/${folderName}`).then(console.log);
</code>```

Then, it took me a little bit of extra time to understand how to set the FieldValue for User fields while using addValidateUpdateItemUsingPath (in this case using the user ID -as usual- to retrieve the user was not working).
But I have found this way:

```<code>{FieldName: 'ColumnUser',
FieldValue: JSON.stringify([{"Key": "i:0#.f|membership|"+"MyUserEmail"}])}
</code>```

Body:
Does anyone know how to add a new item to a List Folder in Sharepoint Framework?

In this way I can add the item to the list MyList:

let list = pnp.sp.web.lists.getByTitle("MyList");

list.items.add({
      Title: "itemName"
      }).then(r => {

      console.log(r);
})

But I need it being created inside the folder MyList\MyFolder.

I have tried retrieving the folder in this way:

var folder= sp.web.lists.getByTitle("MyList").rootFolder.folders.getByName("MyFolder");

but I cannot find a way to add items inside.

Body:
As Jackson wrote, it seems that it's not possibile to add an item to a List Folder with the sp-pnp-js library.

So, doing some searches I have found that it is possible to use addValidateUpdateItemUsingPath for this purpose:

const _spPageContextInfo=this.context.pageContext.legacyPageContext;
const webUrl = _spPageContextInfo.webAbsoluteUrl;

const listPath=webUrl+"/Lists/MyListInternalName";
const folderName="MyFolderName";

sp.site.rootWeb.lists.getByTitle("MyList").addValidateUpdateItemUsingPath([
    { FieldName: 'Column1', FieldValue: 'Value1'},
    { FieldName: 'Column2', FieldValue: 'Value2'}]
  ,`${listPath}/${folderName}`).then(console.log);

Then, it took me a little bit of extra time to understand how to set the FieldValue for User fields while using addValidateUpdateItemUsingPath (in this case using the user ID -as usual- to retrieve the user was not working).
But I have found this way:

{FieldName: 'ColumnUser',
FieldValue: JSON.stringify([{"Key": "i:0#.f|membership|"+"MyUserEmail"}])}


问:
How do you get the nth child of a class in jquery
Normally I would do this in the console:

```<code>$('element:nth-child(which child)')
</code>```

For a class selector I have tried this:

```<code>$('.class:nth-child(2)')
</code>```

This doesn't seem to work, is it even possible to get an nth class? It's just that there are 4 lots with the same class name, and there is no way to select it to then get the button I wish to get.

答:
This should be done with

```<code>$(" ... ").get(n);
</code>```

If you want the jQuery object, not the DOM object, you should use

```<code>$(" ... ").eq(n);
</code>```

This is from the jQuery documentation

Body:
Normally I would do this in the console:

$('element:nth-child(which child)')

For a class selector I have tried this:

$('.class:nth-child(2)')

This doesn't seem to work, is it even possible to get an nth class? It's just that there are 4 lots with the same class name, and there is no way to select it to then get the button I wish to get.

Body:
This should be done with

$(" ... ").get(n);

If you want the jQuery object, not the DOM object, you should use

$(" ... ").eq(n);

This is from the jQuery documentation


问:
Is a "master preferences" class a good idea?
I have a class that manages user preferences for a large software project.  Any class in the project that may need to set or retrieve a user preference from a persistent store is to call the static methods on this class.  This centralized management allows the preferences to be completely wiped programmatically - which would be impossible if each pref was handled close to its use code, sprinkled throughout the project.

I ran into another implication of the centralization design in the course of this.  The software has a public API.  That API can be provided by itself in a jar.  Classes in that API might refer to the pref management class.  So, the pref manager has to go in the API jar.

Each preference might have a default value.  Upon software startup, that default might be computed.  The algorithm depends on the preference, and thus tends to reside near the use code.  So if the pref manager needs to come up with a default, it calls the class in question.

But now that pref manager has become an "octopus class", sucking in all sorts of classes into the API jar that shouldn't be there.  If it doesn't, then programs using the API jar quickly run into ClassDef exceptions.  If it does, then the API jar is now bloated, as each of those other classes may refer to still others.

In general, do other Java programmers manage their preferences with a centralized class?

Does it make sense to distribute that static pref management class as part of a public API?

Should that pref manager be the keeper of the code for determining defaults?

答:
I deleted my first answer since I misunderstood what the author was asking.

To actually address the actual question--it feels like your desire to place preferences (and the calculation of the default values) with the code that uses them makes sense.

Could you meet both requirements by using a preferences container class for each area that follows a pattern for that area, but having it register with a "Global" preference object collection?

Your global collection could do things like iterate over each set of preferences and reset it to defaults but your preferences themselves would still be locally defined and maintained so that it doesn't spider out into other parts of the code.

The only problem I can see is that if you allow the preference object to register itself when instantiated, you run the risk of trying to "reset to defaults" with some of the preferences not instantiated yet.

I suppose this could be fixed by having the main "preference" class instantiate all the others, then any piece of code could retrieve it's local preference object from the central one though a static getter.

This seems to be a lot like how some loggers work.  There is a central mechanism for maintaining log levels, output streams and such, but each class has it's own instance of a "log" method and logs to it.

I hope this was more on target.  Oh, I also agree with the accepted answer, don't ever make all your methods public static, always use a getter--you'll be glad you did some day.

OwnerDisplayName: Paul Brinkley

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Bill K


问:
Apple pay with stripe in Cordova is getting payment not complete
This is my code, and I am getting error payment not complete. I am using apple pay with stripe in Condova.

I have used both the plugins but gave me error. Please also clarify how do I get stripe token.

ApplePay.makePaymentRequest($scope.order).then((paymentResponse) passing $scope not getting paymentResponse

```<code>      ApplePay.canMakePayments({
    // supportedNetworks should not be an empty array. The supported networks currently are: amex, discover, masterCard, visa
    supportedNetworks: ['visa', 'amex', 'masterCard', 'discover'],
    // when merchantCapabilities is passed in, supportedNetworks must also be provided. Valid values: 3ds, debit, credit, emv
    merchantCapabilities: ['3DS', 'debit', 'credit', 'emv']
    }).then((message) => {
    alert(message);
    $scope.order = {};
    $scope.order.items = [{
    label: 'Subscription Charge',
    amount: 1.00
    }];
    $scope.order.shippingMethods = [
    {
    "label": "Free Shipping",
    "detail": "Subscription plan",
    "amount": "0.00",
    "identifier": "FreeShip"
    }
    ];
    $scope.order.supportedNetworks = ['visa', 'masterCard','discover'];
    $scope.order.merchantCapabilities = ['3DS', 'debit', 'credit'];
    $scope.order.merchantIdentifier = "merchant.com.appguys.foodroamer";
    $scope.order.currencyCode = 'USD';
    $scope.order.countryCode = 'US';
    $scope.order.billingAddressRequirement = 'none';
    $scope.order.shippingAddressRequirement = 'none';
    $scope.order.shippingType = 'service';
    ApplePay.makePaymentRequest($scope.order).then((paymentResponse) => {
    alert(JSON.stringify(paymentResponse));
    alert("Token Here",paymentResponse.paymentData);
    httpService.userPost($scope.base_url+'domakeTestPayment',{'token':paymentResponse.paymentData}).then(function(paymentResponse){
    alert(JSON.stringify(paymentResponse));
    });
    }).catch((e) => {
    alert(4);
    alert(e);
    // Failed to open the Apple Pay sheet, or the user cancelled the payment.
    })
    }).catch((message) => {
    alert(2);
    alert(message);
    console.log(message);
    // There is an issue, examine the message to see the details, will be:
    // 'This device cannot make payments.''
    // 'This device can make payments but has no supported cards'
    });

    <plugin name="cordova-plugin-stripe-apple-pay" spec="https://github.com/asangadev/cordova-plugin-stripe-apple-pay">
    <variable name="STRIPE_LIVE_PUBLISHABLE_KEY" value="xxxxxxxxxxx" />
    <variable name="STRIPE_TEST_PUBLISHABLE_KEY" value="xxxxxxxx" />
    <variable name="APPLE_MERCHANT_IDENTIFIER" value="xxxxxxxxxxx" />
    </plugin>
</code>```

答: I used Braintree instead of stripe. And remember I also changed country to US in Apple id, and in sandbox too

Body:
This is my code, and I am getting error payment not complete. I am using apple pay with stripe in Condova.

I have used both the plugins but gave me error. Please also clarify how do I get stripe token.

ApplePay.makePaymentRequest($scope.order).then((paymentResponse) passing $scope not getting paymentResponse

      ApplePay.canMakePayments({
    // supportedNetworks should not be an empty array. The supported networks currently are: amex, discover, masterCard, visa
    supportedNetworks: ['visa', 'amex', 'masterCard', 'discover'],
    // when merchantCapabilities is passed in, supportedNetworks must also be provided. Valid values: 3ds, debit, credit, emv
    merchantCapabilities: ['3DS', 'debit', 'credit', 'emv']
    }).then((message) => {
    alert(message);
    $scope.order = {};
    $scope.order.items = [{
    label: 'Subscription Charge',
    amount: 1.00
    }];
    $scope.order.shippingMethods = [
    {
    "label": "Free Shipping",
    "detail": "Subscription plan",
    "amount": "0.00",
    "identifier": "FreeShip"
    }
    ];
    $scope.order.supportedNetworks = ['visa', 'masterCard','discover'];
    $scope.order.merchantCapabilities = ['3DS', 'debit', 'credit'];
    $scope.order.merchantIdentifier = "merchant.com.appguys.foodroamer";
    $scope.order.currencyCode = 'USD';
    $scope.order.countryCode = 'US';
    $scope.order.billingAddressRequirement = 'none';
    $scope.order.shippingAddressRequirement = 'none';
    $scope.order.shippingType = 'service';
    ApplePay.makePaymentRequest($scope.order).then((paymentResponse) => {
    alert(JSON.stringify(paymentResponse));
    alert("Token Here",paymentResponse.paymentData);
    httpService.userPost($scope.base_url+'domakeTestPayment',{'token':paymentResponse.paymentData}).then(function(paymentResponse){
    alert(JSON.stringify(paymentResponse));
    });
    }).catch((e) => {
    alert(4);
    alert(e);
    // Failed to open the Apple Pay sheet, or the user cancelled the payment.
    })
    }).catch((message) => {
    alert(2);
    alert(message);
    console.log(message);
    // There is an issue, examine the message to see the details, will be:
    // 'This device cannot make payments.''
    // 'This device can make payments but has no supported cards'
    });

    <plugin name="cordova-plugin-stripe-apple-pay" spec="https://github.com/asangadev/cordova-plugin-stripe-apple-pay">
    <variable name="STRIPE_LIVE_PUBLISHABLE_KEY" value="xxxxxxxxxxx" />
    <variable name="STRIPE_TEST_PUBLISHABLE_KEY" value="xxxxxxxx" />
    <variable name="APPLE_MERCHANT_IDENTIFIER" value="xxxxxxxxxxx" />
    </plugin>


问:
Type-level induction on KnownNats: Overlapping instances
I'm trying to figure out how to do type-level induction on KnownNats. A toy example, summing up sized vectors from vector-sized:

{-# LANGUAGE FlexibleInstances, UndecidableInstances #-}
{-# LANGUAGE TypeFamilies, TypeApplications, TypeOperators #-}
{-# LANGUAGE RankNTypes, DataKinds #-}

module Main where

import GHC.TypeNats
import qualified Data.Vector.Sized as V

class KnownNat d => SumVectorSized d where
  sumVS :: V.Vector d Int -> Int

instance SumVectorSized 0 where
  sumVS _ = 0

instance (SumVectorSized d, KnownNat d', d' ~ (1+d)) => SumVectorSized d' where
  sumVS vec = V.head vec + sumVS (V.tail vec)

main = do
  let Just vec = V.fromList @4 [1..4]
  print $ sumVS vec
```

<p>When compiled, this gives an error:</p>

```• Overlapping instances for SumVectorSized 0
    arising from a use of ‘sumVS’
  Matching instances:
    instance SumVectorSized 0 -- Defined at src/Main.hs:14:10
    instance (SumVectorSized d, KnownNat d', d' ~ (1 + d)) =>
             SumVectorSized d'
      -- Defined at src/Main.hs:17:10
```

I think the problem is that GHC doesn't know that (1+d) is not 0 for any d. How can I get across that the instances don't overlap? Or is there another way to do this kind of induction?

答:
I think the problem is that GHC doesn't know that (1+d) is not 0 for any d.

To determine overlap, you only look to the right of =>. These overlap:

```<code>SumVectorSized 0
SumVectorSized d'
</code>```

How can I get across that the instances don't overlap?

Add {-# OVERLAPPING #-} to the second instance.

Or is there another way to do this kind of induction?

This is one of many tricks to palliate the lack of dependent types in Haskell. A reasonable solution is to turn to a dependently typed language like Idris or Agda, where induction can actually be formulated as a plain function.

A less radical alternative is to go through a Peano-like singleton type:

data NatS (n :: Nat) where
  ZS :: NatS 0
  SS :: (n' ~ (n-1), n ~ (1 + n')) => NatS n' -> NatS n
```

<p>The technique you described requires a new type class for every operation you want to perform, requiring duplication of that unsightly trick with overlapping instances. You only need one of those classes to convert a <code>KnownNat</code> constraint into a <code>NatS</code> singleton value, and then everything else is a plain function:</p>

<pre class="lang-hs prettyprint-override"><code>sumVS :: NatS n -> V.Vector n Int -> Int
sumVS ZS _ = 0
sumVS (SS n) v = V.head v + sumVS (V.tail v)
</code>```

Body:
I'm trying to figure out how to do type-level induction on KnownNats. A toy example, summing up sized vectors from vector-sized:

{-# LANGUAGE FlexibleInstances, UndecidableInstances #-}
{-# LANGUAGE TypeFamilies, TypeApplications, TypeOperators #-}
{-# LANGUAGE RankNTypes, DataKinds #-}

module Main where

import GHC.TypeNats
import qualified Data.Vector.Sized as V

class KnownNat d => SumVectorSized d where
  sumVS :: V.Vector d Int -> Int

instance SumVectorSized 0 where
  sumVS _ = 0

instance (SumVectorSized d, KnownNat d', d' ~ (1+d)) => SumVectorSized d' where
  sumVS vec = V.head vec + sumVS (V.tail vec)

main = do
  let Just vec = V.fromList @4 [1..4]
  print $ sumVS vec

When compiled, this gives an error:

• Overlapping instances for SumVectorSized 0
    arising from a use of ‘sumVS’
  Matching instances:
    instance SumVectorSized 0 -- Defined at src/Main.hs:14:10
    instance (SumVectorSized d, KnownNat d', d' ~ (1 + d)) =>
             SumVectorSized d'
      -- Defined at src/Main.hs:17:10

I think the problem is that GHC doesn't know that (1+d) is not 0 for any d. How can I get across that the instances don't overlap? Or is there another way to do this kind of induction?

Body:
I think the problem is that GHC doesn't know that (1+d) is not 0 for any d.

To determine overlap, you only look to the right of =>. These overlap:

SumVectorSized 0
SumVectorSized d'

How can I get across that the instances don't overlap?

Add {-# OVERLAPPING #-} to the second instance.

Or is there another way to do this kind of induction?

This is one of many tricks to palliate the lack of dependent types in Haskell. A reasonable solution is to turn to a dependently typed language like Idris or Agda, where induction can actually be formulated as a plain function.

A less radical alternative is to go through a Peano-like singleton type:

data NatS (n :: Nat) where
  ZS :: NatS 0
  SS :: (n' ~ (n-1), n ~ (1 + n')) => NatS n' -> NatS n

The technique you described requires a new type class for every operation you want to perform, requiring duplication of that unsightly trick with overlapping instances. You only need one of those classes to convert a KnownNat constraint into a NatS singleton value, and then everything else is a plain function:

sumVS :: NatS n -> V.Vector n Int -> Int
sumVS ZS _ = 0
sumVS (SS n) v = V.head v + sumVS (V.tail v)


问:
How to sort entries in row of a tibble in dplyr?
As an example:

```<code>     V1    V2    V3     X
1     1     5     4    "asa"
2     5     2     3    "sdsf"
</code>```

should become

```<code>     V1    V2    V3     X
1     1     4     5    "asa"
2     2     3     5    "sdsf"
</code>```

Looking for short and fast solutions. It takes quite a while with a for loop and base R commands for a dataframe with ~150,000 rows.

答:
```<code>d <- data.frame(
  a=c(1,3),
  b=c(5,2),
  c=c(9,1),
  d=c("as","dasd")
)

d

  a b c    d
1 1 5 9   as
2 3 2 1 dasd

as.data.frame(t(d)) %>% mutate_all(sort) %>% t() %>% as.data.frame()

   V1 V2 V3   V4
V1  1  5  9   as
V2  1  2  3 dasd
</code>```

Of course, the column names of the initial data frame become meaningless.

Body:
As an example:

     V1    V2    V3     X
1     1     5     4    "asa"
2     5     2     3    "sdsf"

should become

     V1    V2    V3     X
1     1     4     5    "asa"
2     2     3     5    "sdsf"

Looking for short and fast solutions. It takes quite a while with a for loop and base R commands for a dataframe with ~150,000 rows.

Body:
d <- data.frame(
  a=c(1,3),
  b=c(5,2),
  c=c(9,1),
  d=c("as","dasd")
)

d

  a b c    d
1 1 5 9   as
2 3 2 1 dasd

as.data.frame(t(d)) %>% mutate_all(sort) %>% t() %>% as.data.frame()

   V1 V2 V3   V4
V1  1  5  9   as
V2  1  2  3 dasd

Of course, the column names of the initial data frame become meaningless.


问:
How to avoid CTQ operator in DB2 Blu with substr?
I'm working with DB2 Blu, and I often have problems in my queries plan with SUBSTR as the CTQ operator is not high enough.

Here is an example :

```<code>select
coalesce(annee,annee_semaine),
count(JOUR_OUVRE)
from d_tps_calendrier
group by grouping sets((annee),(annee_semaine))
</code>```

The query plan is all right :

```<code>Rows
            RETURN
            (   1)
             Cost
              I/O
              |
             2701
            L   TQ
            (   2)
            334.257
              224
              |
             2701
              C TQ
            (   3)
            333.573
              224
              |
             2701
            UNION
            (   4)
            332.721
              224
            /-+--\
         2649      52
        GRPBY    GRPBY
        (   5)   (  10)
        166.197  166.107
          112      112
          |        |
         22310    22310
        TBSCAN   TBSCAN
        (   6)   (  11)
        165.176  165.176
          112      112
          |        |
         22310    22310
        TEMP     TEMP
        (   7)   (   7)
        147.121  147.121
          112      112
          |
         22310
        GRPBY
        (   8)
        134.404
          112
          |
         22310
        TBSCAN
        (   9)
        132.702
          112
          |
         22310
  CO-TABLE: INFIFZ00
 D_TPS_CALENDRIER_INF
          Q1
</code>```

Now, what I really want to do is a group by the first 3 characters of annee_semaine :

```<code>select
coalesce(annee,substr(annee_semaine,1,3)),
count(JOUR_OUVRE)
from d_tps_calendrier
group by grouping sets((annee),(substr(annee_semaine,1,3)))
</code>```

And now in the query plan, the group by and union are done after the CTQ operator

```<code>Rows
            RETURN
            (   1)
             Cost
              I/O
              |
             2701
            UNION
            (   2)
            431.235
              224
            /-+--\
         2649      52
        GRPBY    GRPBY
        (   3)   (  14)
        220.453  210.366
          112      112
          |        |
         2649     22310
        TBSCAN   TBSCAN
        (   4)   (  15)
        220.219  208.372
          112      112
          |        |
         2649     22310
        SORT     TEMP
        (   5)   (   7)
        220.219  190.317
          112      112
          |
         22310
        TBSCAN
        (   6)
        208.372
          112
          |
         22310
        TEMP
        (   7)
        190.317
          112
          |
         22310
        LM  TQ
        (   8)
        181.039
          112
          |
         22310
        GRPBY
        (   9)
        165.712
          112
          |
         22310
        TBSCAN
        (  10)
        163.749
          112
          |
         22310
        SORT
        (  11)
        161.817
          112
          |
         22310
          C TQ
        (  12)
        132.866
          112
          |
         22310
        TBSCAN
        (  13)
        132.702
          112
          |
         22310
  CO-TABLE: INFIFZ00
 D_TPS_CALENDRIER_INF
          Q1
</code>```

I tried with left instead of substr, without success. Is there a good pratice to deal with substr in DB2 Blu ?

In others cases, I was able to directly put de substr in one column in the table, mais in this case it is not possible.

答:
One option is to add a column to the table that is generated always, something like:

```<code>annee_semaine3 char(3) generated always as (substring(annee_semaine,1,3)) implicitly hidden
</code>```

You can then group by this hidden column.

```<code>select
coalesce(annee,substr(annee_semaine,1,3)),
count(JOUR_OUVRE)
from d_tps_calendrier
group by grouping sets((annee),(annee_semaine3))
</code>```

You can also explicitly reference it in the select clause to avoid that calculation.

Because the column is hidden, operations like select * will no include it; it must be explicitly named.

Body:
I'm working with DB2 Blu, and I often have problems in my queries plan with SUBSTR as the CTQ operator is not high enough.

Here is an example :

select
coalesce(annee,annee_semaine),
count(JOUR_OUVRE)
from d_tps_calendrier
group by grouping sets((annee),(annee_semaine))

The query plan is all right :

Rows
            RETURN
            (   1)
             Cost
              I/O
              |
             2701
            L   TQ
            (   2)
            334.257
              224
              |
             2701
              C TQ
            (   3)
            333.573
              224
              |
             2701
            UNION
            (   4)
            332.721
              224
            /-+--\
         2649      52
        GRPBY    GRPBY
        (   5)   (  10)
        166.197  166.107
          112      112
          |        |
         22310    22310
        TBSCAN   TBSCAN
        (   6)   (  11)
        165.176  165.176
          112      112
          |        |
         22310    22310
        TEMP     TEMP
        (   7)   (   7)
        147.121  147.121
          112      112
          |
         22310
        GRPBY
        (   8)
        134.404
          112
          |
         22310
        TBSCAN
        (   9)
        132.702
          112
          |
         22310
  CO-TABLE: INFIFZ00
 D_TPS_CALENDRIER_INF
          Q1

Now, what I really want to do is a group by the first 3 characters of annee_semaine :

select
coalesce(annee,substr(annee_semaine,1,3)),
count(JOUR_OUVRE)
from d_tps_calendrier
group by grouping sets((annee),(substr(annee_semaine,1,3)))

And now in the query plan, the group by and union are done after the CTQ operator

Rows
            RETURN
            (   1)
             Cost
              I/O
              |
             2701
            UNION
            (   2)
            431.235
              224
            /-+--\
         2649      52
        GRPBY    GRPBY
        (   3)   (  14)
        220.453  210.366
          112      112
          |        |
         2649     22310
        TBSCAN   TBSCAN
        (   4)   (  15)
        220.219  208.372
          112      112
          |        |
         2649     22310
        SORT     TEMP
        (   5)   (   7)
        220.219  190.317
          112      112
          |
         22310
        TBSCAN
        (   6)
        208.372
          112
          |
         22310
        TEMP
        (   7)
        190.317
          112
          |
         22310
        LM  TQ
        (   8)
        181.039
          112
          |
         22310
        GRPBY
        (   9)
        165.712
          112
          |
         22310
        TBSCAN
        (  10)
        163.749
          112
          |
         22310
        SORT
        (  11)
        161.817
          112
          |
         22310
          C TQ
        (  12)
        132.866
          112
          |
         22310
        TBSCAN
        (  13)
        132.702
          112
          |
         22310
  CO-TABLE: INFIFZ00
 D_TPS_CALENDRIER_INF
          Q1

I tried with left instead of substr, without success. Is there a good pratice to deal with substr in DB2 Blu ?

In others cases, I was able to directly put de substr in one column in the table, mais in this case it is not possible.

Body:
One option is to add a column to the table that is generated always, something like:

annee_semaine3 char(3) generated always as (substring(annee_semaine,1,3)) implicitly hidden

You can then group by this hidden column.

select
coalesce(annee,substr(annee_semaine,1,3)),
count(JOUR_OUVRE)
from d_tps_calendrier
group by grouping sets((annee),(annee_semaine3))

You can also explicitly reference it in the select clause to avoid that calculation.

Because the column is hidden, operations like select * will no include it; it must be explicitly named.


问:
Java: overriding equals method doesn't do the trick when looking for a key of hashtable?
I have a hashtable looking like this:

```<code>Hashtable<Mapping, Integer> mappingCount = new Hashtable<Mapping, Integer>();
</code>```

I want to use this code:

```<code>if (mappingCount.get(currentMapping) != null)
    mappingCount.put(currentMapping, mappingCount.get(currentMapping) + 1);
else
    mappingCount.put(currentMapping, 1);
</code>```

In order to be able to get the value from the hashtable, for the class Mapping I did the following:

```<code>@Override
public boolean equals(Object obj) {
    return ((Mapping)obj).mappingXML.equals(this.mappingXML);
}
</code>```

However, this doesn't do the trick since mappingCount.get(currentMapping) always results in null. To be sure that something's not wrong, I did the following:

```<code>if (aaa.contains(currentMapping.getMappingXML()))
    System.out.println("found it!");
else
    aaa.add(currentMapping.getMappingXML());
</code>```

where aaa is List<String> aaa = new ArrayList<String>(). Of course, found it is printed many times. What am I doing wrong?

答:
All of the recommendations to override equals and hash code correctly are spot on; Joshua Bloch tells you how to do it properly.

But an equally important requirement is that keys in maps must be immutable.  If your class can change its values, then the equals and hash code can change after you add it to the map; disaster ensues.

Body:
I have a hashtable looking like this:

Hashtable<Mapping, Integer> mappingCount = new Hashtable<Mapping, Integer>();

I want to use this code:

if (mappingCount.get(currentMapping) != null)
    mappingCount.put(currentMapping, mappingCount.get(currentMapping) + 1);
else
    mappingCount.put(currentMapping, 1);

In order to be able to get the value from the hashtable, for the class Mapping I did the following:

@Override
public boolean equals(Object obj) {
    return ((Mapping)obj).mappingXML.equals(this.mappingXML);
}

However, this doesn't do the trick since mappingCount.get(currentMapping) always results in null. To be sure that something's not wrong, I did the following:

if (aaa.contains(currentMapping.getMappingXML()))
    System.out.println("found it!");
else
    aaa.add(currentMapping.getMappingXML());

where aaa is List<String> aaa = new ArrayList<String>(). Of course, found it is printed many times. What am I doing wrong?


问:
How to show a users last visited pages in wp / buddypress?
im trying to figure out how i can show the last 3-5 or so pages within my site a person has visited. I did some searching, and I couldn't find a WP plugin that does so, if anyone knows of one, please point me in that direction :) if not, I'll have to write it from scratch, and thats where i'll need the help.

I've been trying to understand the DB and how it works. I'm assuming that this is where the magic will happen, with PHP, unless there is a javascript option using cookies to do it.

Im open to all ideas :P & Thank you

答:
I'm going to update and translate the code above for WordPress 5+ because the original question has the wordpress tag. Note that you don't need session_start() anywhere.

Here it goes, add the code below to your singular.php template (or single.php + page.php templates, depending on what you need):

/**
 * Store last visited ID (WordPress ID)
 */
function so7035465_store_last_id() {
    global $post;

    $postId = $post->ID; // or get the post ID from your template

    $historyMaxUrl = 3; // number of URLs in the history array
    $history = (array) $_SESSION['history'];

    array_unshift($history, $postId);

    if (count($history) > $historyMaxUrl) {
        array_pop($history);
    }

    $_SESSION['history'] = $history;
}

// Display latest viewed posts (or pages) wherever you want
echo '
';
    foreach ($_SESSION['history'] as $lastViewedId) {
        echo '
' . get_permalink($lastViewedId) . '
';
    }
echo '
';
```

You can also store latest viewed custom post types (CPT) by placing the so7035465_store_last_id() function in your single-cpt.php template.

You can also add it to a hook or inject it in your template as an action, but that is beyond the scope of this question.

Body:
I'm going to update and translate the code above for WordPress 5+ because the original question has the wordpress tag. Note that you don't need session_start() anywhere.

Here it goes, add the code below to your singular.php template (or single.php + page.php templates, depending on what you need):

/**
 * Store last visited ID (WordPress ID)
 */
function so7035465_store_last_id() {
    global $post;

    $postId = $post->ID; // or get the post ID from your template

    $historyMaxUrl = 3; // number of URLs in the history array
    $history = (array) $_SESSION['history'];

    array_unshift($history, $postId);

    if (count($history) > $historyMaxUrl) {
        array_pop($history);
    }

    $_SESSION['history'] = $history;
}

// Display latest viewed posts (or pages) wherever you want
echo '<ul>';
    foreach ($_SESSION['history'] as $lastViewedId) {
        echo '<li>' . get_permalink($lastViewedId) . '</li>';
    }
echo '</ul>';

You can also store latest viewed custom post types (CPT) by placing the so7035465_store_last_id() function in your single-cpt.php template.

You can also add it to a hook or inject it in your template as an action, but that is beyond the scope of this question.


问:
Oracle SQL time difference in HH:MM:SS
I am trying to get time difference in Oracle database. The time difference for all the rows is okay except for one row. Here is the query

```<code>SELECT MAX(REGEXP_SUBSTR (CAST(TO_DATE(call_end, 'YYYY/MM/DD HH24:MI:SS') AS TIMESTAMP) - CAST(TO_DATE(call_start, 'YYYY/MM/DD HH24:MI:SS') AS TIMESTAMP), '\d{2}:\d{2}:\d{2}')) AS call_time
FROM calls
</code>```

The time difference occurs with the following row:

call_end: '2020-02-20 13:00:20'

call_start: '2020-02-20 12:56:03'

The returned result is '11:55:43' which is wrong. As the correct answer should be '00:04:17'

答:
I'm not sure if you want the result as an interval or timestamp, but this should do what you want:

```<code>select t.*, call_end - call_start,
       substr(to_char(call_end - call_start, 'HH24:MI:SS'), 12, 8) as str    from (select timestamp '2020-02-20 13:00:20.000' as call_end,
             timestamp '2020-02-20 12:56:03.000' as call_start
      from dual) t
</code>```

Here is a db<>fiddle.

Title: Oracle SQL time difference in HH:MM:SS

Body:
I am trying to get time difference in Oracle database. The time difference for all the rows is okay except for one row. Here is the query

SELECT MAX(REGEXP_SUBSTR (CAST(TO_DATE(call_end, 'YYYY/MM/DD HH24:MI:SS') AS TIMESTAMP) - CAST(TO_DATE(call_start, 'YYYY/MM/DD HH24:MI:SS') AS TIMESTAMP), '\d{2}:\d{2}:\d{2}')) AS call_time
FROM calls

The time difference occurs with the following row:

call_end: '2020-02-20 13:00:20'

call_start: '2020-02-20 12:56:03'

The returned result is '11:55:43' which is wrong. As the correct answer should be '00:04:17'

Body:
I'm not sure if you want the result as an interval or timestamp, but this should do what you want:

select t.*, call_end - call_start,
       substr(to_char(call_end - call_start, 'HH24:MI:SS'), 12, 8) as str    from (select timestamp '2020-02-20 13:00:20.000' as call_end,
             timestamp '2020-02-20 12:56:03.000' as call_start
      from dual) t

Here is a db<>fiddle.


问:
How to add sessionDelegate option on SocketManager's config Swift
I'm tryng to connect to a self signed SSL URL.
But when I add sessionDelegate as option it's not working.

```<code>import Foundation
import SocketIO
import UIKit
class SocketM: NSObject, URLSessionDelegate {
    static var manager = SocketManager(socketURL: URL(string:"https://localhost:8000")!, config: [.log(true), .secure(true), .selfSigned(true), .sessionDelegate(self)])

    func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
        let protectionSpace = challenge.protectionSpace
        guard protectionSpace.authenticationMethod ==
            NSURLAuthenticationMethodServerTrust,
            protectionSpace.host.contains(Services_Routes.host) else {
                completionHandler(.performDefaultHandling, nil)
                return
        }
        guard let serverTrust = protectionSpace.serverTrust else {
            completionHandler(.performDefaultHandling, nil)
            return
        }
        let credential = URLCredential(trust: serverTrust)
        completionHandler(.useCredential, credential)
    }
</code>```

It returns me
Type 'Any' has no member 'sessionDelegate'

When I try :

```<code>SocketIOClientOption.sessionDelegate(self)
</code>```

Type '(SocketM) -> () -> SocketM' does not conform to protocol 'URLSessionDelegate'

Can someone explain me the problem?
Thanks !

答:
You are creating static variable and passing delegate as "self", you can't use self before initialising object.

If you don't need static object of manager then you can write code as

```<code>class SocketM: NSObject, URLSessionDelegate {
    var manager: SocketManager?

    override init() {
        super.init()
        manager = SocketManager(socketURL: URL(string:"https://localhost:8000")!, config:  [.log(true), .reconnects(true), .selfSigned(true), .sessionDelegate(self)])
    }
}
</code>```

And If you want static manager the

```<code>class SocketM: NSObject, URLSessionDelegate {
    static var manager = SocketManager(socketURL: URL(string:"https://localhost:8000")!, config:  [.log(true), .reconnects(true), .selfSigned(true)])

    override init() {
        super.init()
        SocketM.manager.config.insert(.sessionDelegate(self))
    }
}
</code>```

Body:
I'm tryng to connect to a self signed SSL URL.
But when I add sessionDelegate as option it's not working.

import Foundation
import SocketIO
import UIKit
class SocketM: NSObject, URLSessionDelegate {
    static var manager = SocketManager(socketURL: URL(string:"https://localhost:8000")!, config: [.log(true), .secure(true), .selfSigned(true), .sessionDelegate(self)])

    func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
        let protectionSpace = challenge.protectionSpace
        guard protectionSpace.authenticationMethod ==
            NSURLAuthenticationMethodServerTrust,
            protectionSpace.host.contains(Services_Routes.host) else {
                completionHandler(.performDefaultHandling, nil)
                return
        }
        guard let serverTrust = protectionSpace.serverTrust else {
            completionHandler(.performDefaultHandling, nil)
            return
        }
        let credential = URLCredential(trust: serverTrust)
        completionHandler(.useCredential, credential)
    }

It returns me
Type 'Any' has no member 'sessionDelegate'

When I try :

SocketIOClientOption.sessionDelegate(self)

Type '(SocketM) -> () -> SocketM' does not conform to protocol 'URLSessionDelegate'

Can someone explain me the problem?
Thanks !

Body:
You are creating static variable and passing delegate as "self", you can't use self before initialising object.

If you don't need static object of manager then you can write code as

class SocketM: NSObject, URLSessionDelegate {
    var manager: SocketManager?

    override init() {
        super.init()
        manager = SocketManager(socketURL: URL(string:"https://localhost:8000")!, config:  [.log(true), .reconnects(true), .selfSigned(true), .sessionDelegate(self)])
    }
}

And If you want static manager the

class SocketM: NSObject, URLSessionDelegate {
    static var manager = SocketManager(socketURL: URL(string:"https://localhost:8000")!, config:  [.log(true), .reconnects(true), .selfSigned(true)])

    override init() {
        super.init()
        SocketM.manager.config.insert(.sessionDelegate(self))
    }
}


问:
How to change constraint layout background image using java in android
I'm trying to change the constraint layout background image. On click of either one of the two radio buttons the background image should get changed. I've attached the code below. I've set a OnCheckedChangeListener on the radioGroup.

Java file

```<code>package com.mitwpu.practicallab_6_2_2020;

import android.support.constraint.ConstraintLayout;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.RadioButton;
import android.widget.RadioGroup;

public class Change_Background_Image_Activity extends AppCompatActivity {

    RadioGroup radioGroup;
    RadioButton radioButtonTom;
    RadioButton radioButtonJerry;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_change__background__image_);

        radioGroup=(RadioGroup)findViewById(R.id.radioGroupId);

        radioButtonTom=(RadioButton)findViewById(R.id.radioButtonTom);

        radioButtonJerry=(RadioButton)findViewById(R.id.radioButtonJerry);

        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId){
                    case R.id.radioButtonTom : {
                        //R.drawable.tom ->image1
                        break;
                    }
                    case R.id.radioButtonJerry : {
                        //R.drawable.jerry->image2

                        break;
                    }
                }
            }
        });

    }
}
</code>```

xml file

```<code>    <?xml version="1.0" encoding="utf-8"?>
    <android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/backgroudId"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Change_Background_Image_Activity">

    <RadioGroup
        android:id="@+id/radioGroupId"
        android:layout_width="274dp"
        android:layout_height="448dp"
        android:layout_marginStart="79dp"
        android:layout_marginTop="116dp"
        android:layout_marginEnd="58dp"
        android:layout_marginBottom="167dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <RadioButton
            android:id="@+id/radioButtonTom"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Tom" />

        <RadioButton
            android:id="@+id/radioButtonJerry"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Jerry" />
    </RadioGroup>
</android.support.constraint.ConstraintLayout>
</code>```

how to change the background image once the radio button is clicked

Body:
I'm trying to change the constraint layout background image. On click of either one of the two radio buttons the background image should get changed. I've attached the code below. I've set a OnCheckedChangeListener on the radioGroup.

Java file

package com.mitwpu.practicallab_6_2_2020;

import android.support.constraint.ConstraintLayout;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.RadioButton;
import android.widget.RadioGroup;

public class Change_Background_Image_Activity extends AppCompatActivity {

    RadioGroup radioGroup;
    RadioButton radioButtonTom;
    RadioButton radioButtonJerry;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_change__background__image_);

        radioGroup=(RadioGroup)findViewById(R.id.radioGroupId);

        radioButtonTom=(RadioButton)findViewById(R.id.radioButtonTom);

        radioButtonJerry=(RadioButton)findViewById(R.id.radioButtonJerry);

        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId){
                    case R.id.radioButtonTom : {
                        //R.drawable.tom ->image1
                        break;
                    }
                    case R.id.radioButtonJerry : {
                        //R.drawable.jerry->image2

                        break;
                    }
                }
            }
        });

    }
}

xml file

    <?xml version="1.0" encoding="utf-8"?>
    <android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/backgroudId"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Change_Background_Image_Activity">

    <RadioGroup
        android:id="@+id/radioGroupId"
        android:layout_width="274dp"
        android:layout_height="448dp"
        android:layout_marginStart="79dp"
        android:layout_marginTop="116dp"
        android:layout_marginEnd="58dp"
        android:layout_marginBottom="167dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <RadioButton
            android:id="@+id/radioButtonTom"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Tom" />

        <RadioButton
            android:id="@+id/radioButtonJerry"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Jerry" />
    </RadioGroup>
</android.support.constraint.ConstraintLayout>

how to change the background image once the radio button is clicked

Body: constraintId.setBackground(ContextCompat.getDrawable(this, R.drawable.some_drawable))


问:
hapijs joi validation , validate greater than from sum of other property
I want to validate a field 'familymemberCount' it should be greater than equal to other fields.
I tried below code, but this not allow to use ' + ' operator with Ref.
How do we validate with sum of other values ?</p>

```<code>export const familyMemberRulesSchema = Joi.object({
    relationMembers: Joi.object({
        motherCount: Joi.number().integer().min(0).max(5).optional(),
        fatherCount: Joi.number().integer().min(0).max(5).optional(),
        childrenCount: Joi.number().integer().min(0).max(5).optional()
    }),
    familyMemberCount: Joi.number().integer().min(0).max(15).greater(
        Joi.ref('relationMembers.motherCount') +
        Joi.ref('relationMembers.fatherCount') +
        Joi.ref('relationMembers.childrenCount')
    )
});
</code>```

答:
The joi.ref doesn't work this way. You need to write a custom function which takes all values and do the sum that way. Basically use adjust function while using a Joi.ref. Something like this.

```<code>const Joi = require("@hapi/joi");

const familyMemberRulesSchema = Joi.object({
    relationMembers: Joi.object({
        motherCount: Joi.number().integer().min(0).max(5).optional(),
        fatherCount: Joi.number().integer().min(0).max(5).optional(),
        childrenCount: Joi.number().integer().min(0).max(5).optional()
    }),
    familyMemberCount: Joi.number().integer().min(0).max(15).greater(
        Joi.ref('relationMembers', {"adjust": relationMembers => {
            return relationMembers.motherCount + relationMembers.fatherCount + relationMembers.childrenCount;
        }})
    )
});

const result = familyMemberRulesSchema.validate({"relationMembers": {"motherCount": 2, "fatherCount": 1, "childrenCount": 2}, "familyMemberCount": 6});

console.log(result);

const error = familyMemberRulesSchema.validate({"relationMembers": {"motherCount": 4, "fatherCount": 1, "childrenCount": 2}, "familyMemberCount": 6});

console.log(error);

</code>```

Body:
I want to validate a field 'familymemberCount' it should be greater than equal to other fields.
I tried below code, but this not allow to use ' + ' operator with Ref.
How do we validate with sum of other values ?

export const familyMemberRulesSchema = Joi.object({
    relationMembers: Joi.object({
        motherCount: Joi.number().integer().min(0).max(5).optional(),
        fatherCount: Joi.number().integer().min(0).max(5).optional(),
        childrenCount: Joi.number().integer().min(0).max(5).optional()
    }),
    familyMemberCount: Joi.number().integer().min(0).max(15).greater(
        Joi.ref('relationMembers.motherCount') +
        Joi.ref('relationMembers.fatherCount') +
        Joi.ref('relationMembers.childrenCount')
    )
});

Body:
The joi.ref doesn't work this way. You need to write a custom function which takes all values and do the sum that way. Basically use adjust function while using a Joi.ref. Something like this.

const Joi = require("@hapi/joi");

const familyMemberRulesSchema = Joi.object({
    relationMembers: Joi.object({
        motherCount: Joi.number().integer().min(0).max(5).optional(),
        fatherCount: Joi.number().integer().min(0).max(5).optional(),
        childrenCount: Joi.number().integer().min(0).max(5).optional()
    }),
    familyMemberCount: Joi.number().integer().min(0).max(15).greater(
        Joi.ref('relationMembers', {"adjust": relationMembers => {
            return relationMembers.motherCount + relationMembers.fatherCount + relationMembers.childrenCount;
        }})
    )
});

const result = familyMemberRulesSchema.validate({"relationMembers": {"motherCount": 2, "fatherCount": 1, "childrenCount": 2}, "familyMemberCount": 6});

console.log(result);

const error = familyMemberRulesSchema.validate({"relationMembers": {"motherCount": 4, "fatherCount": 1, "childrenCount": 2}, "familyMemberCount": 6});

console.log(error);


问:
Web application authentication using React and Flask
I am building a web application which uses React on the frontend and Flask on the backend (and deployed to Azure).
I would like to implement user authentication/authorization.

I understand how to implement this with pure Flask, but I am not sure how to achieve this when React is the frontend and Flask on the backend.
For example:

Is still Flask handling this or is this done by React?

If Flask authenticates the users, how do you send passwords in a secure way?

etc etc etc

Any advice/ link to resources is more than welcome.
I am also open to suggestion on other ways to handle this.

答:
There's different ways to handle authentication and what you pick depends on the level of security you need and how much time you're willing to invest.
Sending login data from the client to the server is fairly well protected when you use ssl.

So you build a form in react and send the data with a post over ssl to you backend. After that you can use a token or a session or cookie etc.

There's a nice write up on Flask Authentication in this blog