问:
How To reverse a URL with hyphens in the name?
I have a Django Application, with a file like the next one

app_something/url.py:

```<code>from django.urls import include, path, re_path
from rest_framework import routers
from . import views

slashless_router = routers.DefaultRouter(trailing_slash=True)
router = routers.DefaultRouter()

router.register(r'complex-name', views.ComplexNameModelViewSet)
router.register(r'simple', views.SimpleModelViewSet)

app_name='something'

urlpatterns = [
    path('api/', include(router.urls)),
]

</code>```

It works perfect. Or that is what I used to think. Now, I'm trying to add Tests (Yep, my bad they should be there first)

BUT, now in my test_complex_name_api.py:

```<code>from django.urls import reverse

from rest_framework import status

from app_something import models, serializers

SIMPLE_MODEL_NAME_URL = reverse('something:simple-list')
COMPLEX_MODEL_NAME_URL = reverse('something:complex-name-list')

# ...
# My Tests
</code>```

But, when I run my tests I got next error:

```<code>django.urls.exceptions.NoReverseMatch: Reverse for 'complex-name-list' not found. 'complex-name-list' is not a valid view function or pattern name.
</code>```

SimpleModel works pretty cool. So, I think it's related to the name. But I haven't found which should be the name pattern to use? Should I rename the url or can I still use in this way and I'm only missing the part of the docs which talk about this? (I read from: https://www.django-rest-framework.org/api-guide/routers/)

答:
DRF using basename for reverse viewset urls. By default it's evaluating based on queryset provided in viewset, but can override it by providing custom value to router directly:

```<code>router.register(r'complex-name', views.ComplexNameModelViewSet, basename='complex-name')

COMPLEX_MODEL_NAME_URL = reverse('something:complex-name-list')
</code>```

Body:
I have a Django Application, with a file like the next one

app_something/url.py:

from django.urls import include, path, re_path
from rest_framework import routers
from . import views

slashless_router = routers.DefaultRouter(trailing_slash=True)
router = routers.DefaultRouter()

router.register(r'complex-name', views.ComplexNameModelViewSet)
router.register(r'simple', views.SimpleModelViewSet)

app_name='something'

urlpatterns = [
    path('api/', include(router.urls)),
]

It works perfect. Or that is what I used to think. Now, I'm trying to add Tests (Yep, my bad they should be there first)

BUT, now in my test_complex_name_api.py:

from django.urls import reverse

from rest_framework import status

from app_something import models, serializers

SIMPLE_MODEL_NAME_URL = reverse('something:simple-list')
COMPLEX_MODEL_NAME_URL = reverse('something:complex-name-list')

# ...
# My Tests

But, when I run my tests I got next error:

django.urls.exceptions.NoReverseMatch: Reverse for 'complex-name-list' not found. 'complex-name-list' is not a valid view function or pattern name.

SimpleModel works pretty cool. So, I think it's related to the name. But I haven't found which should be the name pattern to use? Should I rename the url or can I still use in this way and I'm only missing the part of the docs which talk about this? (I read from: https://www.django-rest-framework.org/api-guide/routers/)

Body:
DRF using basename for reverse viewset urls. By default it's evaluating based on queryset provided in viewset, but can override it by providing custom value to router directly:

router.register(r'complex-name', views.ComplexNameModelViewSet, basename='complex-name')

COMPLEX_MODEL_NAME_URL = reverse('something:complex-name-list')


来源: stackexchange

问:
Google Sign In Button does Nothing
I have implemented the Google Sign In exactly as Google states to according to their website. I had it working about a month ago, now it just does nothing. I tried to redo everything by deleting the cocoapod and following their website to a T but nothing is happening still. It is like none of the delegate methods are being called, and I am unsure why. Any help would be appreciative. Thanks!

```<code>import GoogleSignIn
import Google
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    //Get Twitter and set Twitter keys for Application
    Twitter.sharedInstance().startWithConsumerKey("uBedaxDuMDgImGbjun1oYf0ay", consumerSecret: "OaKqBZUesX5CypHCwrTvTZE22jrXIuRsUeZzVaMHej11R5Vh3b")
    Fabric.with([Twitter.self])

    // Initialize sign-in GOOGLE
    var configureError: NSError?
    GGLContext.sharedInstance().configureWithError(&configureError)
    assert(configureError == nil, "Error configuring Google services: \(configureError)")

    GIDSignIn.sharedInstance().delegate = self

    return true
}

func application(application: UIApplication,
                 openURL url: NSURL, options: [String: AnyObject]) -> Bool {
    return GIDSignIn.sharedInstance().handleURL(url,
                                                sourceApplication: options[UIApplicationOpenURLOptionsSourceApplicationKey] as? String,
                                                annotation: options[UIApplicationOpenURLOptionsAnnotationKey])
}

func application(application: UIApplication,
                 openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool {
    var options: [String: AnyObject] = [UIApplicationOpenURLOptionsSourceApplicationKey: sourceApplication!,
                                        UIApplicationOpenURLOptionsAnnotationKey: annotation!]
    return GIDSignIn.sharedInstance().handleURL(url,
                                                sourceApplication: sourceApplication,
                                                annotation: annotation)
}

func signIn(signIn: GIDSignIn!, didSignInForUser user: GIDGoogleUser!,
            withError error: NSError!) {
    print("SIGNING IN")
    if (error == nil) {
        let email = user.profile.email
        print(user.authentication)
        // ...
    } else {
        print("ERROR = \(error.localizedDescription)")
    }
}
</code>```

View Controller

```<code>import GoogleSignIn
class LoginViewController: UIViewController, UITextFieldDelegate, CLLocationManagerDelegate, GIDSignInUIDelegate
 override func viewDidLoad() {

    //Default setup for View Controller
    super.viewDidLoad()

    GIDSignIn.sharedInstance().uiDelegate = self
    var error:NSError?
    GGLContext.sharedInstance().configureWithError(&error)
    if(error != nil) {
        print(error)
    }

    var signInButton = GIDSignInButton(frame: CGRect(x: 0, y: 0, width: 150, height: 400))
    view.addSubview(signInButton)

}
</code>```

EDIT

After HOURS, lol, of figuring this out, the Google Sign-In Button works when it is
1)Held down for more than 2 seconds,
2)Swiped left/down/right but not up
I am unsure of this cause and would be open to suggestions! Thanks!

答:
since my button not working properly i used to put a UIButton over the GIDSignInButton and called the method inside my UIButton action which made all good</p>

```<code>@IBAction func signInWithGoogle(_ sender: Any) {
        GIDSignIn.sharedInstance()?.signIn()
    }
</code>```

ContentLicense: CC BY-SA 3.0

Title: Google Sign In Button does Nothing

Body:
I have implemented the Google Sign In exactly as Google states to according to their website. I had it working about a month ago, now it just does nothing. I tried to redo everything by deleting the cocoapod and following their website to a T but nothing is happening still. It is like none of the delegate methods are being called, and I am unsure why. Any help would be appreciative. Thanks!

import GoogleSignIn
import Google
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    //Get Twitter and set Twitter keys for Application
    Twitter.sharedInstance().startWithConsumerKey("uBedaxDuMDgImGbjun1oYf0ay", consumerSecret: "OaKqBZUesX5CypHCwrTvTZE22jrXIuRsUeZzVaMHej11R5Vh3b")
    Fabric.with([Twitter.self])

    // Initialize sign-in GOOGLE
    var configureError: NSError?
    GGLContext.sharedInstance().configureWithError(&configureError)
    assert(configureError == nil, "Error configuring Google services: \(configureError)")

    GIDSignIn.sharedInstance().delegate = self

    return true
}

func application(application: UIApplication,
                 openURL url: NSURL, options: [String: AnyObject]) -> Bool {
    return GIDSignIn.sharedInstance().handleURL(url,
                                                sourceApplication: options[UIApplicationOpenURLOptionsSourceApplicationKey] as? String,
                                                annotation: options[UIApplicationOpenURLOptionsAnnotationKey])
}

func application(application: UIApplication,
                 openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool {
    var options: [String: AnyObject] = [UIApplicationOpenURLOptionsSourceApplicationKey: sourceApplication!,
                                        UIApplicationOpenURLOptionsAnnotationKey: annotation!]
    return GIDSignIn.sharedInstance().handleURL(url,
                                                sourceApplication: sourceApplication,
                                                annotation: annotation)
}

func signIn(signIn: GIDSignIn!, didSignInForUser user: GIDGoogleUser!,
            withError error: NSError!) {
    print("SIGNING IN")
    if (error == nil) {
        let email = user.profile.email
        print(user.authentication)
        // ...
    } else {
        print("ERROR = \(error.localizedDescription)")
    }
}

View Controller

import GoogleSignIn
class LoginViewController: UIViewController, UITextFieldDelegate, CLLocationManagerDelegate, GIDSignInUIDelegate
 override func viewDidLoad() {

    //Default setup for View Controller
    super.viewDidLoad()

    GIDSignIn.sharedInstance().uiDelegate = self
    var error:NSError?
    GGLContext.sharedInstance().configureWithError(&error)
    if(error != nil) {
        print(error)
    }

    var signInButton = GIDSignInButton(frame: CGRect(x: 0, y: 0, width: 150, height: 400))
    view.addSubview(signInButton)

}

EDIT

After HOURS, lol, of figuring this out, the Google Sign-In Button works when it is
1)Held down for more than 2 seconds,
2)Swiped left/down/right but not up
I am unsure of this cause and would be open to suggestions! Thanks!

Body:
since my button not working properly i used to put a UIButton over the GIDSignInButton and called the method inside my UIButton action which made all good

@IBAction func signInWithGoogle(_ sender: Any) {
        GIDSignIn.sharedInstance()?.signIn()
    }

ContentLicense: CC BY-SA 4.0


问:
How to predict future Stock using LSTM Keras
First of all, I must say, I'm a beginner to this AI things. I followed most of the tutorials about stock market predictions and all of them are pretty much same. These tutorials using a data set and split in to two sets. First one is Training set and the 2nd one is Test set. They are using Closing price of the stocks to train and make a model. From that model, they insert test data set which contain the closing price and showing two graphs. Then they say the actual and the predicted graphs are pretty much same.
The github repo of the tutorial. -
https://github.com/surajr/Stock-Predictor-using-LSTM/blob/master/Stock-Predictor-using-LSTM.ipynb
This is my question,
1. Why all those tutorials are putting closing price in the testing set also? They are only suppose to insert dates right? Because we are predicting the closing price. This is confusing. Please explain me.
2. No one is telling me how to predict next 7 days values. So if we have a model, how to get next 7 days closing value?

Please help me to clarify this. Thanks a lot.

答:
Take a look at this link.  I think it will get you going in the right direction.

https://www.datacamp.com/community/tutorials/lstm-python-stock-market


问:
Is there a "quick documentation" shortcut for VS code?
In some IDEs, Intellij IDEA for example, pressing control + j will display the docstring like this question. How do I get similar functionality for VS code?

答:
Settings

This three settings in the picture will help.

Click to thing that you want to its documentation with mouse

Use keybinding that given below

Show Hover

Definition Preview Hover


问:
How to run powershell job in parallel on AzureDevops Hosted pipeline
-EDIT 03-

I am editing my question because comments are too small.

I finally got my task to run. I had to edit the Publish-UpgradedServiceFabricApplication to accept a "compareApplicationName" and a "compareMode". It would then use those to determine a list of services that would get upgraded. I had to be careful not to unRegister the ApplicationType until I was done upgrading all the applications.

I'm sorry but my legal department will not allow me to post any actual code, claiming it as IP for the company.

-EDIT 02-

User Error
It turns out Get-VstsInput does not return any value when called from a thread. So any and all evaluations were wrong and the error was getting swallowed by the thread.
I'm rewriting to just thread the call to Publish-UpgradedServiceFabricApplication.

-Original message-

I have a service fabric cluster with several services running. Some of these are dynamically created services so they are not referenced in the ServiceManifest.xml

I have a custom task that updates the dynamically created services in series but this takes hours. I am trying to run Publish-UpgradedServiceFabricApplication in parallel so I can run all the upgrade jobs at once. The jobs start (I think) but the task never waits for them to finish before ending (and, thus, ending the PS jobs).

I've tried adding a Do...While loop on the job state but it still ends the task prematurely.

How do I keep the task alive while the upgrade is running?

-EDIT-

I feel I need to provide a sample because my code is not working the way it's supposed to. Given this code in the task:

```<code>    foreach($serviceapp in $servicefabricapp){
        if(-not ($serviceapp.ApplicationName.OriginalString.StartsWith("fabric:/DynamicService"))) {
            Write-Host "Application '$($serviceapp.ApplicationName.OriginalString)' does not start with 'fabric:/DynamicService' -SKIPPING"
            continue
        }

        $foundTaxReturnApp = $true
        Write-Host "Starting upgrade for $($serviceapp.ApplicationName.OriginalString)"
        Start-Job -ScriptBlock $upgradeScriptBlock -ArgumentList $serviceapp.ApplicationName, $applicationPackagePath, $applicationParameterFile, $publishProfile, $isUpgrade, $upgradeParameters

        Start-Sleep 5
    }

    $jobCount = (Get-Job | Where-Object{ $_.state -eq 'Running'}).Count

    Do {
        Start-Sleep -Seconds 30
        Write-Host "Waiting for $jobCount jobs to finish..."
        $jobCount = (Get-Job | Where-Object{ $_.state -eq 'Running'}).Count
    } while ($jobCount -gt 0)

    Get-Job

    $jobCount = (Get-Job | Where-Object{ $_.state -eq 'Running'}).Count

    Write-Host "Finished waiting, $jobCount jobs running."
</code>```

This is the output to the pipeline. There is no time elapsed between "upgrade for fabric:/DynamicService-2019OA20200131__16_21_39" and "Waiting for 0 jobs to finish...". And none of the DynamicServices get upgraded.

```<code>Application 'fabric:/MyFabricSystem' does not start with 'fabric:/DynamicService' -SKIPPING
Starting upgrade for fabric:/DynamicService
VERBOSE: Exporting function 'New-PSWorkflowSession'.
VERBOSE: Exporting alias 'nwsn'.

Id     Name            PSJobTypeName   State         HasMoreData     Location             Command
--     ----            -------------   -----         -----------     --------             -------
1      Job1            BackgroundJob   Running       True            localhost            ...
Starting upgrade for fabric:/DynamicService-2018CA20200128__13_35_06
3      Job3            BackgroundJob   Running       True            localhost            ...
Starting upgrade for fabric:/DynamicService-2018FA20200130__16_12_16
5      Job5            BackgroundJob   Running       True            localhost            ...
Starting upgrade for fabric:/DynamicService-2018GA20200130__16_12_16
7      Job7            BackgroundJob   Running       True            localhost            ...
Starting upgrade for fabric:/DynamicService-2018IA20200131__16_21_39
9      Job9            BackgroundJob   Running       True            localhost            ...
Starting upgrade for fabric:/DynamicService-2018IB20200131__16_21_39
11     Job11           BackgroundJob   Running       True            localhost            ...
Starting upgrade for fabric:/DynamicService-2018KA20200121__15_08_01
13     Job13           BackgroundJob   Running       True            localhost            ...
Starting upgrade for fabric:/DynamicService-2018OA20200131__16_21_39
15     Job15           BackgroundJob   Running       True            localhost            ...
Starting upgrade for fabric:/DynamicService-2018PA20200131__16_21_39
17     Job17           BackgroundJob   Running       True            localhost            ...
Starting upgrade for fabric:/DynamicService-2018SA20200130__16_12_16
19     Job19           BackgroundJob   Running       True            localhost            ...
Starting upgrade for fabric:/DynamicService-2018XA20200127__16_43_45
21     Job21           BackgroundJob   Running       True            localhost            ...
Starting upgrade for fabric:/DynamicService-2018YA20200124__15_17_35
23     Job23           BackgroundJob   Running       True            localhost            ...
Starting upgrade for fabric:/DynamicService-2019GA20200130__16_12_16
25     Job25           BackgroundJob   Running       True            localhost            ...
Starting upgrade for fabric:/DynamicService-2019OA20200131__16_21_39
27     Job27           BackgroundJob   Running       True            localhost            ...
Waiting for 0 jobs to finish...
1      Job1            BackgroundJob   Completed     True            localhost            ...
3      Job3            BackgroundJob   Completed     True            localhost            ...
5      Job5            BackgroundJob   Completed     True            localhost            ...
7      Job7            BackgroundJob   Completed     True            localhost            ...
9      Job9            BackgroundJob   Completed     True            localhost            ...
11     Job11           BackgroundJob   Completed     True            localhost            ...
13     Job13           BackgroundJob   Completed     True            localhost            ...
15     Job15           BackgroundJob   Completed     True            localhost            ...
17     Job17           BackgroundJob   Completed     True            localhost            ...
19     Job19           BackgroundJob   Completed     True            localhost            ...
21     Job21           BackgroundJob   Completed     True            localhost            ...
23     Job23           BackgroundJob   Completed     True            localhost            ...
25     Job25           BackgroundJob   Completed     True            localhost            ...
27     Job27           BackgroundJob   Completed     True            localhost            ...
Finished waiting, 0 jobs running.
##[debug]Leaving D:\a\_tasks\DynamicServiceUpgrade_4ec0e9dc-0f0a-47ff-86e3-ca0ae22d21d9\0.0.31\taskmain.ps1.

</code>```

答:
In this instance the script is executing properly. The concept of the Job is to execute and move on. If you would like to wait for the jobs to finish simply Get-Job | Wait-Job after your all of Jobs have executed.

If you want to do something a little more advanced/smart you can put it in your do-while loop

```<code>Do {
 $Job = Get-Job
 if ($Job.Status -eq "Failed") {
  "Fail"
  Exit 1
 }
Sleep 10
} Until ($Job.Status -eq "Success")
</code>```

Body:
-EDIT 03-

I am editing my question because comments are too small.

I finally got my task to run. I had to edit the Publish-UpgradedServiceFabricApplication to accept a "compareApplicationName" and a "compareMode". It would then use those to determine a list of services that would get upgraded. I had to be careful not to unRegister the ApplicationType until I was done upgrading all the applications.

I'm sorry but my legal department will not allow me to post any actual code, claiming it as IP for the company.

-EDIT 02-

User Error
It turns out Get-VstsInput does not return any value when called from a thread. So any and all evaluations were wrong and the error was getting swallowed by the thread.
I'm rewriting to just thread the call to Publish-UpgradedServiceFabricApplication.

-Original message-

I have a service fabric cluster with several services running. Some of these are dynamically created services so they are not referenced in the ServiceManifest.xml

I have a custom task that updates the dynamically created services in series but this takes hours. I am trying to run Publish-UpgradedServiceFabricApplication in parallel so I can run all the upgrade jobs at once. The jobs start (I think) but the task never waits for them to finish before ending (and, thus, ending the PS jobs).

I've tried adding a Do...While loop on the job state but it still ends the task prematurely.

How do I keep the task alive while the upgrade is running?

-EDIT-

I feel I need to provide a sample because my code is not working the way it's supposed to. Given this code in the task:

    foreach($serviceapp in $servicefabricapp){
        if(-not ($serviceapp.ApplicationName.OriginalString.StartsWith("fabric:/DynamicService"))) {
            Write-Host "Application '$($serviceapp.ApplicationName.OriginalString)' does not start with 'fabric:/DynamicService' -SKIPPING"
            continue
        }

        $foundTaxReturnApp = $true
        Write-Host "Starting upgrade for $($serviceapp.ApplicationName.OriginalString)"
        Start-Job -ScriptBlock $upgradeScriptBlock -ArgumentList $serviceapp.ApplicationName, $applicationPackagePath, $applicationParameterFile, $publishProfile, $isUpgrade, $upgradeParameters

        Start-Sleep 5
    }

    $jobCount = (Get-Job | Where-Object{ $_.state -eq 'Running'}).Count

    Do {
        Start-Sleep -Seconds 30
        Write-Host "Waiting for $jobCount jobs to finish..."
        $jobCount = (Get-Job | Where-Object{ $_.state -eq 'Running'}).Count
    } while ($jobCount -gt 0)

    Get-Job

    $jobCount = (Get-Job | Where-Object{ $_.state -eq 'Running'}).Count

    Write-Host "Finished waiting, $jobCount jobs running."

This is the output to the pipeline. There is no time elapsed between "upgrade for fabric:/DynamicService-2019OA20200131__16_21_39" and "Waiting for 0 jobs to finish...". And none of the DynamicServices get upgraded.

Application 'fabric:/MyFabricSystem' does not start with 'fabric:/DynamicService' -SKIPPING
Starting upgrade for fabric:/DynamicService
VERBOSE: Exporting function 'New-PSWorkflowSession'.
VERBOSE: Exporting alias 'nwsn'.

Id     Name            PSJobTypeName   State         HasMoreData     Location             Command
--     ----            -------------   -----         -----------     --------             -------
1      Job1            BackgroundJob   Running       True            localhost            ...
Starting upgrade for fabric:/DynamicService-2018CA20200128__13_35_06
3      Job3            BackgroundJob   Running       True            localhost            ...
Starting upgrade for fabric:/DynamicService-2018FA20200130__16_12_16
5      Job5            BackgroundJob   Running       True            localhost            ...
Starting upgrade for fabric:/DynamicService-2018GA20200130__16_12_16
7      Job7            BackgroundJob   Running       True            localhost            ...
Starting upgrade for fabric:/DynamicService-2018IA20200131__16_21_39
9      Job9            BackgroundJob   Running       True            localhost            ...
Starting upgrade for fabric:/DynamicService-2018IB20200131__16_21_39
11     Job11           BackgroundJob   Running       True            localhost            ...
Starting upgrade for fabric:/DynamicService-2018KA20200121__15_08_01
13     Job13           BackgroundJob   Running       True            localhost            ...
Starting upgrade for fabric:/DynamicService-2018OA20200131__16_21_39
15     Job15           BackgroundJob   Running       True            localhost            ...
Starting upgrade for fabric:/DynamicService-2018PA20200131__16_21_39
17     Job17           BackgroundJob   Running       True            localhost            ...
Starting upgrade for fabric:/DynamicService-2018SA20200130__16_12_16
19     Job19           BackgroundJob   Running       True            localhost            ...
Starting upgrade for fabric:/DynamicService-2018XA20200127__16_43_45
21     Job21           BackgroundJob   Running       True            localhost            ...
Starting upgrade for fabric:/DynamicService-2018YA20200124__15_17_35
23     Job23           BackgroundJob   Running       True            localhost            ...
Starting upgrade for fabric:/DynamicService-2019GA20200130__16_12_16
25     Job25           BackgroundJob   Running       True            localhost            ...
Starting upgrade for fabric:/DynamicService-2019OA20200131__16_21_39
27     Job27           BackgroundJob   Running       True            localhost            ...
Waiting for 0 jobs to finish...
1      Job1            BackgroundJob   Completed     True            localhost            ...
3      Job3            BackgroundJob   Completed     True            localhost            ...
5      Job5            BackgroundJob   Completed     True            localhost            ...
7      Job7            BackgroundJob   Completed     True            localhost            ...
9      Job9            BackgroundJob   Completed     True            localhost            ...
11     Job11           BackgroundJob   Completed     True            localhost            ...
13     Job13           BackgroundJob   Completed     True            localhost            ...
15     Job15           BackgroundJob   Completed     True            localhost            ...
17     Job17           BackgroundJob   Completed     True            localhost            ...
19     Job19           BackgroundJob   Completed     True            localhost            ...
21     Job21           BackgroundJob   Completed     True            localhost            ...
23     Job23           BackgroundJob   Completed     True            localhost            ...
25     Job25           BackgroundJob   Completed     True            localhost            ...
27     Job27           BackgroundJob   Completed     True            localhost            ...
Finished waiting, 0 jobs running.
##[debug]Leaving D:\a\_tasks\DynamicServiceUpgrade_4ec0e9dc-0f0a-47ff-86e3-ca0ae22d21d9\0.0.31\taskmain.ps1.

Body:
In this instance the script is executing properly. The concept of the Job is to execute and move on. If you would like to wait for the jobs to finish simply Get-Job | Wait-Job after your all of Jobs have executed.

If you want to do something a little more advanced/smart you can put it in your do-while loop

Do {
 $Job = Get-Job
 if ($Job.Status -eq "Failed") {
  "Fail"
  Exit 1
 }
Sleep 10
} Until ($Job.Status -eq "Success")


问:
Error with KafkaHDFS example: java.lang.NoSuchMethodError
I have trouble trying out the Kafka-HDFS data ingestion example .

I have tried both 0.10.0 and 0.14.0 version.
For the 0.10.0 version i use the ready distribution and for the 0.14.0 version i made a build by myself following the instructions in the README file (one problem that i encountered here was that the scala-library downloaded by gradle was not the one listed in the dependencies and i had to manually download scala-library-2.11.8 and put it in under the lib/ directory).

I have used hadoop server version 2.3.0 (with a pseudo distributed single node setup) and 3.2.1. One problem that i have with the 2.3.0 version i use as a cluster is that the downloaded release from the apache hadoop page is build against java < 1.8 in 32-bit mode whereas the gobblin libraries require java >= 1.8 and then i get some weird errors regarding stack guards etc.

Nevertheless, i prefer to go with hadoop 3.2.1 for my pseudo-distributed single node setup. So i went to try that.
Using the ready distribution for 0.10.0 (gobblin-distribution-0.10.0.tar.gz) i follow the instructions here: https://github.com/apache/incubator-gobblin/blob/gobblin_0.10.0/gobblin-docs/case-studies/Kafka-HDFS-Ingestion.md

then i execute:

```<code>bin/gobblin-mapreduce.sh --conf ~/Gobblin/ap       ps/KafkaHDFSIngestionMapReduce/job_conf_dir/job.pull
</code>```

And i got this error in the log gobblin-current.log:

```<code>2020-02-18 10:42:18 UTC ERROR [main] gobblin.runtime.AbstractJobLauncher  442 - Failed to launch and run job job_GobblinKafkaQuickStart_1582022486716: java.lang.NoSuchMethodError: org.apache.hadoop.yarn.api.records.URL.fromPath(Lorg/apache/hadoop/fs/Path;)Lorg/apache/hadoop/yarn/api/records/URL;
java.lang.NoSuchMethodError: org.apache.hadoop.yarn.api.records.URL.fromPath(Lorg/apache/hadoop/fs/Path;)Lorg/apache/hadoop/yarn/api/records/URL;
    at org.apache.hadoop.mapred.YARNRunner.setupLocalResources(YARNRunner.java:393)
    at org.apache.hadoop.mapred.YARNRunner.createApplicationSubmissionContext(YARNRunner.java:573)
    at org.apache.hadoop.mapred.YARNRunner.submitJob(YARNRunner.java:325)
    at org.apache.hadoop.mapreduce.JobSubmitter.submitJobInternal(JobSubmitter.java:432)
    at org.apache.hadoop.mapreduce.Job$10.run(Job.java:1285)
    at org.apache.hadoop.mapreduce.Job$10.run(Job.java:1282)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:422)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1548)
    at org.apache.hadoop.mapreduce.Job.submit(Job.java:1282)
    at gobblin.runtime.mapreduce.MRJobLauncher.runWorkUnits(MRJobLauncher.java:230)
    at gobblin.runtime.AbstractJobLauncher.runWorkUnitStream(AbstractJobLauncher.java:570)
    at gobblin.runtime.AbstractJobLauncher.launchJob(AbstractJobLauncher.java:417)
    at gobblin.runtime.mapreduce.CliMRJobLauncher.launchJob(CliMRJobLauncher.java:89)
    at gobblin.runtime.mapreduce.CliMRJobLauncher.run(CliMRJobLauncher.java:66)
    at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:70)
    at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:84)
    at gobblin.runtime.mapreduce.CliMRJobLauncher.main(CliMRJobLauncher.java:111)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.hadoop.util.RunJar.main(RunJar.java:212)
</code>```

One thing i tried was to change bin/gobblin-mapreduce.sh and add to LIBJARS that are passed as -libjars to hadoop jar all the jars under the lib/ folder so that the jobs use the 2.3.0 versions provided there (i.e hadoop-yarn-api-2.3.0 for the URL class in the error above).
After that change i still get the same error.

Notes:
1. HADOOP_HOME and HADOOP_BIN_DIR are only set before calling bin/gobblin-mapreduce.sh that point to my hadoop 3.2.1 installation.

Do you have any suggestions in tackling this problem? If using hadoop version 3.2.1 for the cluster setup is not possible what 2.X version could i use (that would not require to prepare a full development environment just to make a java 1.8 64-bit build :) )???

Alternatively, has anyone of you successfully tried the example in the page and could you please list the versions used?

Thanks for your time and assistance!

答:
Seems like you have mixed versions of hadoop dependencies. The org.apache.hadoop.yarn.api.records.URL comes from 2+, but the YARNRunner comes from 3+.

What is the error when you use 0.14.0?

Body:
I have trouble trying out the Kafka-HDFS data ingestion example .

I have tried both 0.10.0 and 0.14.0 version.
For the 0.10.0 version i use the ready distribution and for the 0.14.0 version i made a build by myself following the instructions in the README file (one problem that i encountered here was that the scala-library downloaded by gradle was not the one listed in the dependencies and i had to manually download scala-library-2.11.8 and put it in under the lib/ directory).

I have used hadoop server version 2.3.0 (with a pseudo distributed single node setup) and 3.2.1. One problem that i have with the 2.3.0 version i use as a cluster is that the downloaded release from the apache hadoop page is build against java < 1.8 in 32-bit mode whereas the gobblin libraries require java >= 1.8 and then i get some weird errors regarding stack guards etc.

Nevertheless, i prefer to go with hadoop 3.2.1 for my pseudo-distributed single node setup. So i went to try that.
Using the ready distribution for 0.10.0 (gobblin-distribution-0.10.0.tar.gz) i follow the instructions here: https://github.com/apache/incubator-gobblin/blob/gobblin_0.10.0/gobblin-docs/case-studies/Kafka-HDFS-Ingestion.md

then i execute:

bin/gobblin-mapreduce.sh --conf ~/Gobblin/ap       ps/KafkaHDFSIngestionMapReduce/job_conf_dir/job.pull

And i got this error in the log gobblin-current.log:

2020-02-18 10:42:18 UTC ERROR [main] gobblin.runtime.AbstractJobLauncher  442 - Failed to launch and run job job_GobblinKafkaQuickStart_1582022486716: java.lang.NoSuchMethodError: org.apache.hadoop.yarn.api.records.URL.fromPath(Lorg/apache/hadoop/fs/Path;)Lorg/apache/hadoop/yarn/api/records/URL;
java.lang.NoSuchMethodError: org.apache.hadoop.yarn.api.records.URL.fromPath(Lorg/apache/hadoop/fs/Path;)Lorg/apache/hadoop/yarn/api/records/URL;
    at org.apache.hadoop.mapred.YARNRunner.setupLocalResources(YARNRunner.java:393)
    at org.apache.hadoop.mapred.YARNRunner.createApplicationSubmissionContext(YARNRunner.java:573)
    at org.apache.hadoop.mapred.YARNRunner.submitJob(YARNRunner.java:325)
    at org.apache.hadoop.mapreduce.JobSubmitter.submitJobInternal(JobSubmitter.java:432)
    at org.apache.hadoop.mapreduce.Job$10.run(Job.java:1285)
    at org.apache.hadoop.mapreduce.Job$10.run(Job.java:1282)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:422)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1548)
    at org.apache.hadoop.mapreduce.Job.submit(Job.java:1282)
    at gobblin.runtime.mapreduce.MRJobLauncher.runWorkUnits(MRJobLauncher.java:230)
    at gobblin.runtime.AbstractJobLauncher.runWorkUnitStream(AbstractJobLauncher.java:570)
    at gobblin.runtime.AbstractJobLauncher.launchJob(AbstractJobLauncher.java:417)
    at gobblin.runtime.mapreduce.CliMRJobLauncher.launchJob(CliMRJobLauncher.java:89)
    at gobblin.runtime.mapreduce.CliMRJobLauncher.run(CliMRJobLauncher.java:66)
    at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:70)
    at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:84)
    at gobblin.runtime.mapreduce.CliMRJobLauncher.main(CliMRJobLauncher.java:111)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.hadoop.util.RunJar.main(RunJar.java:212)

One thing i tried was to change bin/gobblin-mapreduce.sh and add to LIBJARS that are passed as -libjars to hadoop jar all the jars under the lib/ folder so that the jobs use the 2.3.0 versions provided there (i.e hadoop-yarn-api-2.3.0 for the URL class in the error above).
After that change i still get the same error.

Notes:
1. HADOOP_HOME and HADOOP_BIN_DIR are only set before calling bin/gobblin-mapreduce.sh that point to my hadoop 3.2.1 installation.

Do you have any suggestions in tackling this problem? If using hadoop version 3.2.1 for the cluster setup is not possible what 2.X version could i use (that would not require to prepare a full development environment just to make a java 1.8 64-bit build :) )???

Alternatively, has anyone of you successfully tried the example in the page and could you please list the versions used?

Thanks for your time and assistance!


问:
I want to use a local variable outside of functions
I'm new to python and Im trying to create a program that will ask the user to select an image file using tk.filedialog and then do some PIL related work on it.. 'cause i've made a button that on-press will execute a function (Button = tk.Button(win, text="Select File", command=buttonFunc)), and the command parameter only takes a function name, I defined a function to open up the dialog and let user select the file, I wanted my function to store the path of the selected file, (In this case, in the variable path), It saves the path in the local variable but I wanna use it outside of function as well,, I've used global statement to make the variable global but it doesn't seem to work..

```<code>import tkinter as tk
import turtle
from tkinter import filedialog
from tkinter import PhotoImage
import os
from tkinter import INSERT
from tkinter import TOP
from tkinter import LEFT
from tkinter import *
from PIL import Image
from PIL import ImageEnhance
import time

# Main Screen
win = tk.Tk()
win.title('Color Enhancer')
win.geometry('500x70')
# Below line of code is used to set window icon, Not really sure how it works, copied from Net and pasted here.
win.tk.call('wm', 'iconphoto', win._w, tk.PhotoImage(file='icon.gif'))
Lab = tk.Label(win, text='Welcome to Color Enhancer, This mini utility is written purely in \n'
                         'Python and can be used to change colors of given Image, Select \n'
                         ' image and see the magic.')
Lab.pack()

def buttonFunc():
    global path
    path = tk.filedialog.askopenfilenames()
    print(path)
# buttonFunc() --> Works fine if i call it here, But it opens the dialog before even the button appears..

button = tk.Button(win, text='Select File', command=buttonFunc)
button.pack(side=BOTTOM)
print(path)
win.mainloop()
</code>```

I've tried to run the code and it throws the following error,

```<code>Traceback (most recent call last):
  File "C:\Users\iMacPro 2K19\Desktop\Main\Python\Scratches\PIL_Edit.py", line 34, in <module>
    print(path)
NameError: name 'path' is not defined
</code>```

I know that it is saying that the path is not defined.. but as You can see that I've defined it and also made it global..
One thing i wanna say that if I call buttonFunc() after defining it.. It works.. But it opens up the dialog before i press the button.. Is there any other way to solve it, or someone please tell me where im going wrong..

答:
path is only defined inside the function buttonFunc(). That's fine. But it also means that the variable path is UNDEFINED until the buttonFunc() func is called to initialize it.

Because your code only calls that func when the button is pressed, the path variable is still undefined when you hit your print(path) statement, because the button has not yet been hit to call the func to init the variable.

You can either initialize the path variable before the print(path) call, or you can just remove that print(path) call from there because it does not really do anything, and you can leave it inside your function, as it is.

Body:
I'm new to python and Im trying to create a program that will ask the user to select an image file using tk.filedialog and then do some PIL related work on it.. 'cause i've made a button that on-press will execute a function (Button = tk.Button(win, text="Select File", command=buttonFunc)), and the command parameter only takes a function name, I defined a function to open up the dialog and let user select the file, I wanted my function to store the path of the selected file, (In this case, in the variable path), It saves the path in the local variable but I wanna use it outside of function as well,, I've used global statement to make the variable global but it doesn't seem to work..

import tkinter as tk
import turtle
from tkinter import filedialog
from tkinter import PhotoImage
import os
from tkinter import INSERT
from tkinter import TOP
from tkinter import LEFT
from tkinter import *
from PIL import Image
from PIL import ImageEnhance
import time

# Main Screen
win = tk.Tk()
win.title('Color Enhancer')
win.geometry('500x70')
# Below line of code is used to set window icon, Not really sure how it works, copied from Net and pasted here.
win.tk.call('wm', 'iconphoto', win._w, tk.PhotoImage(file='icon.gif'))
Lab = tk.Label(win, text='Welcome to Color Enhancer, This mini utility is written purely in \n'
                         'Python and can be used to change colors of given Image, Select \n'
                         ' image and see the magic.')
Lab.pack()

def buttonFunc():
    global path
    path = tk.filedialog.askopenfilenames()
    print(path)
# buttonFunc() --> Works fine if i call it here, But it opens the dialog before even the button appears..

button = tk.Button(win, text='Select File', command=buttonFunc)
button.pack(side=BOTTOM)
print(path)
win.mainloop()

I've tried to run the code and it throws the following error,

Traceback (most recent call last):
  File "C:\Users\iMacPro 2K19\Desktop\Main\Python\Scratches\PIL_Edit.py", line 34, in <module>
    print(path)
NameError: name 'path' is not defined

I know that it is saying that the path is not defined.. but as You can see that I've defined it and also made it global..
One thing i wanna say that if I call buttonFunc() after defining it.. It works.. But it opens up the dialog before i press the button.. Is there any other way to solve it, or someone please tell me where im going wrong..


问:
Empty XML Columns during SQL Server replication
We have a merge replication setup on SQL Server that goes like this: 1 SQL server at the office, another SQL server traveling around the world. The publisher is the SQL server at the office.

In about 1% of the cases, two of our tables with a column of XML Data type (not bound to a schema) are replicated with rows containing empty XML columns. ( This only happened when data is sent from the "traveling server" back home, but then again, data seems to be changed more often there ). We only have this in prod. environment ( WAN replication ).

Things i have verified:

The row is replicated, as the last modification date on the row is refreshed but the xml column is empty. Of course it is not empty on the other SQL Server.

No conflicts are displayed in the replication conflicts UI.

It is not caused by the size of the data inside the XML Column as some are very small.

Usually, the problem occurs in batch. ( The xml column of 8-9 consecutive rows will be empty )

The problem occurs if a row was inserted OR updated. No pattern there.

The problem seems to occur, but this is pure speculation on my part when the connection is weaker. ( We've seen this problem happen more often when the server was far away as compared to when it was close by. )

Sorry if i have confused some things, I am not really a DBA, more of a DEV with knowledge of SQL but since the application using the database keeps getting blamed for the problems ( the XML column must not be empty!! ) I have taken it at heart to try and find the problem instead of just manually patching the data each time ( Whats the use of replication if you have to do that? )

If anyone could help out with this problem, or at least suggest some ways of being able to debug / investigate this it would be greatly appreciated.
I did search alot on google and I did find this: Hot Fix . But we do have the latest service pack and the problem seems a bit different.

fyi: We have a replication setup locally here but the problem never occurs. We will be trying a WAN simulator on it as well to see if that can help.

Thanks

答:
Figured i'd put an update here as this issue got me a few gray hairs and I am somewhat closer to a solution now.

I finally had some time to work on this and managed to reproduce this issue in our test environment, using a WAN simulator and slowing down the link and injecting some random packet loss. ( to best simulate the production environment where the server is overseas on a really bad line ).

After doing some SQL tracing, and some verbose logging here are my conclusions:
When replicating a row with an XML column, the process is done in 2 steps. First an insert is done of the full row but with an empty string for the XML column. Right after, an update is done this time with the XML column having data. Since the link is slow, in some situations a foreign key violation occured.
In this scenario, Table2 depends on Table1. After finishing replicating table1, and starting to replicate table2 (Enumration of insert/updates which takes time on a slow link), some entries were added to table1 and table2. Therefore some inserts on Table2 failed because Table1 entries were not in the database and were only going to be replicated next batch. The next time the replication occured, no more foreign key violations occured, however when it tried to insert the row that had previously failed in Table2 ( XML column row ), the update part of it was missing ( I could see that in the SQL profiler ) and that is why the row ended up after all was done with an empty XML.

Setting "Enforce for replication" to false on the foreign keys seems to address the problem, however I do still think that this whole process should work with the option set to true.

I logged a support call with Microsoft for this. I have sent the traces and logs to Microsoft and will see what they have to say.

I've read this article: http://msdn.microsoft.com/en-us/library/ms152529(v=SQL.90).aspx. But for me, setting this option to false is kind of a work around, no?

What do you guys think?

ps: Hope this is clear, tried to explain it the best I could. English is not my first language.

ContentLicense: CC BY-SA 2.5


问:
How to make EditText ediable but disable no keyboard?
I made a calculator. Its working fine. I want to have touch focus in edittext but the problem is when i touch it the keyboard popup. How to disable keyboard?

Screenshot of Calculator

```<code><EditText
    android:layout_width="match_parent"
    android:layout_height="100dp"
    android:gravity="bottom|end"
    android:textSize="40sp"
    android:enabled="true"
    android:singleLine="true"
    android:textIsSelectable="true"
    android:scrollHorizontally="true"
    android:id="@+id/tvExpression_ID"/>
</code>```

答:
Use this in Manifest file
android:windowSoftInputMode="stateAlwaysHidden"  or
set this for your edittext
    android:textIsSelectable="true"

Body:
I made a calculator. Its working fine. I want to have touch focus in edittext but the problem is when i touch it the keyboard popup. How to disable keyboard?

Screenshot of Calculator

<EditText
    android:layout_width="match_parent"
    android:layout_height="100dp"
    android:gravity="bottom|end"
    android:textSize="40sp"
    android:enabled="true"
    android:singleLine="true"
    android:textIsSelectable="true"
    android:scrollHorizontally="true"
    android:id="@+id/tvExpression_ID"/>


问:
How do I filter through an array list and return results that match the filter parameter?
I have a list that I'm filtering through to return results that are either, lessThan, greaterThan or equals to a particular value. But the function that does the comparison returns boolean values.

queryModifiers is an object of key value pairs that specifies what key within the data set is being compared and also the type of comparison.

const queryModifiers = {
price: "greaterThan",
weight: "lessThan",
}

const list = [
{
      '2104a7bd-5e78-49ce-a1f6-0699ac98f264': {
        additionalPrices: 0,
        clientOrderNumber: 'N / A',
        companyName: 'Test Company',
        completeDate: 'Invalid date',
        createdAt: '2019-09-08 16:41:43',
        createdBy: 'test@test.com',
        deliveryDate: '2019-09-14 16:39:25',
        driver: 'Robert Kaszkiewicz',
        dropOff: 'Avenida Callao 1234, Buenos Aires, Argentina',
        height: 23,
        isPreparingTrailer: true,
        isSmsSent: true,
        isTrailerReady: true,
        key: '2104a7bd-5e78-49ce-a1f6-0699ac98f264',
        notes: '',
        pickUp: 'Poprad, Slovakia',
        price: 1400,
        quantity: 2,
        trailer: 'einzeln',
        vehicle: 'Sattel',
        vehicleClass: 'Mega',
        vehicleId: '12313',
        vehicleReadyDate: '2019-09-27 16:41:22',
        weight: 123
      },
      '388113f5-3927-4fe3-80d5-f2fcf1c7cedd': {
        clientOrderNumber: 'N / A',
        companyName: 'Test Company',
        createdAt: '2019-09-26 18:32:18',
        createdBy: 'test@test.com',
        deliveryDate: '2019-09-20 18:31:45',
        driver: 'Michal Kucharski',
        dropOff: 'Logroño, Spain',
        height: 0,
        isPreparingTrailer: false,
        isSmsSent: false,
        isTrailerReady: false,
        key: '388113f5-3927-4fe3-80d5-f2fcf1c7cedd',
        notes: '',
        orderId: '',
        pickUp: '16671 Butano Place, Fontana, CA, USA',
        price: 0,
        quantity: 1,
        trailer: '2er Pack',
        vehicle: 'Sattel',
        vehicleClass: 'Standard',
        vehicleId: 'efgefg',
        vehicleReadyDate: '2019-09-27 18:32:08',
        weight: 0
      },
      '795e7531-8655-4e38-a576-e13483922607': {
        clientOrderNumber: 'N / A',
        companyName: 'Test Company',
        createdAt: '2019-10-07 14:59:28',
        createdBy: 'test@test.com',
        deliveryDate: '2019-10-09 14:54:44',
        driver: 'Pawel Marczyk',
        dropOff: 'München, Germany',
        height: 1150,
        isPreparingTrailer: false,
        isSmsSent: false,
        isTrailerReady: false,
        key: '795e7531-8655-4e38-a576-e13483922607',
        notes: 'alle fertig, vorher anrufen',
        orderId: '',
        pickUp: 'Soest, Germany',
        price: 5000,
        quantity: 10,
        trailer: '3er Pack',
        vehicle: 'Sattel',
        vehicleClass: 'Standard',
        vehicleId: '1121+23+24',
        vehicleReadyDate: '2019-10-07 14:55:19',
        weight: 20000
      },
] // list is an array of objects

export const handleFilterModifier = (value, compareValue, modifier) => {
    if (modifier === 'lessThan') {
        return value > compareValue;
    }

    if (modifier === 'equals') {
        return value === compareValue;
    }

    if (modifier === 'greaterThan') {
        return value < compareValue;
    }

    return null;
};

list.filter(
            item => Object.entries(queryModifiers)
                .every(([filterKey, filterVal]) => {
                    const compareValue = item[filterKey];
                    const value = Object.values(queryKeys);
                    const result = handleFilterModifier(
                        parseFloat(value),
                        compareValue,
                        filterVal
                    );
                    console.log(result); // result here returns boolean (true or false);
                })
        );
```

Where value is the parameter by which the list is being queried with e.g 100

compareValue is the data[key] value from the list that corresponds with the parameter being compared.

and modifier is the comparison method e.g greaterThan, lessThan or equals.

I want result to return list items that match and not boolean (which are actually correct when matched with the dataset).

答:
The section of code which returns boolean values is the following:

```<code>   export const handleFilterModifier = (value,
   compareValue, modifier) => {
    if (modifier === 'lessThan') {
        return value > compareValue;
        }

        if (modifier === 'equals') {
            return value === compareValue;
        }

        if (modifier === 'greaterThan') {
            return value < compareValue;
        }

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

To say it in pure english: If the modifier is lessThan and the value is greater than the compare value it will return boolean true. If the modifier is equals and the values are equal it will return boolean true. If the modifier is greaterThan and value is less than compare value it will return boolean true. Maybe you need to have a good look at this code and fix it.

Body:
I have a list that I'm filtering through to return results that are either, lessThan, greaterThan or equals to a particular value. But the function that does the comparison returns boolean values.

queryModifiers is an object of key value pairs that specifies what key within the data set is being compared and also the type of comparison.

const queryModifiers = {
price: "greaterThan",
weight: "lessThan",
}

const list = [
{
      '2104a7bd-5e78-49ce-a1f6-0699ac98f264': {
        additionalPrices: 0,
        clientOrderNumber: 'N / A',
        companyName: 'Test Company',
        completeDate: 'Invalid date',
        createdAt: '2019-09-08 16:41:43',
        createdBy: 'test@test.com',
        deliveryDate: '2019-09-14 16:39:25',
        driver: 'Robert Kaszkiewicz',
        dropOff: 'Avenida Callao 1234, Buenos Aires, Argentina',
        height: 23,
        isPreparingTrailer: true,
        isSmsSent: true,
        isTrailerReady: true,
        key: '2104a7bd-5e78-49ce-a1f6-0699ac98f264',
        notes: '',
        pickUp: 'Poprad, Slovakia',
        price: 1400,
        quantity: 2,
        trailer: 'einzeln',
        vehicle: 'Sattel',
        vehicleClass: 'Mega',
        vehicleId: '12313',
        vehicleReadyDate: '2019-09-27 16:41:22',
        weight: 123
      },
      '388113f5-3927-4fe3-80d5-f2fcf1c7cedd': {
        clientOrderNumber: 'N / A',
        companyName: 'Test Company',
        createdAt: '2019-09-26 18:32:18',
        createdBy: 'test@test.com',
        deliveryDate: '2019-09-20 18:31:45',
        driver: 'Michal Kucharski',
        dropOff: 'Logroño, Spain',
        height: 0,
        isPreparingTrailer: false,
        isSmsSent: false,
        isTrailerReady: false,
        key: '388113f5-3927-4fe3-80d5-f2fcf1c7cedd',
        notes: '',
        orderId: '',
        pickUp: '16671 Butano Place, Fontana, CA, USA',
        price: 0,
        quantity: 1,
        trailer: '2er Pack',
        vehicle: 'Sattel',
        vehicleClass: 'Standard',
        vehicleId: 'efgefg',
        vehicleReadyDate: '2019-09-27 18:32:08',
        weight: 0
      },
      '795e7531-8655-4e38-a576-e13483922607': {
        clientOrderNumber: 'N / A',
        companyName: 'Test Company',
        createdAt: '2019-10-07 14:59:28',
        createdBy: 'test@test.com',
        deliveryDate: '2019-10-09 14:54:44',
        driver: 'Pawel Marczyk',
        dropOff: 'München, Germany',
        height: 1150,
        isPreparingTrailer: false,
        isSmsSent: false,
        isTrailerReady: false,
        key: '795e7531-8655-4e38-a576-e13483922607',
        notes: 'alle fertig, vorher anrufen',
        orderId: '',
        pickUp: 'Soest, Germany',
        price: 5000,
        quantity: 10,
        trailer: '3er Pack',
        vehicle: 'Sattel',
        vehicleClass: 'Standard',
        vehicleId: '1121+23+24',
        vehicleReadyDate: '2019-10-07 14:55:19',
        weight: 20000
      },
] // list is an array of objects

export const handleFilterModifier = (value, compareValue, modifier) => {
    if (modifier === 'lessThan') {
        return value > compareValue;
    }

    if (modifier === 'equals') {
        return value === compareValue;
    }

    if (modifier === 'greaterThan') {
        return value < compareValue;
    }

    return null;
};

list.filter(
            item => Object.entries(queryModifiers)
                .every(([filterKey, filterVal]) => {
                    const compareValue = item[filterKey];
                    const value = Object.values(queryKeys);
                    const result = handleFilterModifier(
                        parseFloat(value),
                        compareValue,
                        filterVal
                    );
                    console.log(result); // result here returns boolean (true or false);
                })
        );

Where value is the parameter by which the list is being queried with e.g 100

compareValue is the data[key] value from the list that corresponds with the parameter being compared.

and modifier is the comparison method e.g greaterThan, lessThan or equals.

I want result to return list items that match and not boolean (which are actually correct when matched with the dataset).

Body:
The section of code which returns boolean values is the following:

   export const handleFilterModifier = (value,
   compareValue, modifier) => {
    if (modifier === 'lessThan') {
        return value > compareValue;
        }

        if (modifier === 'equals') {
            return value === compareValue;
        }

        if (modifier === 'greaterThan') {
            return value < compareValue;
        }

        return null;
    };

To say it in pure english: If the modifier is lessThan and the value is greater than the compare value it will return boolean true. If the modifier is equals and the values are equal it will return boolean true. If the modifier is greaterThan and value is less than compare value it will return boolean true. Maybe you need to have a good look at this code and fix it.


问:
How to code public key encryption logic in php given sample java logic?
I have a project of coding encryption logic using public key in php.
Given following sample Java code, how do you code it in php?
The specification document says to encrypt source with RSA(2048 bit).</p>

```<code>import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;
import org.apache.commons.codec.binary.Base64;
import org.json.JSONObject;

//some other codes...

String PUBLIC_KEY = "";
Map<String, String> map = new HashMap<>();
String data = new JSONObject(map).toString();

//generating public key object
byte[] buffer = Base64.decodeBase64(PUBLIC_KEY.getBytes());
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(keySpec);
//encryption data
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] encryptedByte = cipher.doFinal(data.getBytes());
//base 64
String encrypted = Base64.encodeToString(encryptedByte, Base64.DEFAULT);
return encrypted;
</code>```

答:
Solved php conversion myself by using module phpseclib\Crypt\RSA</p>

```<code>    $token = file_get_contents($path);
    $base64_decoded = base64_decode($token);
    $pubKey = new RSA();
    $pubKey->setEncryptionMode(RSA::ENCRYPTION_PKCS1);
    $pubKey->loadKey($base64_decoded);
    $crypted = $pubKey->encrypt($json);
    return base64_encode($crypted);
</code>```

Body:
I have a project of coding encryption logic using public key in php.
Given following sample Java code, how do you code it in php?
The specification document says to encrypt source with RSA(2048 bit).

import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;
import org.apache.commons.codec.binary.Base64;
import org.json.JSONObject;

//some other codes...

String PUBLIC_KEY = "";
Map<String, String> map = new HashMap<>();
String data = new JSONObject(map).toString();

//generating public key object
byte[] buffer = Base64.decodeBase64(PUBLIC_KEY.getBytes());
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(keySpec);
//encryption data
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] encryptedByte = cipher.doFinal(data.getBytes());
//base 64
String encrypted = Base64.encodeToString(encryptedByte, Base64.DEFAULT);
return encrypted;

Body:
Solved php conversion myself by using module phpseclib\Crypt\RSA

    $token = file_get_contents($path);
    $base64_decoded = base64_decode($token);
    $pubKey = new RSA();
    $pubKey->setEncryptionMode(RSA::ENCRYPTION_PKCS1);
    $pubKey->loadKey($base64_decoded);
    $crypted = $pubKey->encrypt($json);
    return base64_encode($crypted);


问:
How to create an object based on filtering two arrays with a filter criteria from one array in Javascript/ES6?
Let's assume I have two arrays of the same length:

```<code>const arr_one = [1,2,null,4,null,6];
const arr_two = ["a","b","c","d","e","f"];
</code>```

Now I would like to create one object called arr_final out of it that uses the values of arr_two as keys and the values of arr_one as values for arr_final, but only for values in arr_one that are not null.

So the desired outcome would be:

```<code>const obj_final = {"a": 1, "b": 2, "d": 4, "f": 6}
</code>```

Current solution

Currently, I am having a for loop with an if check inside it and would like to change it to a more shorter code:

```<code>let arr_final = {};
for (const [i, v] of arr_one.entries()) {
    if (v != null) {
        arr_final[arr_two[i]] = v
    }
};
</code>```

How can I achieve this with a minimal number of code lines?

答:
Here's the shortest one-liner approach, that requires 1 array iteration only

const arr_one = [1,2,null,4,null,6];
const arr_two = ["a","b","c","d","e","f"];

const fa = arr_one.reduce((a, e, i) => e ? { ...a, [arr_two[i]]: e } : a ,{});
console.log(fa);```

Body:
Let's assume I have two arrays of the same length:

const arr_one = [1,2,null,4,null,6];
const arr_two = ["a","b","c","d","e","f"];

Now I would like to create one object called arr_final out of it that uses the values of arr_two as keys and the values of arr_one as values for arr_final, but only for values in arr_one that are not null.

So the desired outcome would be:

const obj_final = {"a": 1, "b": 2, "d": 4, "f": 6}

Current solution

Currently, I am having a for loop with an if check inside it and would like to change it to a more shorter code:

let arr_final = {};
for (const [i, v] of arr_one.entries()) {
    if (v != null) {
        arr_final[arr_two[i]] = v
    }
};

How can I achieve this with a minimal number of code lines?


问:
List of List of child objects having same super class
I am trying to design a model in which I have a List of List of child object having same super class. This model will be a Model of a ListView. The super class is:

```<code>public class Element implements Serializable {

    private static final long serialVersionUID = 10121L;

    private String value;

    public Element(String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return "Element [value=" + value + "]";
    }
}
</code>```

One of the sub class is:

```<code>public class DateElement extends Element {

    private static final long serialVersionUID = 10122L;

    private DateTime date;

    public DateElement(String value, DateTime date) {
        super(value);
        this.date = date;
    }

    public DateTime getDate() {
        return date;
    }

    public void setDate(DateTime date) {
        this.date = date;
    }

    @Override
    public String toString() {
        return "DateElement [date=" + date + ", value=" + getValue() + "]";
    }
}
</code>```

I am instantiating the List of List as:

```<code>this.userMonitorMap = new ArrayList<List<? extends Element>>(0);
</code>```

Adding a List of DateElement in userMonitorMap as:

```<code>List<DateElement> dateElements = getDateElements();
userMonitorMap.add(dateElements);
</code>```

Upto this portion I am having no trouble. But the population of the ListView has problem, the code snippet is:

```<code>        ListView row = new ListView("row", userMonitorMap) {

            @Override
            protected void populateItem(ListItem rowItem) {
                List<? extends Element> columnMap = (List<? extends Element>) rowItem;
                ListView column = new ListView("column", columnMap) {

                    @Override
                    protected void populateItem(ListItem columnItem) {
                        Element element = (Element) columnItem; //The compile time error is here
                    }
                };
                rowItem.add(column);
            }
        };
</code>```

I have commented the problem in my code. How can I achieve this? What are the changes do I need?

The eclipse IDE red marked that line and the error message is: Cannot cast from ListItem to Element

Thanks and Regards.

答:
The ListItem isn't the object in the list itself, it contains a model which contains your object. You should be using:

```<code>Model<Element> elementModel = columnItem.getModel();
</code>```

or

```<code>Element element = columnItem.getModelObject();
</code>```

Take a look at these examples

Your code should read:

ListView row = new ListView("row", userMonitorMap) {

```<code>        @Override
        protected void populateItem(ListItem rowItem) {
            List<? extends Element> columnMap = rowItem.getModelObject();
            ListView column = new ListView("column", columnMap) {

                @Override
                protected void populateItem(ListItem columnItem) {
                    Element element = columnItem.getModelObject();
                }
            };
            rowItem.add(column);
        }
    };
</code>```

Body:
I am trying to design a model in which I have a List of List of child object having same super class. This model will be a Model of a ListView. The super class is:

public class Element implements Serializable {

    private static final long serialVersionUID = 10121L;

    private String value;

    public Element(String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return "Element [value=" + value + "]";
    }
}

One of the sub class is:

public class DateElement extends Element {

    private static final long serialVersionUID = 10122L;

    private DateTime date;

    public DateElement(String value, DateTime date) {
        super(value);
        this.date = date;
    }

    public DateTime getDate() {
        return date;
    }

    public void setDate(DateTime date) {
        this.date = date;
    }

    @Override
    public String toString() {
        return "DateElement [date=" + date + ", value=" + getValue() + "]";
    }
}

I am instantiating the List of List as:

this.userMonitorMap = new ArrayList<List<? extends Element>>(0);

Adding a List of DateElement in userMonitorMap as:

List<DateElement> dateElements = getDateElements();
userMonitorMap.add(dateElements);

Upto this portion I am having no trouble. But the population of the ListView has problem, the code snippet is:

        ListView row = new ListView("row", userMonitorMap) {

            @Override
            protected void populateItem(ListItem rowItem) {
                List<? extends Element> columnMap = (List<? extends Element>) rowItem;
                ListView column = new ListView("column", columnMap) {

                    @Override
                    protected void populateItem(ListItem columnItem) {
                        Element element = (Element) columnItem; //The compile time error is here
                    }
                };
                rowItem.add(column);
            }
        };

I have commented the problem in my code. How can I achieve this? What are the changes do I need?

The eclipse IDE red marked that line and the error message is: Cannot cast from ListItem to Element

Thanks and Regards.

Body:
The ListItem isn't the object in the list itself, it contains a model which contains your object. You should be using:

Model<Element> elementModel = columnItem.getModel();

or

Element element = columnItem.getModelObject();

Take a look at these examples

Your code should read:

ListView row = new ListView("row", userMonitorMap) {

        @Override
        protected void populateItem(ListItem rowItem) {
            List<? extends Element> columnMap = rowItem.getModelObject();
            ListView column = new ListView("column", columnMap) {

                @Override
                protected void populateItem(ListItem columnItem) {
                    Element element = columnItem.getModelObject();
                }
            };
            rowItem.add(column);
        }
    };


答:
You should initialize the path variable outside the function. Only then you will be able to access it globally.</p>

```<code>path=None
def buttonFunc():
    global path
    path="file path"
buttonFunc()
print(path)
</code>```

Title: I want to use a local variable outside of functions

Body:
You should initialize the path variable outside the function. Only then you will be able to access it globally.

path=None
def buttonFunc():
    global path
    path="file path"
buttonFunc()
print(path)


问:
How to create colspan in createdRow function?
How to coslpan a certain row with createdRow function? I want to "colspan="2" in row with out data "TOTAL". Thank you

```<code>"createdRow" : function (row, data, dataIndex){
        if ((data["INFO"] === "TOTAL" || data["NO"] === "999")){
            $(row).css({
                "background-color": "#F4D35E",
            });
         };
     },
</code>```

答:
```<code>$(<selector>).attr("colspan","2");
</code>```

selector -> the required

Body:
How to coslpan a certain row with createdRow function? I want to "colspan="2" in row with out data "TOTAL". Thank you

"createdRow" : function (row, data, dataIndex){
        if ((data["INFO"] === "TOTAL" || data["NO"] === "999")){
            $(row).css({
                "background-color": "#F4D35E",
            });
         };
     },

Body:
$(<selector>).attr("colspan","2");

selector -> the required <td>


问:
Append the specific column in another existing table using SQL QUERY
I know it sounds easy when appending a entire row to new table, but this is different

Question 1, state to combine the Table 1 and Table 2 and keep duplicate value, to create a new table, I have used the following query:

```<code>CREATE TABLE EMP_TBL_3
(
    EMP_ID int,
    Name varchar(255),
    DOJ int
);

INSERT INTO EMP_TBL_3 (EMP_ID, Name, DOJ)
   SELECT * FROM EMP_TBL_1
   UNION ALL
   SELECT * FROM EMP_TBL_2;
</code>```

Results:

Now the problem arise at 2nd question, saying: Take the D.O.B from EMP_BRTH_REC and combine them to EMP_TBL_3:

I have tried this query:

```<code>ALTER TABLE EMP_TBL_3
ADD DOB int;

SELECT * FROM EMP_TBL_3;

SELECT EMP_ID, Name, DOJ, DOB
FROM EMP_TBL_3
UNION ALL
SELECT EMP_TBL_3.EMP_ID, EMP_TBL_3.Name, EMP_TBL_3.DOJ, EMP_BRTH_REC.DOB
FROM EMP_BRTH_REC
LEFT JOIN EMP_TBL_3 ON EMP_BRTH_REC.EMP_ID = EMP_TBL_3.EMP_ID;
</code>```

Results:

My desired output is:

How do I do that?

答:
If i undertand propery, you just need to do this:</p>

```<code>select EMP_TBL_3.EMP_ID, EMP_TBL_3.Name, EMP_TBL_3.DOJ, EMP_BRTH_REC.DOB
from EMP_BRTH_REC LEFT JOIN
     EMP_TBL_3
     on EMP_BRTH_REC.EMP_ID = EMP_TBL_3.EMP_ID;
</code>```

Body:
I know it sounds easy when appending a entire row to new table, but this is different

Question 1, state to combine the Table 1 and Table 2 and keep duplicate value, to create a new table, I have used the following query:

CREATE TABLE EMP_TBL_3
(
    EMP_ID int,
    Name varchar(255),
    DOJ int
);

INSERT INTO EMP_TBL_3 (EMP_ID, Name, DOJ)
   SELECT * FROM EMP_TBL_1
   UNION ALL
   SELECT * FROM EMP_TBL_2;

Results:

Now the problem arise at 2nd question, saying: Take the D.O.B from EMP_BRTH_REC and combine them to EMP_TBL_3:

I have tried this query:

ALTER TABLE EMP_TBL_3
ADD DOB int;

SELECT * FROM EMP_TBL_3;

SELECT EMP_ID, Name, DOJ, DOB
FROM EMP_TBL_3
UNION ALL
SELECT EMP_TBL_3.EMP_ID, EMP_TBL_3.Name, EMP_TBL_3.DOJ, EMP_BRTH_REC.DOB
FROM EMP_BRTH_REC
LEFT JOIN EMP_TBL_3 ON EMP_BRTH_REC.EMP_ID = EMP_TBL_3.EMP_ID;

Results:

My desired output is:

How do I do that?

Body:
If i undertand propery, you just need to do this:

select EMP_TBL_3.EMP_ID, EMP_TBL_3.Name, EMP_TBL_3.DOJ, EMP_BRTH_REC.DOB
from EMP_BRTH_REC LEFT JOIN
     EMP_TBL_3
     on EMP_BRTH_REC.EMP_ID = EMP_TBL_3.EMP_ID;


问:
flutter add controller to an inputfield
i have a inputfield in a a widget to get the user email, i need to add a controller to this, but if i add the controller: line then i get an error:

```<code>  child: new Column(
          children: <Widget>[
            new InputField(
              ****controller: emailController,******
                hintText: email,
                obscureText: false,
                textInputType: TextInputType.text,
                textStyle: loginFormTextStyle,
                textFieldColor: textFieldColor,
                icon: Icons.mail_outline,
                iconColor: Colors.blue,
                bottomMargin: 20.0,
                validateFunction: validations.validateEmail,
                onSaved: (String email) {
                  user.email = email;
                }),
</code>```

how i can add the controller to this input without change the inputfield to a inputtextfield?

thanks

答:
There is no such kind of widget named InputField(). If you are expecting to take the user input's such as Username, password, mobile number etc. You need to use TextFormField, then you can get the controller parameter for your inputs. Check the below link

https://api.flutter.dev/flutter/material/TextFormField-class.html

It is having the explanation of how to deal with input validation. Please let me know, once you try this! Happy coding

Title: flutter add controller to an inputfield

Body:
i have a inputfield in a a widget to get the user email, i need to add a controller to this, but if i add the controller: line then i get an error:

  child: new Column(
          children: <Widget>[
            new InputField(
              ****controller: emailController,******
                hintText: email,
                obscureText: false,
                textInputType: TextInputType.text,
                textStyle: loginFormTextStyle,
                textFieldColor: textFieldColor,
                icon: Icons.mail_outline,
                iconColor: Colors.blue,
                bottomMargin: 20.0,
                validateFunction: validations.validateEmail,
                onSaved: (String email) {
                  user.email = email;
                }),

how i can add the controller to this input without change the inputfield to a inputtextfield?

thanks


问:
Bytes to dict conversion
I have a list of dict objects. I converted the dict object inside list to bytes by converting dict to str and then encode them.

```<code>    for idx, key in enumerate(key_data):
        key_data[idx] = str(key).encode('utf-8')
    for idx, value in enumerate(value_data):
        value_data[idx] = str(value).encode('utf-8')

    test = key_data[0]
    test = json.loads(test.decode('utf-8').replace("'",'"'))
</code>```

But when I try to convert them back, I'm getting JSON error " json.decoder.JSONDecodeError: Expecting value: line 1 column 183 (char 182) "

Do I need to add anything to my string ? Help is appreciated. Thanks !

答:
As @KlausD suggested, Python has an inbuilt module json to serialize or deserialize any JSON or python dictionaries. If you have a list of JSON objects, it is nothing but a JSON array.

The python module json converts a python dict object into JSON objects, whereas the list and tuple are converted into JSON array. A python str is converted into a JSON string. Integers and floating-point numbers are converted into JSON numbers. The Boolean value True is converted into JSON constant true.

In your case, you can serialize by calling

```<code>encoded = json.dumps(key_data).encode()
</code>```

And deserialize by calling

```<code>decoded = json.loads(encoded.decode())
</code>```

Title: Bytes to dict conversion

Body:
I have a list of dict objects. I converted the dict object inside list to bytes by converting dict to str and then encode them.

    for idx, key in enumerate(key_data):
        key_data[idx] = str(key).encode('utf-8')
    for idx, value in enumerate(value_data):
        value_data[idx] = str(value).encode('utf-8')

    test = key_data[0]
    test = json.loads(test.decode('utf-8').replace("'",'"'))

But when I try to convert them back, I'm getting JSON error " json.decoder.JSONDecodeError: Expecting value: line 1 column 183 (char 182) "

Do I need to add anything to my string ? Help is appreciated. Thanks !

Body:
As @KlausD suggested, Python has an inbuilt module json to serialize or deserialize any JSON or python dictionaries. If you have a list of JSON objects, it is nothing but a JSON array.

The python module json converts a python dict object into JSON objects, whereas the list and tuple are converted into JSON array. A python str is converted into a JSON string. Integers and floating-point numbers are converted into JSON numbers. The Boolean value True is converted into JSON constant true.

In your case, you can serialize by calling

encoded = json.dumps(key_data).encode()

And deserialize by calling

decoded = json.loads(encoded.decode())


问:
How to save the information on a Page when traveling from one detail page to another
I am working with Xamarin.Forms and I am trying to implement my multipage form in a Master-Detail format. When I click on another page from the Master page menu, I want to make sure that the information on the current detail page gets saved to its respective database table on the mobile device before I travel to the next detail page. Any idea on how to achieve that?</p>

答:
Hi @lovetolearn you can achieve this things OnDisappearing() method of each page.</p>

```<code>protected override void OnDisappearing()
{
    //Your code before you switch to another page
}
</code>```

Body:
Hi @lovetolearn you can achieve this things OnDisappearing() method of each page.

protected override void OnDisappearing()
{
    //Your code before you switch to another page
}


问:
Haskell: Get caller function name
In Haskell, is there a way to get the caller function name?  Of course I could hard-code it, but that turns into a maintenance burden: If someone were to rename the function, nothing is forcing them to rename the hard-coded name.

A contrived example:

```<code>f1 :: String
f1 = "f1" -- can this be automated?
</code>```

答:
You can do this with GHC's CallStack functionality.

```<code>import GHC.Stack ( HasCallStack, getCallStack, callStack )

foo :: HasCallStack => String -> String
foo s = let ((name, _):_) = getCallStack callStack
         in s <> ": " <> name

main :: HasCallStack => IO ()
main = putStrLn $ foo "This string is being passed to"
</code>```

Produces output This string is being passed to: foo

See my link above for a full description, but basically you can ask to have access to a (partial) call stack in a function by including a HasCallStack constraint. Then callStack gets a CallStack, which is isomorphic to [(String, SrcLoc)], where the first element of each pair is a function name; getCallStack converts the abstract CallStack type into an actual list of pairs.

(The docs seem to claim that HasCallStack constraints can be inferred, but in my very brief experiments that wasn't happening; if I used callStack in a function with no signature I was just getting an empty call stack; probably best to explicitly write a signature with a HasCallStack constraint)

Title: Haskell: Get caller function name

Body:
In Haskell, is there a way to get the caller function name?  Of course I could hard-code it, but that turns into a maintenance burden: If someone were to rename the function, nothing is forcing them to rename the hard-coded name.

A contrived example:

f1 :: String
f1 = "f1" -- can this be automated?

Body:
You can do this with GHC's CallStack functionality.

import GHC.Stack ( HasCallStack, getCallStack, callStack )

foo :: HasCallStack => String -> String
foo s = let ((name, _):_) = getCallStack callStack
         in s <> ": " <> name

main :: HasCallStack => IO ()
main = putStrLn $ foo "This string is being passed to"

Produces output This string is being passed to: foo

See my link above for a full description, but basically you can ask to have access to a (partial) call stack in a function by including a HasCallStack constraint. Then callStack gets a CallStack, which is isomorphic to [(String, SrcLoc)], where the first element of each pair is a function name; getCallStack converts the abstract CallStack type into an actual list of pairs.

(The docs seem to claim that HasCallStack constraints can be inferred, but in my very brief experiments that wasn't happening; if I used callStack in a function with no signature I was just getting an empty call stack; probably best to explicitly write a signature with a HasCallStack constraint)


问:
DevOps Pipeline fails - Cannot import key file: [XXX].pfx
I have been trying to create a build pipeline in Azure DevOps. While I am able to build a basic console app project, I have been getting issues when I added pfx files into the project app.

The console app project has been enabled for ClickOnce, which required to have a *.pfx key file.

When I set a basic build pipeline, but it appears to keep on failing. I get this message:

Error MSB3325: Cannot import the following key file: [XXXX].pfx. The key file may be password protected. To correct this, try to import the certificate again or manually install the certificate to the Strong Name CSP with the following key container name: VS_KEY_FE357D179B4A2D91

error MSB3325: Cannot import the following key file: [XXXX].pfx. The key file may be password protected. To correct this, try to import the certificate again or manually install the certificate to the Strong Name CSP with the following key container name: VS_KEY_FE357D179B4A2D91

How do I import the pfx to get the build to succeed?
Appreciate any insights/directions for this.

Thanks.

答:
If you're making your PFX file available to the pipeline just add a Powershell task before the main task

```<code>#Import the PFX certificate file and password. Read the thumbprint into variable
$Thumbprint = (Import-PfxCertificate -CertStoreLocation Cert:\CurrentUser\My -FilePath Certificate.pfx -Password $pwd).Thumbprint

Write-Host $Thumbprint

#Rest of Script below or set environment variable for rest of Pipeline
Write-Host "##vso[task.setvariable variable=Thumbprint]$Thumbprint"
</code>```

If you need it, you can pass the thumbprint to the rest of the pipeline with the last line or you can hard code the thumbprint where required.

I store my certificates in Azure KeyVault. If you do/would like to do the same, I have a post here for it: Access certificate thumprint from Azure DevOps variable group connected to Key vaults

Body:
If you're making your PFX file available to the pipeline just add a Powershell task before the main task

#Import the PFX certificate file and password. Read the thumbprint into variable
$Thumbprint = (Import-PfxCertificate -CertStoreLocation Cert:\CurrentUser\My -FilePath Certificate.pfx -Password $pwd).Thumbprint

Write-Host $Thumbprint

#Rest of Script below or set environment variable for rest of Pipeline
Write-Host "##vso[task.setvariable variable=Thumbprint]$Thumbprint"

If you need it, you can pass the thumbprint to the rest of the pipeline with the last line or you can hard code the thumbprint where required.

I store my certificates in Azure KeyVault. If you do/would like to do the same, I have a post here for it: Access certificate thumprint from Azure DevOps variable group connected to Key vaults


问:
How to get a list of video URLs from a specific YouTube channel
I want to get a list of video URLs from a specific YouTube channel with Python.

First, I wrote the following code.

```<code>import os
import time
import requests
import pandas as pd

API_KEY = os.environ['API_KEY']
CHANNEL_ID = 'your_searching_channel_id'

base_url = 'https://www.googleapis.com/youtube/v3'
url = base_url + '/search?key=%s&channelId=%s&part=snippet,id&order=date&maxResults=50'
infos = []
</code>```

But I don't know the next step.

I read YouTube API HELP, but I couldn't understand how to structure the program.

答:
The solution provided assumes that the link given to driver.get() is a Youtube Playlist. Modify it at your discretion.

```<code>import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Chrome("pathToChromeDriver")
driver.get('https://www.youtube.com/watch?v=WN-IW6wOdnI&list=PLs4hTtftqnlBOsOiQ2U1fddASTO9SlRbY')

def collectLinks():
    elements = []
    elems = driver.find_elements_by_xpath("//a[@href]")
    print("Collecting links...")
    for elem in elems:
        elements.append(str(elem.get_attribute("href")))

    for i in elements:
        print(i)

collectLinks()
driver.quit()
</code>```

Where "pathToChromeDriver" is replaced by your path to chrome driver.

Where 'https://www.youtube.com/watch?v=WN-IW6wOdnI&list=PLs4hTtftqnlBOsOiQ2U1fddASTO9SlRbY' is replaced by the playlist you want to find all url links.

Body:
I want to get a list of video URLs from a specific YouTube channel with Python.

First, I wrote the following code.

import os
import time
import requests
import pandas as pd

API_KEY = os.environ['API_KEY']
CHANNEL_ID = 'your_searching_channel_id'

base_url = 'https://www.googleapis.com/youtube/v3'
url = base_url + '/search?key=%s&channelId=%s&part=snippet,id&order=date&maxResults=50'
infos = []

But I don't know the next step.

I read YouTube API HELP, but I couldn't understand how to structure the program.

Body:
The solution provided assumes that the link given to driver.get() is a Youtube Playlist. Modify it at your discretion.

import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Chrome("pathToChromeDriver")
driver.get('https://www.youtube.com/watch?v=WN-IW6wOdnI&list=PLs4hTtftqnlBOsOiQ2U1fddASTO9SlRbY')

def collectLinks():
    elements = []
    elems = driver.find_elements_by_xpath("//a[@href]")
    print("Collecting links...")
    for elem in elems:
        elements.append(str(elem.get_attribute("href")))

    for i in elements:
        print(i)

collectLinks()
driver.quit()

Where "pathToChromeDriver" is replaced by your path to chrome driver.

Where 'https://www.youtube.com/watch?v=WN-IW6wOdnI&list=PLs4hTtftqnlBOsOiQ2U1fddASTO9SlRbY' is replaced by the playlist you want to find all url links.


问:
Split Pandas Dataframe into Multiple Excel Sheets Based on Index Value in Dataframe
I have this dataset:

That has the column 'Product' with values 'Gas', 'Oil', and 'Water'. I want to write this dataframe to a single excel workbook with three worksheets with the 'Gas', 'Oil', and 'Water' data in those three worksheets.

I have tried:

and keep getting a type error. Any assistance is appreciated.

答:
This should work. Try to apply this example to your needs:</p>

```<code>import pandas as pd

data = pd.read_excel('test.xlsx', index_col = 0)

Gas = data.loc['Gas']  # look for index Gas
Oil = data.loc['Oil']  # look for index Oil

writer = pd.ExcelWriter("Test.xlsx", engine = 'xlsxwriter')
Gas.to_excel(writer, sheet_name = 'Gas')
Oil.to_excel(writer, sheet_name = 'Oil')
writer.save()
</code>```

Body:
This should work. Try to apply this example to your needs:

import pandas as pd

data = pd.read_excel('test.xlsx', index_col = 0)

Gas = data.loc['Gas']  # look for index Gas
Oil = data.loc['Oil']  # look for index Oil

writer = pd.ExcelWriter("Test.xlsx", engine = 'xlsxwriter')
Gas.to_excel(writer, sheet_name = 'Gas')
Oil.to_excel(writer, sheet_name = 'Oil')
writer.save()


问:
How to set JAVA_HOME when I use the method "Runtime.getRuntime().exec" in Intellij Idea?
I want to use "jdeps" command to analyze some jar files' dependencies. My OS is Windows10. The core code is

```<code>String command = String.format("jdeps \"%s\"", path.toAbsolutePath().toString());
String format = String.format("cmd.exe /c %s", command);
process = Runtime.getRuntime().exec(format);
</code>```

There are 2 JDK version in my computer, JDK11 and JDK8. I want to use JDK11 and I set environment variable JAVA_HOME to JDK11's path. When I use cmd windows to execute the code, it works as I want, but If I run it in Intellij Idea, the JDK is changed to JDK8.

I'm sure that I have set the Project Settings--Project--Project SDK to JDK11. Project language level is SDK default(11-Local variable syntax for lambda parameters). Modules--Sources--Language level is "11-Local variable syntax for lambda parameters". The Java Compiler of Intellij Idea is also set to 11. There is nothing about JDK8 in my Intellij Idea.

But If I run my code in Intellij Idea, the JDK is still changed to JDK8. That makes me crazy. Is it a bug? What can I do to set JDK11?

By the way, I exec the "setx JAVA_HOME" command to set JAVA_HOME to JDK11 in my code, but it does not work.

答:
None of that uses JAVA_HOME.

When you execute jdeps like that, unqualified, you'll use the version that is on the PATH.

Either change the PATH, or qualify the command.

E.g. I don't have Java on the PATH, by default, so running jdeps unqualified fails, but I can run it if I qualify the command:

C:\>jdeps -version
'jdeps' is not recognized as an internal or external command,
operable program or batch file.

C:\>C:\prog\Java64\jdk1.8.0_181\bin\jdeps -version
1.8.0_181

C:\>C:\prog\Java64\jdk-13.0.2\bin\jdeps -version
13.0.2
```

Body:
I want to use "jdeps" command to analyze some jar files' dependencies. My OS is Windows10. The core code is

String command = String.format("jdeps \"%s\"", path.toAbsolutePath().toString());
String format = String.format("cmd.exe /c %s", command);
process = Runtime.getRuntime().exec(format);

There are 2 JDK version in my computer, JDK11 and JDK8. I want to use JDK11 and I set environment variable JAVA_HOME to JDK11's path. When I use cmd windows to execute the code, it works as I want, but If I run it in Intellij Idea, the JDK is changed to JDK8.

I'm sure that I have set the Project Settings--Project--Project SDK to JDK11. Project language level is SDK default(11-Local variable syntax for lambda parameters). Modules--Sources--Language level is "11-Local variable syntax for lambda parameters". The Java Compiler of Intellij Idea is also set to 11. There is nothing about JDK8 in my Intellij Idea.

But If I run my code in Intellij Idea, the JDK is still changed to JDK8. That makes me crazy. Is it a bug? What can I do to set JDK11?

By the way, I exec the "setx JAVA_HOME" command to set JAVA_HOME to JDK11 in my code, but it does not work.


问:
How to detect when a UIScrollView has finished scrolling
UIScrollViewDelegate has got two delegate methods scrollViewDidScroll: and scrollViewDidEndScrollingAnimation: but neither of these tell you when scrolling has completed. scrollViewDidScroll only notifies you that the scroll view did scroll not that it has finished scrolling.

The other method scrollViewDidEndScrollingAnimation only seems to fire if you programmatically move the scroll view not if the user scrolls.

Does anyone know of scheme to detect when a scroll view has completed scrolling?

答:
Using Ashley Smart logic and is being converted into Swift 4.0 and above.

```<code>    func scrollViewDidScroll(_ scrollView: UIScrollView) {
         NSObject.cancelPreviousPerformRequests(withTarget: self)
        perform(#selector(UIScrollViewDelegate.scrollViewDidEndScrollingAnimation(_:)), with: scrollView, afterDelay: 0.3)
    }

    func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
        NSObject.cancelPreviousPerformRequests(withTarget: self)
    }
</code>```

The logic above solve issues such as when user is scrolling off the tableview. Without the logic, when you scroll off the tableview, didEnd will be called but it will not execute anything. Currently using it in year 2020.

Body:
Using Ashley Smart logic and is being converted into Swift 4.0 and above.

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
         NSObject.cancelPreviousPerformRequests(withTarget: self)
        perform(#selector(UIScrollViewDelegate.scrollViewDidEndScrollingAnimation(_:)), with: scrollView, afterDelay: 0.3)
    }

    func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
        NSObject.cancelPreviousPerformRequests(withTarget: self)
    }

The logic above solve issues such as when user is scrolling off the tableview. Without the logic, when you scroll off the tableview, didEnd will be called but it will not execute anything. Currently using it in year 2020.


问:
Asymptotic Notation: Finding two constants such that n >= n0
Here is an asymptotic notation problem:

Let g(n) = 27n^2 + 18n and let f(n) = 0.5n^2 − 100. Find positive constants n0, c1 and c2 such that c1f(n) ≤ g(n) ≤ c2f(n) for all n ≥ n0.

Is this solving for theta? Do I prove 27n^2 + 18n = Ω(0.5n^2 − 100) and then prove (27n^2 + 18n) = O(0.5n^2 − 100)?

In that case wouldn't c1 and c2 be 1 and 56 respectively, and n0 would be the higher of the two n0 that I find?

答:
There are infinitely many solutions. We just need to fiddle with algebra to find one.

The first thing to note is that both g and f are positive for all n≥15. In particular, g(15) = 6345, f(15) = 12.5. (All smaller values of n make f<0.) This implies n0=15 might work fine as well as any larger value.

Next note g'(n) = 54n + 18 and f'(n) = n.

Since f(15) < g(15) and f'(n) < g'(n) for all n >= 15, choose c1 = 1.

Proof that this is a good choice:

0.5n^2 − 100 ≤ 27n^2 + 18n <=> 26.5n^2 + 18n + 100 ≥ 0

...obviously true for all n≥15.

What about c2? First, we want c2*f(n) to grow at least as fast as g: c2f'(n)≥g'(n), or c2*n ≥ 54n + 18 for n ≥ 15. So choose c2 ≥ 56, which obviously makes this true.

Unfortunately, c2=56 doesn't quite work with n0 = 15. There's the other criterion to meet: c2*f(15)≥g(15).  For that, 56 isn't big enough: 56*f(15) is only 700; g(15) is much bigger.

It turns out by substitution in the relation above and a bit more algebra that c2 = 508 does the trick.

Proof:

27n^2 + 18n ≤ 508 * (0.5n^2 − 100)

  <=> 27n^2 + 18n ≤ 254n^2 − 50800

  <=> 227n^2 - 18n - 50800 ≥ 0

At n=15, this is true by simple substitution. For all bigger values of n, note the lhs derivative 454n - 18 is positive for all n≥15, so the function is also non-decreasing over that domain. That makes the relation true as well.

To summarize, we've shown that n0=15, c1=1, and c2=508 is one solution.


问:
JustGage not defined after upgrading to angular 8
After upgrading my apps from angular 7.2 to 8.2. the angular2-just-gage module(link) that i used throwing error.
First, is about "eve not defined", i tried upgrading raphael from version 2.2.7 to 2.2.8. But then it throw another error

justgage.js:8 Uncaught ReferenceError: JustGage is not defined
      at Object../node_modules/justgage/justgage.js (justgage.js:8)

I have tried updating JustGage and raphael module to latest version but still throwing the same error. Is there anyone who also encouter this issue and has the fix?

答: I finally got it working, by setting "allowJs : true" in tsconfig.json file.</p>


问:
Laravel Japanese character validation full width (Katakana & Hirakana )
I want to validate whether user's input is in full-width (Katakana & Hirakana & alpha) characters or not?

I has saw Laravel Validation doc but cannot validate on my case.
https://readouble.com/laravel/5.7/en/validation.html

Anyone can give me an example for below? (input => validate)

full-width only ckeck:

```<code>'ぁァ1'　=> invalid,

'ぁァ1あア１'　=> invalid,

 'あア１'　=> valid,
</code>```

Half-width only ckeck:

```<code>'ぁァ1'　=> valid,

'ぁァ1あア１'　=> invalid,

'あア１'　=> invalid,
</code>```

答:
You can create new custom validate rule: https://laravel.com/docs/5.8/validation#custom-validation-rules

And use regex to validate it. This is some common rules:

half width alphabets（ lowercase ）

/^[a-z]+$/

half width alphabets（ uppercase ）

/^[A-Z]+$/

half width alphabets（ lowercase & uppercase ）

/^[a-zA-Z]+$/

half width alphabets（ lowercase & numeric ）

/^[a-z0-9]+$/

half width alphabets（ uppercase & numeric ）

/^[A-Z0-9]+$/

half width alphabets（ uppercase & lowercase & numeric ）

/^[a-zA-Z0-9]+$/

full width HIRAGANA

/^[ぁ-ん]+$/

full width KATAKANA

/^[ァ-ン]+$/

full width HIRAGANA & KATAKANA

/^[ぁ-んァ-ン]+$/

half width KATAKANA

/^[ｧ-ﾝﾞﾟ]+$/

KANJI

/^[一-龥]+$/

full width HIRAGANA & KANJI

/^[一-龥ぁ-ん]/

full width HIRAGANA & full width KATAKANA & KANJI

/^[ぁ-んァ-ン一-龥]/

Body:
I want to validate whether user's input is in full-width (Katakana & Hirakana & alpha) characters or not?

I has saw Laravel Validation doc but cannot validate on my case.
https://readouble.com/laravel/5.7/en/validation.html

Anyone can give me an example for below? (input => validate)

full-width only ckeck:

'ぁァ1'　=> invalid,

'ぁァ1あア１'　=> invalid,

 'あア１'　=> valid,

Half-width only ckeck:

'ぁァ1'　=> valid,

'ぁァ1あア１'　=> invalid,

'あア１'　=> invalid,