问:
Form and input validation
I am trying to get two inputs inside of a form tag to bring up a error message if you leave either of them blank.

I went to w3schools and tried their code but it does not work. (see below)

HTML

```<code><form name="myForm"  onsubmit="return validateForm()" method="post">
    Name: <input type="text" name="fname">
    <input type="submit" value="Submit">
</form>
</code>```

Js

```<code>function validateForm() {
    var x = document.forms["myForm"]["fname"].value;
    if (x == null || x == "") {
       alert("Name must be filled out");
       return false;
    }
}
</code>```

I removed the action="demo_form.asp" from the code because my teacher told me to

Here is my code

HTML

```<code><div class="loginShite">
    <form name="username" onsubmit="return validateForm()" method="post">
        <input type="text" name="username" placeholder="@Username" />
        <input type="password" name="password" placeholder="Password" />
        <br />
    </form>
    <div class="loginButton">
        <a href="#homePage">
           <input type ="button" value="login" />
        </a>
    </div>
</div>
</code>```

Js

```<code>function validateForm() {
    var x = document.forms["username"]["password"].value;
    if (x == null || x == "") {
       alert("Name must be filled out");
       return false;
    }
}
</code>```

I would be greatly appreciative is somebody could either tell me what I'm doing wrong OR point me in the right direction to solve the problem.

Thank you in advance.

答:
Actually, all you have to do is put required at the end of the first input tag. For example:

```<code><form>
<input type=“text” required>some text</input>
<!—-some other input—->
<input type=button>submit</input>
</form>
</code>```

I believe that should work.

Title: Form and input validation

Body:
I am trying to get two inputs inside of a form tag to bring up a error message if you leave either of them blank.

I went to w3schools and tried their code but it does not work. (see below)

HTML

<form name="myForm"  onsubmit="return validateForm()" method="post">
    Name: <input type="text" name="fname">
    <input type="submit" value="Submit">
</form>

Js

function validateForm() {
    var x = document.forms["myForm"]["fname"].value;
    if (x == null || x == "") {
       alert("Name must be filled out");
       return false;
    }
}

I removed the action="demo_form.asp" from the code because my teacher told me to

Here is my code

HTML

    <form name="username" onsubmit="return validateForm()" method="post">
        <input type="text" name="username" placeholder="@Username" />
        <input type="password" name="password" placeholder="Password" />

    </form>

           <input type ="button" value="login" />

Js

function validateForm() {
    var x = document.forms["username"]["password"].value;
    if (x == null || x == "") {
       alert("Name must be filled out");
       return false;
    }
}

I would be greatly appreciative is somebody could either tell me what I'm doing wrong OR point me in the right direction to solve the problem.

Thank you in advance.

Body:
Actually, all you have to do is put required at the end of the first input tag. For example:

<form>
<input type=“text” required>some text</input>
<!—-some other input—->
<input type=button>submit</input>
</form>

I believe that should work.


来源: stackexchange

问:
UITabBar Lifecycle's methods are not fired from background start
I've have a UITabBar controller as main controller, with 2 tabs. Each tab is a NavigatorViewController with a UIViewController embedded.

If I open the application from background after a previous cold launch, none of the ViewWillAppear (UITabBarController, UIViewController) is fired.

How can I call the lifecycle of UITabBarChildren when user come from backgroud? (IE: From a notification)

答:
When application comes from background non viewWillAppear/viewDidAppear is called for any active vc , you need to listen to app delegate  like applicationWillEnterForegroundNotification

```<code>NotificationCenter.default.addObserver(self, selector: #selector(applicationWillEnterForegroundNotification), name: UIApplication.willEnterForegroundNotification, object: nil)
</code>```

```<code>@objc func applicationWillEnterForegroundNotification(_ notification: NSNotification) {
  print("To-Do")
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
When application comes from background non viewWillAppear/viewDidAppear is called for any active vc , you need to listen to app delegate  like applicationWillEnterForegroundNotification

NotificationCenter.default.addObserver(self, selector: #selector(applicationWillEnterForegroundNotification), name: UIApplication.willEnterForegroundNotification, object: nil)

@objc func applicationWillEnterForegroundNotification(_ notification: NSNotification) {
  print("To-Do")
}


问:
Detail to detail drillthrough in Power BI
I have a Master page in a Power BI report with a list of IDs. For each ID's there are multiple detail pages set up as drillthrough pages - e.g. Overview Detail and Usage Detail. Each detail page takes in an ID and you can drillthrough from the master page to get to either.

What I would like to do is link the detail pages to each other. So I have filtered in ID 1 and looking at the Overview Detail and I want to have a menu or link to "See Usage Details" which would drillthrough with the same ID to the Usage Detail page (and vica versa). I could then break my detail pages up into a whole set of pages and almost have a tab menu on each to explore a particular ID.

I tried tables with hyperlinks (and querystrings) but it was getting really messy. The button links and bookmarks cannot take in a dynamic drillthrough filter.

Is this possible to do?

答:
I think you can achieve that with bookmarks.

First thing would be to create a bookmark, which takes a user to the desired page (from drilled page A to drilled page B). Bookmarks can be found here:

You need to turn Data and Display options off. The bookmark should only move a user between pages. Add button to Drillpage A with the bookmark as an action. If you need it both ways, do the same thing with Drillpage B.

After that, add slicer with IDs (column you use to drill) to both Drillpages and mark sync between them to True (option dialog should pop up when copypasting the visual, or turn ON sync pane here:

Then just hide both slicers so the user is not aware of them (via selection page - turn on just over Sync slicers option). I think the slicer should keep the ID, which was used to drillthrough into the page, thus providing the desired behavior.

Another option that comes into mind, is to make a small drillthrough table, which would contain only ID column, so a user could use it to drill from drillpageA to drillpageP, but I've never found it user-friendly.


答:
That is not in the life cycle because the state of controllers is not changing during background mode or other application events.

You should observe for applicationWillEnterForegroundNotification

```<code>class VC: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Listen for application event somewhere early like `ViewDidLoad`
        NotificationCenter.default.addObserver(self, selector: #selector(applicationWillEnterForegroundNotification), name: UIApplication.willEnterForegroundNotification, object: nil)
    }

    // Implement a function that you want to execute when event happen
    @objc func applicationWillEnterForegroundNotification() {
        // Do anything before application Enter Foreground
    }

    // Remove observer when the controller is going to remove to prevent further issues
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}
</code>```

Title: UITabBar Lifecycle's methods are not fired from background start

Body:
I've have a UITabBar controller as main controller, with 2 tabs. Each tab is a NavigatorViewController with a UIViewController embedded.

If I open the application from background after a previous cold launch, none of the ViewWillAppear (UITabBarController, UIViewController) is fired.

How can I call the lifecycle of UITabBarChildren when user come from backgroud? (IE: From a notification)

Body:
That is not in the life cycle because the state of controllers is not changing during background mode or other application events.

You should observe for applicationWillEnterForegroundNotification

class VC: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Listen for application event somewhere early like `ViewDidLoad`
        NotificationCenter.default.addObserver(self, selector: #selector(applicationWillEnterForegroundNotification), name: UIApplication.willEnterForegroundNotification, object: nil)
    }

    // Implement a function that you want to execute when event happen
    @objc func applicationWillEnterForegroundNotification() {
        // Do anything before application Enter Foreground
    }

    // Remove observer when the controller is going to remove to prevent further issues
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}


问:
Checking out a project on github with the Eclipse CVS client?
I am playing with my eclipse cvs functionality (on my windows box), is there a way to check out a project hosted on github?

Anyone shows me a pointer? Thanks,

答: Use EGit, which provides Git support as part of Eclipse and is available in both the latest Helios builds as well as the upcoming Indigo release.</p>

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
How to clone/fetch a repo getting only the history
Is it possible to download a repository's commits, branches, and tags, excluding blobs and trees? I would like to be able to view the history and whatnot without downloading the files (this is for the Chromium repo, which is multiple gigs). Obviously I will not be able to see which files were affected by a commit, but that's fine.</p>

答:
The "Partial Clone" feature was added in git 2.19.

Documentation here: https://www.git-scm.com/docs/partial-clone

In order to use it:

You need git >= 2.19 on both the server and the client

On the server, you need to enable the feature: git config --global uploadpack.allowFilter true

git clone --filter=tree:0 REMOTE_URL


问:
How to fix redirects in nginx after the front-slash in the end of the URL
We are changing our web from example.se to example.com and also changing a few categories from Swedish to English so I need to point the old URLs to new ones with new names.

I am trying to redirect example.se/something to example.com/anything-else

I've managed to accomplish the redirection from example.se > example.com but whenever I try to go to example.com/something > example.com/anything-else I get a 404.

Here's the nginx conf:

```<code>server {
    listen 80;
    listen 443;
    server_name example.se www.example.se;

    rewrite ^/(.*)$ http://.example.com/$1 permanent;
    rewrite ^/something/$ /anything-else/ permanent;
}
</code>```

What I've managed to accomplish is the redirection from example.se > example.com but whenever I try to go to example.com/something (which I'd like to point to example.com/anything-else) I get a 404.

答:
In second redirect you should specify domain name: rewrite ^/something/$ http://example.com/anything-else/ permanent instead rewrite ^/something/$ /anything-else/ permanent

Or you could use if:

```<code>if ($request_uri  =  / )  {
          rewrite (.*) http://example.com/ permanent;
      }
if ($request_uri ~ ^/something) {
          rewrite (.*) http://example.com/anything-else permanent;
      }
</code>```

Body:
We are changing our web from example.se to example.com and also changing a few categories from Swedish to English so I need to point the old URLs to new ones with new names.

I am trying to redirect example.se/something to example.com/anything-else

I've managed to accomplish the redirection from example.se > example.com but whenever I try to go to example.com/something > example.com/anything-else I get a 404.

Here's the nginx conf:

server {
    listen 80;
    listen 443;
    server_name example.se www.example.se;

    rewrite ^/(.*)$ http://.example.com/$1 permanent;
    rewrite ^/something/$ /anything-else/ permanent;
}

What I've managed to accomplish is the redirection from example.se > example.com but whenever I try to go to example.com/something (which I'd like to point to example.com/anything-else) I get a 404.

Body:
In second redirect you should specify domain name: rewrite ^/something/$ http://example.com/anything-else/ permanent instead rewrite ^/something/$ /anything-else/ permanent

Or you could use if:

if ($request_uri  =  / )  {
          rewrite (.*) http://example.com/ permanent;
      }
if ($request_uri ~ ^/something) {
          rewrite (.*) http://example.com/anything-else permanent;
      }


问:
How to extract matching keywords from two columns in a pandas dataframe?
I have two columns in a dataframe both are strings where column1 have some matching keywords in column2. I want to extract those matching keyword from column1 and column2 in a new column.

```<code>df['column3']=df.column1.apply(lambda x : df.column2[df.column2.str.contains(x)]
</code>```

I am expecting the output something like this

```<code>column1                     column2                 column3
A girl is going to market   girl market school      girl market
A girl is going to school   girl market school      girl school
The sky is blue in color    sky blue orange color   sky blue color
</code>```

答:
Using apply

Ex:

```<code>df["column3"] = df.apply(lambda x: " ".join(i for i in x["column2"].split() if i in x["column1"]),axis=1)
print(df)
</code>```

Output:

```<code>                     column1                column2         column3
0  A girl is going to market     girl market school     girl market
1  A girl is going to school     girl market school     girl school
2   The sky is blue in color  sky blue orange color  sky blue color
</code>```

Body:
I have two columns in a dataframe both are strings where column1 have some matching keywords in column2. I want to extract those matching keyword from column1 and column2 in a new column.

df['column3']=df.column1.apply(lambda x : df.column2[df.column2.str.contains(x)]

I am expecting the output something like this

column1                     column2                 column3
A girl is going to market   girl market school      girl market
A girl is going to school   girl market school      girl school
The sky is blue in color    sky blue orange color   sky blue color

Body:
Using apply

Ex:

df["column3"] = df.apply(lambda x: " ".join(i for i in x["column2"].split() if i in x["column1"]),axis=1)
print(df)

Output:

                     column1                column2         column3
0  A girl is going to market     girl market school     girl market
1  A girl is going to school     girl market school     girl school
2   The sky is blue in color  sky blue orange color  sky blue color


问:
K8s fails to assign floating ip to loadbalancer with octavia
I have

an openstack, it is Queens, it has octavia for lbaas

a small (test) k8s cluster on top of it (3 nodes, 1 master), version 9.1.2

a deployment called hello which serves a simple webpage saying 'hello world', it works when accessed from within the cluster

I want to expose my deployment as a load balanced service with a floating IP.

I did kubectl expose deployment hello --type=LoadBalancer --name=my-service

It says (kubectl describe service my-service)

Error creating load balancer (will retry): failed to ensure load balancer for service default/my-service: error getting floating ip for port 9cc6442b-2b2f-4b6a-8f91-65dbc2ff13d0: Resource not found

If I manually do: openstack floating ip --port 9cc6442b-2b2f-4b6a-8f91-65dbc2ff13d0 356c8ffa-7bc2-43a9-a8d3-29147ae01727
where:

```<code>| ID                                   | Floating IP Address | Port                                 | Floating Network                     |
| 356c8ffa-7bc2-43a9-a8d3-29147ae01727 | 172.27.81.241       | None                                 | eb31cc74-96ba-4394-aef4-0e94bec46d85 |
</code>```

and  /etc/kubernetes/cloud_config has:

```<code>[LoadBalancer]
subnet-id=6a6cdc35-8dda-4982-850e-53c6ee5a5085
floating-network-id=eb31cc74-96ba-4394-aef4-0e94bec46d85
use-octavia=True
</code>```

(so it is looking for floating IPs on the correct network, and that subnet is the k8s internal subnet)

It all works.

So everything except "associate an IP" has worked.  Why does this step fail? Where has k8s logged what it did and how it failed?  I can only find docs for pod level logging (and my pod is fine, and serving it's test webpage just great).

(I have lots of quota remaining for 'make more floating ips', and several unused ones hanging around)

答:
I was able to find this No Ports Available when trying to associate a floating IP and this Failed to Associate Floating IP. Maybe those will point you into right direction.

I would recommend that you check this page OpenStack community and look for more answers as I'm not an expert in OpenStack.

As for your question

Where has k8s logged what it did and how it failed?

You can use kubectl describe service <service_name>

Show details of a specific resource or group of resources

Print a detailed description of the selected resources, including related resources such as events or controllers. You may select a single object by name, all objects of that type, provide a name prefix, or label selector. For example:

$ kubectl describe TYPE NAME_PREFIX

For mode debug description please check Debug Services.

Body:
I have

an openstack, it is Queens, it has octavia for lbaas

a small (test) k8s cluster on top of it (3 nodes, 1 master), version 9.1.2

a deployment called hello which serves a simple webpage saying 'hello world', it works when accessed from within the cluster

I want to expose my deployment as a load balanced service with a floating IP.

I did kubectl expose deployment hello --type=LoadBalancer --name=my-service

It says (kubectl describe service my-service)

Error creating load balancer (will retry): failed to ensure load balancer for service default/my-service: error getting floating ip for port 9cc6442b-2b2f-4b6a-8f91-65dbc2ff13d0: Resource not found

If I manually do: openstack floating ip --port 9cc6442b-2b2f-4b6a-8f91-65dbc2ff13d0 356c8ffa-7bc2-43a9-a8d3-29147ae01727
where:

| ID                                   | Floating IP Address | Port                                 | Floating Network                     |
| 356c8ffa-7bc2-43a9-a8d3-29147ae01727 | 172.27.81.241       | None                                 | eb31cc74-96ba-4394-aef4-0e94bec46d85 |

and  /etc/kubernetes/cloud_config has:

[LoadBalancer]
subnet-id=6a6cdc35-8dda-4982-850e-53c6ee5a5085
floating-network-id=eb31cc74-96ba-4394-aef4-0e94bec46d85
use-octavia=True

(so it is looking for floating IPs on the correct network, and that subnet is the k8s internal subnet)

It all works.

So everything except "associate an IP" has worked.  Why does this step fail? Where has k8s logged what it did and how it failed?  I can only find docs for pod level logging (and my pod is fine, and serving it's test webpage just great).

(I have lots of quota remaining for 'make more floating ips', and several unused ones hanging around)


答:
You can add an observer to UIApplicationWillEnterForeground in your controllers.

Posted shortly before an app leaves the background state on its way to
  becoming the active app.

```<code>override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(self,selector: #selector(self.appEnteredFromBackground(_:)),name: NSNotification.Name.UIApplicationWillEnterForeground, object: nil)
}

@objc func appEnteredFromBackground(_ notification: NSNotification) {
    print("From background")
}
</code>```

Body:
You can add an observer to UIApplicationWillEnterForeground in your controllers.

Posted shortly before an app leaves the background state on its way to
  becoming the active app.

override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(self,selector: #selector(self.appEnteredFromBackground(_:)),name: NSNotification.Name.UIApplicationWillEnterForeground, object: nil)
}

@objc func appEnteredFromBackground(_ notification: NSNotification) {
    print("From background")
}


问:
How to refer a class instance with a local variable?

class A {
    x = 1;
};

let B = A;

function C(arg1: B){
    arg1.x
};
```

ERROR in [at-loader] ./src/syntax/colletion-range.ts:10:18
    TS2749: 'B' refers to a value, but is being used as a type here.

答:
Aliasing the class constructor using a variable will not also alias the type. Declaring a class produces both a value (the constructor) and a type (the instance type of the class).

You could define the type as well:

```<code>let B = A;
type B = A;
</code>```

You could also get the type of the class stored in B using typeof B and then get the instance type using InstanceType:

```<code>class A {
    x = 1;
};

let B = A;

function C(arg1: InstanceType<typeof B>){
    arg1.x
};
</code>```

Body:
class A {
    x = 1;
};

let B = A;

function C(arg1: B){
    arg1.x
};

ERROR in [at-loader] ./src/syntax/colletion-range.ts:10:18
    TS2749: 'B' refers to a value, but is being used as a type here.

Body:
Aliasing the class constructor using a variable will not also alias the type. Declaring a class produces both a value (the constructor) and a type (the instance type of the class).

You could define the type as well:

let B = A;
type B = A;

You could also get the type of the class stored in B using typeof B and then get the instance type using InstanceType:

class A {
    x = 1;
};

let B = A;

function C(arg1: InstanceType<typeof B>){
    arg1.x
};


问:
How to make a Grouping By using Collectors
I retrieve the data from a MongoDB database and I store them in a JSONObject after I add the JSONObject to a list each time in order to make the group by using Collectors (By date) I'm sure that the code of the group by is running correctly since I tested them in a simple example but the problem I have this display

```<code> while (traficCursor.hasNext()) {
        try {
            DBObject next = traficCursor.next();
            wordsArray = next.get("Date").toString().split("\\s+");
            jsonObject.put("DateComplete",wordsArray[0]);
            jsonObject.put("Heure",wordsArray[1]);
            for (String mapKeyInfo : next.keySet()) {
                jsonObject.put(mapKeyInfo,next.get(mapKeyInfo));
            }
            data.add(jsonObject);

        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
try {
        Map<Object, List<JSONObject>> groupbydate = data.stream()
                .map(json -> new AbstractMap.SimpleEntry<>(json.getString("Date"), json))
                .collect(Collectors.groupingBy(Map.Entry::getKey, Collectors.mapping(Map.Entry::getValue, Collectors.toList())));
        groupbydate.entrySet().forEach(gbd -> System.out.println(gbd.getValue()));
    } catch (Exception e) {
        e.printStackTrace();
    }
</code>```

[{"id_arc_trafic":"1","taux":"1360","DateComplete":"24/01/2018","_id":"5ce66598a4021f9e6224c699","debit":"61","Heure":"18:00","Date":"24/01/2018 18:00"},{"id_arc_trafic":"1","taux":"1360","DateComplete":"24/01/2018","_id":"5ce66598a4021f9e6224c699","debit":"61","Heure":"18:00","Date":"24/01/2018 18:00"},{"id_arc_trafic":"1","taux":"1360","DateComplete":"24/01/2018","_id":"5ce66598a4021f9e6224c699","debit":"61","Heure":"18:00","Date":"24/01/2018 18:00"}]
this is the last line of the JSONObject that repeats itself

this is what i want the grouping by Date which i display records by records grouping by Attribute Date

```<code>[{"id_arc_trafic":"1","taux":"100","DateComplete":"24/01/2018","_id":"5ce66598a4021f9e6224c699","debit":"250","Heure":"18:00","Date":"25/01/2018 18:00"}]
[{"id_arc_trafic":"1","taux":"1360","DateComplete":"25/01/2018","_id":"5ce66598a4021f9e6224c699","debit":"61","Heure":"18:00","Date":"25/01/2018 18:00"}]
[{"id_arc_trafic":"1","taux":"500","DateComplete":"27/01/2018","_id":"5ce66598a4021f9e6224c699","debit":"140","Heure":"18:00","Date":"27/01/2018 18:00"}]
</code>```

答:
jsonObject should get initialized inside the while loop:

```<code>jsonObject = new JSONObject();
</code>```

If you don't do this, you'll update every entry of data with the latest inserted object's values

Body:
I retrieve the data from a MongoDB database and I store them in a JSONObject after I add the JSONObject to a list each time in order to make the group by using Collectors (By date) I'm sure that the code of the group by is running correctly since I tested them in a simple example but the problem I have this display

 while (traficCursor.hasNext()) {
        try {
            DBObject next = traficCursor.next();
            wordsArray = next.get("Date").toString().split("\\s+");
            jsonObject.put("DateComplete",wordsArray[0]);
            jsonObject.put("Heure",wordsArray[1]);
            for (String mapKeyInfo : next.keySet()) {
                jsonObject.put(mapKeyInfo,next.get(mapKeyInfo));
            }
            data.add(jsonObject);

        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
try {
        Map<Object, List<JSONObject>> groupbydate = data.stream()
                .map(json -> new AbstractMap.SimpleEntry<>(json.getString("Date"), json))
                .collect(Collectors.groupingBy(Map.Entry::getKey, Collectors.mapping(Map.Entry::getValue, Collectors.toList())));
        groupbydate.entrySet().forEach(gbd -> System.out.println(gbd.getValue()));
    } catch (Exception e) {
        e.printStackTrace();
    }

[{"id_arc_trafic":"1","taux":"1360","DateComplete":"24/01/2018","_id":"5ce66598a4021f9e6224c699","debit":"61","Heure":"18:00","Date":"24/01/2018 18:00"},{"id_arc_trafic":"1","taux":"1360","DateComplete":"24/01/2018","_id":"5ce66598a4021f9e6224c699","debit":"61","Heure":"18:00","Date":"24/01/2018 18:00"},{"id_arc_trafic":"1","taux":"1360","DateComplete":"24/01/2018","_id":"5ce66598a4021f9e6224c699","debit":"61","Heure":"18:00","Date":"24/01/2018 18:00"}]
this is the last line of the JSONObject that repeats itself

this is what i want the grouping by Date which i display records by records grouping by Attribute Date

[{"id_arc_trafic":"1","taux":"100","DateComplete":"24/01/2018","_id":"5ce66598a4021f9e6224c699","debit":"250","Heure":"18:00","Date":"25/01/2018 18:00"}]
[{"id_arc_trafic":"1","taux":"1360","DateComplete":"25/01/2018","_id":"5ce66598a4021f9e6224c699","debit":"61","Heure":"18:00","Date":"25/01/2018 18:00"}]
[{"id_arc_trafic":"1","taux":"500","DateComplete":"27/01/2018","_id":"5ce66598a4021f9e6224c699","debit":"140","Heure":"18:00","Date":"27/01/2018 18:00"}]

Body:
jsonObject should get initialized inside the while loop:

jsonObject = new JSONObject();

If you don't do this, you'll update every entry of data with the latest inserted object's values


问:
MQL4 to C++ dll on microsoft Visual Studio 2017 Community
How can I create a DLL file in Microsoft Visual Studio 2017 Community that can not be decompiled
and transfer functions from my mq4 indicator to the DLL file and connect them together?

I do not know any language other than MQL4

答: I have not heard of any MQL programs being reverse engineered with the current compiler. The best way (in my opinion) in a DLL will be to write it in C++. Writing it in a DOTnet language will allow others to reverse engineer your code unless it is obfuscated. However, obfuscated code cannot be used to communicate with MT4.</p>


问:
How to organize and group test cases in XCUI test automation framework
I am using XCUI test framework for automating my iOS App test cases. I have separate tests for all modules. I need to specifically select particular cases from each module to set up a high level sanity run where I can run those tests alone. Do we have something similar to Selenium TestNG groups?

```<code>@Test (groups = { "bonding", "strong_ties" })
</code>```

something similar to this for iOS XCUI?

答:
You can arrange your tests using path-like strings.

As per xcodebuild documentation

The -only-testing and -skip-testing options, which are optional, allow you to run only a specific test and to skip a test, respectively. They take an argument , which specifies the test to be executed or excluded. test-identifier's format is as follows:

```<code>TestTarget[/TestClass[/TestMethod]]
</code>```

TestTarget, which is required, is the name of the test bundle. TestClass and TestMethod, which are both optional, respectively represent the name of the class and the name of the method to be tested.

Example usage:

```<code>xcodebuild -workspace Foo.xcworkspace \
-scheme Bar\
-sdk iphonesimulator \
-destination 'platform=iOS Simulator,name=iPhone SE,OS=12.3'
'-only-testing:TestGroup/TestClass' test
</code>```

Check out How to Get Started with XCUITest (iOS) for initial instructions.

You might also find EarlGrey framework useful

Body:
I am using XCUI test framework for automating my iOS App test cases. I have separate tests for all modules. I need to specifically select particular cases from each module to set up a high level sanity run where I can run those tests alone. Do we have something similar to Selenium TestNG groups?

@Test (groups = { "bonding", "strong_ties" })

something similar to this for iOS XCUI?

Body:
You can arrange your tests using path-like strings.

As per xcodebuild documentation

The -only-testing and -skip-testing options, which are optional, allow you to run only a specific test and to skip a test, respectively. They take an argument , which specifies the test to be executed or excluded. test-identifier's format is as follows:

TestTarget[/TestClass[/TestMethod]]

TestTarget, which is required, is the name of the test bundle. TestClass and TestMethod, which are both optional, respectively represent the name of the class and the name of the method to be tested.

Example usage:

xcodebuild -workspace Foo.xcworkspace \
-scheme Bar\
-sdk iphonesimulator \
-destination 'platform=iOS Simulator,name=iPhone SE,OS=12.3'
'-only-testing:TestGroup/TestClass' test

Check out How to Get Started with XCUITest (iOS) for initial instructions.

You might also find EarlGrey framework useful


问:
How can I place legend relative to text box?
I'd like to obtain this:

But the legend's frame should be perfectly right-aligned with the text box above it. Right now I'm using a poor, manual solution:

from matplotlib import pyplot as plt
fig, ax = plt.subplots()
for i in range(5):
  ax.plot([i, 0],label=i)

pad = 0.02
text = ax.text(1-pad, 1-pad, "Some words", bbox=dict(alpha=1),
    transform=ax.transAxes, ha="right", va="top")

# text_height = text.get_bbox_patch().get_height() # doesn't work
text_height=0.05

ax.legend(loc="upper right", bbox_to_anchor=(1-pad, 1-pad-text_height))
```

So how can I improve and automate this alignment?

Also, it would be nice if I could reasonably set the pad parameter automatically.

答:
Simply use title parameter:</p>

```<code>from matplotlib import pyplot as plt
fig, ax = plt.subplots()
for i in range(5):
   ax.plot([i, 0],label=i)

ax.legend(loc="upper right", title='some text')
plt.show()
</code>```

Body:
I'd like to obtain this:

But the legend's frame should be perfectly right-aligned with the text box above it. Right now I'm using a poor, manual solution:

from matplotlib import pyplot as plt
fig, ax = plt.subplots()
for i in range(5):
  ax.plot([i, 0],label=i)

pad = 0.02
text = ax.text(1-pad, 1-pad, "Some words", bbox=dict(alpha=1),
    transform=ax.transAxes, ha="right", va="top")

# text_height = text.get_bbox_patch().get_height() # doesn't work
text_height=0.05

ax.legend(loc="upper right", bbox_to_anchor=(1-pad, 1-pad-text_height))

So how can I improve and automate this alignment?

Also, it would be nice if I could reasonably set the pad parameter automatically.

Body:
Simply use title parameter:

from matplotlib import pyplot as plt
fig, ax = plt.subplots()
for i in range(5):
   ax.plot([i, 0],label=i)

ax.legend(loc="upper right", title='some text')
plt.show()


问:
Identify Locale Date string correctly
I have a date string that is formatted depending on the language/locale of the browser. For example, "03/05/2019" in en-US is March 5, 2019 (mm/dd/yyyy) but in en-NZ, it's May 3, 2019 (dd/mm/yyyy).

I need to know how to convert the string to date using JavaScript with the corresponding locale. I cannot hardcode the format because the locale really depends on the browser. I tried using Moment.js but I cannot seem to make it work. It returns invalid date for dates like "16/05/2019". It looks like it's not following the locale which I set to en-NZ.

Here is the momentjs code that I have tried:

```<code>moment().locale('en-NZ').format('L')
</code>```

This will return the en-NZ format of the current date which is 27/05/2019 but when I try to include a date string:

```<code>moment('16/05/2019').locale('en-NZ').format('L')
</code>```

This returns 'Invalid Date'. Any suggestions on how to do it or even a different plugin that I can use? Thanks.

答:
Per http://momentjs.com/docs/#/parsing/string-format/ you need to pass the format:

If you know the format of an input string, you can use that to parse a
  moment.

```<code>moment("12-25-1995", "MM-DD-YYYY");
</code>```

The parser ignores non-alphanumeric characters, so both of the
  following will return the same thing.

```<code>moment("12-25-1995", "MM-DD-YYYY");
moment("12/25/1995", "MM-DD-YYYY");
</code>```

The parsing tokens are similar to the formatting tokens used in
  moment#format.

Title: Identify Locale Date string correctly

Body:
I have a date string that is formatted depending on the language/locale of the browser. For example, "03/05/2019" in en-US is March 5, 2019 (mm/dd/yyyy) but in en-NZ, it's May 3, 2019 (dd/mm/yyyy).

I need to know how to convert the string to date using JavaScript with the corresponding locale. I cannot hardcode the format because the locale really depends on the browser. I tried using Moment.js but I cannot seem to make it work. It returns invalid date for dates like "16/05/2019". It looks like it's not following the locale which I set to en-NZ.

Here is the momentjs code that I have tried:

moment().locale('en-NZ').format('L')

This will return the en-NZ format of the current date which is 27/05/2019 but when I try to include a date string:

moment('16/05/2019').locale('en-NZ').format('L')

This returns 'Invalid Date'. Any suggestions on how to do it or even a different plugin that I can use? Thanks.

Body:
Per http://momentjs.com/docs/#/parsing/string-format/ you need to pass the format:

If you know the format of an input string, you can use that to parse a
  moment.

moment("12-25-1995", "MM-DD-YYYY");

The parser ignores non-alphanumeric characters, so both of the
  following will return the same thing.

moment("12-25-1995", "MM-DD-YYYY");
moment("12/25/1995", "MM-DD-YYYY");

The parsing tokens are similar to the formatting tokens used in
  moment#format.


问:
Server Error in '/' Application. with same route
I've been trying to figure this out but can't find any answers to my problem. The problem I am having is with this url:

```<code>localhost:343434/Lev/Details/1/4/CON/2
</code>```

This url will return a "Server Error in '/' Application". I know that my Action will return a value with theese parameters.

However, if I use the same route but with other parameters:

```<code>localhost:343434/Lev/Details/3/4/FHS/5
</code>```

It will call the action and return the result. The "Server Error in '/' Application" only appears when using "CON"

The outpus is this:

```<code>The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly.

Requested URL: /Lev/Details/1/4/CON/2
</code>```

And this is my route:

```<code>        routes.MapRoute(
                "LevRoute",
                "{controller}/{action}/{id}/{source}/{levtyp}/{Levid2}/{page}/{order}",
                new { controller = "Lev", action = "Details", page =       UrlParameter.Optional, order = UrlParameter.Optional  }

            );
</code>```

Thanks for help in advance!

答: You can use Route Debugger to debug routes</p>

Body:
I've been trying to figure this out but can't find any answers to my problem. The problem I am having is with this url:

localhost:343434/Lev/Details/1/4/CON/2

This url will return a "Server Error in '/' Application". I know that my Action will return a value with theese parameters.

However, if I use the same route but with other parameters:

localhost:343434/Lev/Details/3/4/FHS/5

It will call the action and return the result. The "Server Error in '/' Application" only appears when using "CON"

The outpus is this:

The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly.

Requested URL: /Lev/Details/1/4/CON/2

And this is my route:

        routes.MapRoute(
                "LevRoute",
                "{controller}/{action}/{id}/{source}/{levtyp}/{Levid2}/{page}/{order}",
                new { controller = "Lev", action = "Details", page =       UrlParameter.Optional, order = UrlParameter.Optional  }

            );

Thanks for help in advance!


问:
How to add custom menu for admin in Shopify?
I am newbie to Shopify. I want to create a custom menu for admin.

Example : I want to create  Vendors (Menu Name) for admin under Apps in Shopify.

Any option is there to create own custom menu for admin.

答:
You can't modify the Shopify admin in any way or form.

The dashboard is a closed platform ( not like WordPress ) where you can't modify/add/remove items or links.


问:
Retrofit 2 doesn't perform a request
My app is needed to connect to GitHub.com using OAuth 2.0. So I created the next API model:

```<code>interface IGitHubApi {
    @GET("login/oauth/access_token")
    fun getAccessToken(
        @Query("client_id") clientId: String = GitHub.CLIENT_ID,
        @Query("client_secret") clientSecret: String = GitHub.CLIENT_SECRET,
        @Query("code") code: String
    ): Single<String>
}
</code>```

I know I can provide a some class that will describe JSON structure and Gson will deserialize it automatically but I wanna see a simple JSON (as string).

After I created a component and module for Retrofit 2:

```<code>@Component(modules = [GitHubApiModule::class])
interface IGitHubApiComponent {
    fun getGitHubService(): IGitHubApi
}

@Module
class GitHubApiModule {

    @Provides
    fun provideGitHubApi(retrofit: Retrofit): IGitHubApi {
        return retrofit.create(IGitHubApi::class.java)
    }

    @Provides
    fun provideRetrofit(gsonConverterFactory: GsonConverterFactory,
                        rxJava2CallAdapterFactory: RxJava2CallAdapterFactory): Retrofit {
        return Retrofit.Builder()
            .baseUrl(GitHub.BASE_URL)
            .addConverterFactory(gsonConverterFactory)
            .addCallAdapterFactory(rxJava2CallAdapterFactory)
            .build()
    }

    @Provides
    fun provideGson(): Gson {
        val gsonBuilder = GsonBuilder()
        return gsonBuilder.create()
    }

    @Provides
    fun provideGsonConverterFactory(gson: Gson): GsonConverterFactory {
        return GsonConverterFactory.create(gson)
    }

    @Provides
    fun provideRxJava2CallAdapterFactory(): RxJava2CallAdapterFactory {
        return RxJava2CallAdapterFactory.create()
    }
}
</code>```

and connected Dagger 2 to my view model:

```<code>class AccountViewModel(app: Application) : AndroidViewModel(app) {

    var label: ObservableField<String> = ObservableField()
    var isLoading: ObservableBoolean = ObservableBoolean(true)
    var progress: ObservableInt = ObservableInt(0)
    private var gitHubApi: IGitHubApi = DaggerIGitHubApiComponent.create().getGitHubService()

    private fun getErrorMsg(app: Application, hasAccount: Boolean): String {
        return if (hasAccount) {
            app.getString(R.string.err_account_update_failed)
        } else {
            app.getString(R.string.err_account_creation_failed)
        }
    }

    fun createOrUpdateAccount(authorizationCode: String?) {
        val app = getApplication<App>()
        val accountType = app.getString(R.string.account_type_git)
        val accountManager = AccountManager.get(app.applicationContext)
        val accounts = accountManager.getAccountsByType(accountType)

        label.set(app.getString(R.string.msg_account_creating))

        if (authorizationCode == null) {
            val msg = getErrorMsg(app, accounts.isNotEmpty())
            label.set(msg)

            return //Break operation
        }

        gitHubApi.getAccessToken(code = authorizationCode)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeBy(
                onSuccess = {
                    label.set(it)
                    progress.set(100)
                    isLoading.set(false)
                },
                onError = {
                    Log.e("AccountViewModel", it.message?: "Could not retrieve an access token.", it)
                    val msg = getErrorMsg(app, accounts.isNotEmpty())
                    label.set(msg)
                }
            )
            .dispose()
    }
}
</code>```

When I run my app I just see Creating an account... label that means onSuccess and onError methods weren't called.

What am I doing wrongly? It must call onError at least and there is not any related errors in LogCat.

I've checked in debugger app retrieves an authorization code, it's not null.

答:
Primary reason: dispose() is essentially a cancel, and you won't receive success or error event after disposing.

AndroidStudio asks to call this method

subscribeBy() is annotated with @CheckReturnValue and Studio complains that you're ignoring the returned Disposable.

For fire-and-forget requests you can ignore the disposable and suppress the IDE warning.

If you want to scope the request and to be able to cancel it e.g. when navigating to another screen, you can store the Disposable to a variable and call dispose() on it in an appropriate lifecycle method. If you have multiple such requests, you can use CompositeDisposable to bundle them together.

In your comments you state you have a ViewModel. In a ViewModel, you can override onCleared() and dispose the call there.

Title: Retrofit 2 doesn't perform a request

Body:
My app is needed to connect to GitHub.com using OAuth 2.0. So I created the next API model:

interface IGitHubApi {
    @GET("login/oauth/access_token")
    fun getAccessToken(
        @Query("client_id") clientId: String = GitHub.CLIENT_ID,
        @Query("client_secret") clientSecret: String = GitHub.CLIENT_SECRET,
        @Query("code") code: String
    ): Single<String>
}

I know I can provide a some class that will describe JSON structure and Gson will deserialize it automatically but I wanna see a simple JSON (as string).

After I created a component and module for Retrofit 2:

@Component(modules = [GitHubApiModule::class])
interface IGitHubApiComponent {
    fun getGitHubService(): IGitHubApi
}

@Module
class GitHubApiModule {

    @Provides
    fun provideGitHubApi(retrofit: Retrofit): IGitHubApi {
        return retrofit.create(IGitHubApi::class.java)
    }

    @Provides
    fun provideRetrofit(gsonConverterFactory: GsonConverterFactory,
                        rxJava2CallAdapterFactory: RxJava2CallAdapterFactory): Retrofit {
        return Retrofit.Builder()
            .baseUrl(GitHub.BASE_URL)
            .addConverterFactory(gsonConverterFactory)
            .addCallAdapterFactory(rxJava2CallAdapterFactory)
            .build()
    }

    @Provides
    fun provideGson(): Gson {
        val gsonBuilder = GsonBuilder()
        return gsonBuilder.create()
    }

    @Provides
    fun provideGsonConverterFactory(gson: Gson): GsonConverterFactory {
        return GsonConverterFactory.create(gson)
    }

    @Provides
    fun provideRxJava2CallAdapterFactory(): RxJava2CallAdapterFactory {
        return RxJava2CallAdapterFactory.create()
    }
}

and connected Dagger 2 to my view model:

class AccountViewModel(app: Application) : AndroidViewModel(app) {

    var label: ObservableField<String> = ObservableField()
    var isLoading: ObservableBoolean = ObservableBoolean(true)
    var progress: ObservableInt = ObservableInt(0)
    private var gitHubApi: IGitHubApi = DaggerIGitHubApiComponent.create().getGitHubService()

    private fun getErrorMsg(app: Application, hasAccount: Boolean): String {
        return if (hasAccount) {
            app.getString(R.string.err_account_update_failed)
        } else {
            app.getString(R.string.err_account_creation_failed)
        }
    }

    fun createOrUpdateAccount(authorizationCode: String?) {
        val app = getApplication<App>()
        val accountType = app.getString(R.string.account_type_git)
        val accountManager = AccountManager.get(app.applicationContext)
        val accounts = accountManager.getAccountsByType(accountType)

        label.set(app.getString(R.string.msg_account_creating))

        if (authorizationCode == null) {
            val msg = getErrorMsg(app, accounts.isNotEmpty())
            label.set(msg)

            return //Break operation
        }

        gitHubApi.getAccessToken(code = authorizationCode)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeBy(
                onSuccess = {
                    label.set(it)
                    progress.set(100)
                    isLoading.set(false)
                },
                onError = {
                    Log.e("AccountViewModel", it.message?: "Could not retrieve an access token.", it)
                    val msg = getErrorMsg(app, accounts.isNotEmpty())
                    label.set(msg)
                }
            )
            .dispose()
    }
}

When I run my app I just see Creating an account... label that means onSuccess and onError methods weren't called.

What am I doing wrongly? It must call onError at least and there is not any related errors in LogCat.

I've checked in debugger app retrieves an authorization code, it's not null.


问:
Protractor typescript issue with Boolean true in if statement
I want if an element is not selected then only i should select it ,here I am using if else in typescript but it does't work for me</p>

```<code>let inputEle = element(by.xpath('//div[@class="pq-select-menu"]//span[text()="Users(1003)"]/preceding-sibling::input'));
console.log(await inputEle.isSelected()); //true or false
let val=inputEle.isSelected();

if (val== true){
    console.log('Is Already selected');
}else{
    await element(by.xpath('//*[@id="quincbody"]/*//div[contains(@class, "pq-select-menu")]//*[contains(text(),"Users(1003)")]')).click();
}
</code>```

答:
Protractor deals in promises. As such, val will be of Promise<boolean>
You could try this:

```<code>        let inputEle = element(by.xpath('//div[@class="pq-select-menu"]//span[text()="Users(1003)"]/preceding-sibling::input'));
        inputEle.isSelected().then(selected => {
            if (selected) {
                console.log('Is Already selected');
            } else {
                await element(by.xpath('//*[@id="quincbody"]/*//div[contains(@class, "pq-select-menu")]//*[contains(text(),"Users(1003)")]')).click();
            }
            // the rest of the code if there's any.
        });
</code>```

Body:
I want if an element is not selected then only i should select it ,here I am using if else in typescript but it does't work for me

let inputEle = element(by.xpath('//div[@class="pq-select-menu"]//span[text()="Users(1003)"]/preceding-sibling::input'));
console.log(await inputEle.isSelected()); //true or false
let val=inputEle.isSelected();

if (val== true){
    console.log('Is Already selected');
}else{
    await element(by.xpath('//*[@id="quincbody"]/*//div[contains(@class, "pq-select-menu")]//*[contains(text(),"Users(1003)")]')).click();
}

Body:
Protractor deals in promises. As such, val will be of Promise<boolean>
You could try this:

        let inputEle = element(by.xpath('//div[@class="pq-select-menu"]//span[text()="Users(1003)"]/preceding-sibling::input'));
        inputEle.isSelected().then(selected => {
            if (selected) {
                console.log('Is Already selected');
            } else {
                await element(by.xpath('//*[@id="quincbody"]/*//div[contains(@class, "pq-select-menu")]//*[contains(text(),"Users(1003)")]')).click();
            }
            // the rest of the code if there's any.
        });


问:
Spring JDBCTemplate : Construct JSON without special characters
I am reading table from postgreSQL DB and populating all columns and its values in a json object.

One of the column in postgre is of type json. So the output has lot of escape characters. like below for key dummykeyname.

```<code> {
        "XY": "900144",
        "id": 1,
        "date": 1556167980000,
        "type": "XX50",
        "dummykeyname": {
            "type": "json",
            "value": "{\"XXXX\": 14445.0, \"YYYY\": 94253.0}"
        }
 }
</code>```

I want the output to look like

```<code>  "value": "{"XXXX": 14445.0, "YYYY": 94253.0}"
</code>```

Code i used is

```<code>JSONArray entities = new JSONArray();

var rm = (RowMapper<?>) (ResultSet result, int rowNum) -> {

while (result.next()) {
    JSONObject entity = new JSONObject();
    ResultSetMetaData metadata = result.getMetaData();
    int columnCount = metadata.getColumnCount() + 1;
    IntStream.range(1, columnCount).forEach(nbr -> {
      try {
        entity.put(result.getMetaData().getColumnName(nbr), result.getObject(nbr));
      } catch (SQLException e) {
        LOGGER.error(e.getMessage());
      }
    });
    entities.add(entity);
  }
  return entities;
};
</code>```

Library used:

```<code>import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
</code>```

Please guide me where am i going wrong.

答:
Take a different approach.

1) first create a pojo of the required columns

```<code>  ex : if your table has 4 columns
         id, name, country, mobile create a class Employee and populate the class using rowmapper available in spring jdbc.
</code>```

2) create a class EmployeeList, which has List , add each Employee objects created out of rowmapper to declared list.

3) use

```<code>a) ObjectMapper mapper = new ObjectMapper();
b) mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
c) mapper.writeValueAsString(EmployeeListobjects);
</code>```

Body:
I am reading table from postgreSQL DB and populating all columns and its values in a json object.

One of the column in postgre is of type json. So the output has lot of escape characters. like below for key dummykeyname.

 {
        "XY": "900144",
        "id": 1,
        "date": 1556167980000,
        "type": "XX50",
        "dummykeyname": {
            "type": "json",
            "value": "{\"XXXX\": 14445.0, \"YYYY\": 94253.0}"
        }
 }

I want the output to look like

  "value": "{"XXXX": 14445.0, "YYYY": 94253.0}"

Code i used is

JSONArray entities = new JSONArray();

var rm = (RowMapper<?>) (ResultSet result, int rowNum) -> {

while (result.next()) {
    JSONObject entity = new JSONObject();
    ResultSetMetaData metadata = result.getMetaData();
    int columnCount = metadata.getColumnCount() + 1;
    IntStream.range(1, columnCount).forEach(nbr -> {
      try {
        entity.put(result.getMetaData().getColumnName(nbr), result.getObject(nbr));
      } catch (SQLException e) {
        LOGGER.error(e.getMessage());
      }
    });
    entities.add(entity);
  }
  return entities;
};

Library used:

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

Please guide me where am i going wrong.

Body:
Take a different approach.

1) first create a pojo of the required columns

  ex : if your table has 4 columns
         id, name, country, mobile create a class Employee and populate the class using rowmapper available in spring jdbc.

2) create a class EmployeeList, which has List , add each Employee objects created out of rowmapper to declared list.

3) use

a) ObjectMapper mapper = new ObjectMapper();
b) mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
c) mapper.writeValueAsString(EmployeeListobjects);


问:
Can we user both <circuitBreaker> with <failover> in apache camel
I need to send messages to two back-end IBM MQs in a failover + round robin manner, but I found that if one IBM MQ failed, the camel will still try the failed endpoint for each inbound message, which slows down the whole process.

I try to combine the circuit breaker, but camel doesn’t allow to use  with .

How could I ask the camel not to try a failed endpoint for a particular period of time?

答:
with error handler and exception clause

for example (java DSL) let's assume you are wrapping the exception you want to handle in a MyDelayedRetryableException:

```<code>onException(MyDelayedRetryableException.class)
    .useOriginalMessage()
    .redeliveryDelay(1000) \\ wait 1 second before retry
    .backOffMultiplier(2.0) \\every retry wait last delay multiplied this value (1000, 2000, 4000,...)
    .maximumRedeliveries(100) \\ attempts before giving up
    .retryAttemptedLogLevel(LoggingLevel.WARN)
    .useExponentialBackOff();
</code>```

The example above apply to all routes, you can also specify the error handling per route as well. There are multiple ways of doing what you are asking, for instance with the example above you can keep it general and use the onExceptionOccurred part to plug in some logic:

```<code>.onExceptionOccurred(
    exchange -> {
        //extra logic, like accessing the exchange headers
        log.error(exchange.getException() == null ? "no message" : exchange.getException().getMessage());
    }
)
</code>```

see https://camel.apache.org/error-handling-in-camel.html for more info

Body:
with error handler and exception clause

for example (java DSL) let's assume you are wrapping the exception you want to handle in a MyDelayedRetryableException:

onException(MyDelayedRetryableException.class)
    .useOriginalMessage()
    .redeliveryDelay(1000) \\ wait 1 second before retry
    .backOffMultiplier(2.0) \\every retry wait last delay multiplied this value (1000, 2000, 4000,...)
    .maximumRedeliveries(100) \\ attempts before giving up
    .retryAttemptedLogLevel(LoggingLevel.WARN)
    .useExponentialBackOff();

The example above apply to all routes, you can also specify the error handling per route as well. There are multiple ways of doing what you are asking, for instance with the example above you can keep it general and use the onExceptionOccurred part to plug in some logic:

.onExceptionOccurred(
    exchange -> {
        //extra logic, like accessing the exchange headers
        log.error(exchange.getException() == null ? "no message" : exchange.getException().getMessage());
    }
)

see https://camel.apache.org/error-handling-in-camel.html for more info


问:
How can I get files within the tests in Python?
I have the following package structure:

```<code>.
├── my_app
│   ├── app.py
│   ├── cli.py
│   ├── db.py
│   └── __init__.py
├── setup.py
├── tests
│   ├── data
│   │   └── foobar.gz
│   ├── test_app.py
│   └── test_database.py
└── tox.ini
</code>```

Within test_app.py, I do this:

```<code>import pkg_resources
path = '../tests/data/foobar.gz'
full_path = pkg_resources.resource_filename(__name__, path)
</code>```

Now I've seen the message:

```<code>/usr/local/lib/python3.7/site-packages/pkg_resources/__init__.py:1145:
  DeprecationWarning: Use of .. or absolute path in a resource path
  is not allowed and will raise exceptions in a future release.
self, resource_name
</code>```

What should I do instead?

(I could also change the structure of the package, but I would like to keep the test data within the tests - it is not necessary for running the application)

答:
To get a path relative to your script directory, try to work with the script location itself:

```<code>import sys
print(sys.argv[0])
</code>```

You can get the directory containing the script using os.path.dirname():

```<code>import os
import sys
print(os.path.dirname(sys.argv[0]))
</code>```

Then, os.path.join() might help to create arbitrary paths:

```<code>import os
import sys
print(os.path.join(os.path.dirname(sys.argv[0]), "some_subdir"))
</code>```

HTH!

Body:
I have the following package structure:

.
├── my_app
│   ├── app.py
│   ├── cli.py
│   ├── db.py
│   └── __init__.py
├── setup.py
├── tests
│   ├── data
│   │   └── foobar.gz
│   ├── test_app.py
│   └── test_database.py
└── tox.ini

Within test_app.py, I do this:

import pkg_resources
path = '../tests/data/foobar.gz'
full_path = pkg_resources.resource_filename(__name__, path)

Now I've seen the message:

/usr/local/lib/python3.7/site-packages/pkg_resources/__init__.py:1145:
  DeprecationWarning: Use of .. or absolute path in a resource path
  is not allowed and will raise exceptions in a future release.
self, resource_name

What should I do instead?

(I could also change the structure of the package, but I would like to keep the test data within the tests - it is not necessary for running the application)

Body:
To get a path relative to your script directory, try to work with the script location itself:

import sys
print(sys.argv[0])

You can get the directory containing the script using os.path.dirname():

import os
import sys
print(os.path.dirname(sys.argv[0]))

Then, os.path.join() might help to create arbitrary paths:

import os
import sys
print(os.path.join(os.path.dirname(sys.argv[0]), "some_subdir"))

HTH!


答:
Even though not ideal, there are a few ways in which to identify a date string.

In your case, I would try and use the language API available in newer browsers.

```<code>if(navigator.language=="en-US"){
    //USA Date Format
}else{
   //NZ Date Format
}
</code>```

You could expand this using the full list of countries: https://en.wikipedia.org/wiki/Date_format_by_country

See Get Locale Short Date Format using javascript for a full list of languages and formats that could be used.

I would also advice using Luxon over Moment.JS as it is more future proof and supports locales.

Title: Identify Locale Date string correctly

Body:
Even though not ideal, there are a few ways in which to identify a date string.

In your case, I would try and use the language API available in newer browsers.

if(navigator.language=="en-US"){
    //USA Date Format
}else{
   //NZ Date Format
}

You could expand this using the full list of countries: https://en.wikipedia.org/wiki/Date_format_by_country

See Get Locale Short Date Format using javascript for a full list of languages and formats that could be used.

I would also advice using Luxon over Moment.JS as it is more future proof and supports locales.


问:
How to alias object through xstream?
I've got an object which contains list of strings. How is it possible to define that the String.class should be serialized with alias "somealias" instead of "string" through annotations?</p>

答:
```<code>@XStreamImplicit(itemFieldName="somealias")
private List<String> content;
</code>```

Title: How to alias object through xstream?


问:
How to get the dynamic user groups of the active windows user?
How do I get the dynamic/virtual groups the active user is a member of in VBA? I tried the solution of this question: Determining a User's Group Membership using VBA

This means I tried this code:

```<code>Public Function UserIsInGroup(GroupName As String, _
                              Optional Username As String, _
                              Optional Domain As String) As Boolean
Dim strUsername As String
Dim objGroup    As Object
Dim objUser     As Object
Dim objNetwork  As Object

UserIsInGroup = False

If Username = "" Then
    Set objNetwork = CreateObject("WScript.Network")
    strUsername = objNetwork.UserDomain & "/" & objNetwork.Username
Else
    strUsername = Username
End If

strUsername = Replace(strUsername, "\", "/")
If InStr(strUsername, "/") Then
    ' No action: Domain has already been supplied in the user name
Else
    If Domain = "" Then
        Set objNetwork = CreateObject("WScript.Network")
        Domain = objNetwork.UserDomain
    End If
    strUsername = Domain & "/" & strUsername
End If

Set objUser = GetObject("WinNT://" & strUsername & ",user")
If objUser Is Nothing Then
    ' Insert error-handler here if you want to report an unknown user name
Else
    For Each objGroup In objUser.Groups
        Debug.Print objGroup.Name
        If GroupName = objGroup.Name Then
            UserIsInGroup = True
            Exit For
        End If
    Next objGroup
End If

Set objNetwork = Nothing
Set objGroup = Nothing
Set objUser = Nothing

End Function
</code>```

but it seems only to return the active directory (AD) groups. The groups I am interested in (And which I can see in cmd "whoami /groups") are not listed.

So how do I find out which dynamic groups the current user is part of?

答:
The user groups I was searching for where the "Token-Groups" querable via the UserToken.

I did this with the following code:

```<code>Enum TokenInformation
  TokenUser = 1
  TokenGroups = 2
End Enum

Private Const TOKEN_READ As Long = &H20008

Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (pTo As Any, uFrom As Any, ByVal lSize As Long)
Private Declare Function GetCurrentProcess Lib "kernel32" () As Long
Private Const GetCurrentProcessFail As Long = 0

Private Declare Function OpenProcessToken Lib "advapi32.dll" (ByVal ProcessHandle As Long, ByVal DesiredAccess As Long, TokenHandle As Long) As Long
Private Const OpenProcessTokenFail As Long = 0
Private Declare Function GetTokenInformation Lib "advapi32.dll" (ByVal TokenHandle As Long, ByVal TokenInformationClass As Long, TokenInformation As Any, ByVal TokenInformationLength As Long, ReturnLength As Long) As Long
Private Const GetTokenInformationFail As Long = 0
Private Declare Function ConvertSidToStringSid Lib "advapi32.dll" Alias "ConvertSidToStringSidA" (ByVal lpSid As Long, lpString As Long) As Long
Private Declare Function LocalFree Lib "kernel32" (ByVal hMem As Long) As Long
Private Declare Function lstrlen Lib "kernel32" Alias "lstrlenA" (ByVal lpString As Long) As Long

Private Type SID_AND_ATTRIBUTES
  Sid             As Long
  Attributes      As Long
End Type

Private Type VB_TOKEN_GROUPS
  GroupCount      As Long
  Groups()        As SID_AND_ATTRIBUTES
End Type

Private Const SizeDword As Long = 4

Public Function fn_checkForTokenGroup(ByVal par_UserGroupSid As String) As Boolean

  Dim dPseudoProcessHandle As Long
  Dim dTokenHandler As Long
  Dim dNeeded As Long
  Dim dReadBuffer() As Byte
  Dim dStringBuffer As String
  Dim dStringPointer As Long
  Dim dGroupData As VB_TOKEN_GROUPS

  On Error GoTo fn_checkForTokenGroup_error

  fn_checkForTokenGroup = False

  dPseudoProcessHandle = GetCurrentProcess()
  If dPseudoProcessHandle <> GetCurrentProcessFail Then
    If OpenProcessToken(dPseudoProcessHandle, TOKEN_READ, dTokenHandler) <> OpenProcessTokenFail Then
      Call GetTokenInformation(dTokenHandler, TokenInformation.TokenGroups, ByVal 0, 0, dNeeded)
      ReDim dReadBuffer(0 To dNeeded)
      If GetTokenInformation(dTokenHandler, TokenInformation.TokenGroups, dReadBuffer(0), UBound(dReadBuffer), dNeeded) <> GetTokenInformationFail Then
        Call CopyMemory(dGroupData.GroupCount, dReadBuffer(0), SizeDword)
        ReDim dGroupData.Groups(0 To dGroupData.GroupCount - 1)
        Call CopyMemory(dGroupData.Groups(0), dReadBuffer(SizeDword), dGroupData.GroupCount * Len(dGroupData.Groups(0)))

        Dim i As Long
        For i = 0 To dGroupData.GroupCount - 1
          If ConvertSidToStringSid(dGroupData.Groups(i).Sid, dStringPointer) Then
            dStringBuffer = Space(lstrlen(dStringPointer))
            Call CopyMemory(ByVal dStringBuffer, ByVal dStringPointer, Len(dStringBuffer))
            Call LocalFree(dStringPointer)
            If (dStringBuffer = par_UserGroupSid) Then
              fn_checkForTokenGroup = True
              GoTo fn_checkForTokenGroup_endeSchleife:
            End If
          End If
        Next
fn_checkForTokenGroup_endeSchleife:

      End If
      Call CloseHandle(dTokenHandler)
    End If
    Call CloseHandle(dPseudoProcessHandle)
  End If

fn_checkForTokenGroup_exit:

  Exit Function

fn_checkForTokenGroup_error:
  Call MsgBox(ModuleName, "CheckForTokenGroup")
  GoTo fn_checkForTokenGroup_exit:
End Function
</code>```

Body:
How do I get the dynamic/virtual groups the active user is a member of in VBA? I tried the solution of this question: Determining a User's Group Membership using VBA

This means I tried this code:

Public Function UserIsInGroup(GroupName As String, _
                              Optional Username As String, _
                              Optional Domain As String) As Boolean
Dim strUsername As String
Dim objGroup    As Object
Dim objUser     As Object
Dim objNetwork  As Object

UserIsInGroup = False

If Username = "" Then
    Set objNetwork = CreateObject("WScript.Network")
    strUsername = objNetwork.UserDomain & "/" & objNetwork.Username
Else
    strUsername = Username
End If

strUsername = Replace(strUsername, "\", "/")
If InStr(strUsername, "/") Then
    ' No action: Domain has already been supplied in the user name
Else
    If Domain = "" Then
        Set objNetwork = CreateObject("WScript.Network")
        Domain = objNetwork.UserDomain
    End If
    strUsername = Domain & "/" & strUsername
End If

Set objUser = GetObject("WinNT://" & strUsername & ",user")
If objUser Is Nothing Then
    ' Insert error-handler here if you want to report an unknown user name
Else
    For Each objGroup In objUser.Groups
        Debug.Print objGroup.Name
        If GroupName = objGroup.Name Then
            UserIsInGroup = True
            Exit For
        End If
    Next objGroup
End If

Set objNetwork = Nothing
Set objGroup = Nothing
Set objUser = Nothing

End Function

but it seems only to return the active directory (AD) groups. The groups I am interested in (And which I can see in cmd "whoami /groups") are not listed.

So how do I find out which dynamic groups the current user is part of?

Body:
The user groups I was searching for where the "Token-Groups" querable via the UserToken.

I did this with the following code:

Enum TokenInformation
  TokenUser = 1
  TokenGroups = 2
End Enum

Private Const TOKEN_READ As Long = &H20008

Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (pTo As Any, uFrom As Any, ByVal lSize As Long)
Private Declare Function GetCurrentProcess Lib "kernel32" () As Long
Private Const GetCurrentProcessFail As Long = 0

Private Declare Function OpenProcessToken Lib "advapi32.dll" (ByVal ProcessHandle As Long, ByVal DesiredAccess As Long, TokenHandle As Long) As Long
Private Const OpenProcessTokenFail As Long = 0
Private Declare Function GetTokenInformation Lib "advapi32.dll" (ByVal TokenHandle As Long, ByVal TokenInformationClass As Long, TokenInformation As Any, ByVal TokenInformationLength As Long, ReturnLength As Long) As Long
Private Const GetTokenInformationFail As Long = 0
Private Declare Function ConvertSidToStringSid Lib "advapi32.dll" Alias "ConvertSidToStringSidA" (ByVal lpSid As Long, lpString As Long) As Long
Private Declare Function LocalFree Lib "kernel32" (ByVal hMem As Long) As Long
Private Declare Function lstrlen Lib "kernel32" Alias "lstrlenA" (ByVal lpString As Long) As Long

Private Type SID_AND_ATTRIBUTES
  Sid             As Long
  Attributes      As Long
End Type

Private Type VB_TOKEN_GROUPS
  GroupCount      As Long
  Groups()        As SID_AND_ATTRIBUTES
End Type

Private Const SizeDword As Long = 4

Public Function fn_checkForTokenGroup(ByVal par_UserGroupSid As String) As Boolean

  Dim dPseudoProcessHandle As Long
  Dim dTokenHandler As Long
  Dim dNeeded As Long
  Dim dReadBuffer() As Byte
  Dim dStringBuffer As String
  Dim dStringPointer As Long
  Dim dGroupData As VB_TOKEN_GROUPS

  On Error GoTo fn_checkForTokenGroup_error

  fn_checkForTokenGroup = False

  dPseudoProcessHandle = GetCurrentProcess()
  If dPseudoProcessHandle <> GetCurrentProcessFail Then
    If OpenProcessToken(dPseudoProcessHandle, TOKEN_READ, dTokenHandler) <> OpenProcessTokenFail Then
      Call GetTokenInformation(dTokenHandler, TokenInformation.TokenGroups, ByVal 0, 0, dNeeded)
      ReDim dReadBuffer(0 To dNeeded)
      If GetTokenInformation(dTokenHandler, TokenInformation.TokenGroups, dReadBuffer(0), UBound(dReadBuffer), dNeeded) <> GetTokenInformationFail Then
        Call CopyMemory(dGroupData.GroupCount, dReadBuffer(0), SizeDword)
        ReDim dGroupData.Groups(0 To dGroupData.GroupCount - 1)
        Call CopyMemory(dGroupData.Groups(0), dReadBuffer(SizeDword), dGroupData.GroupCount * Len(dGroupData.Groups(0)))

        Dim i As Long
        For i = 0 To dGroupData.GroupCount - 1
          If ConvertSidToStringSid(dGroupData.Groups(i).Sid, dStringPointer) Then
            dStringBuffer = Space(lstrlen(dStringPointer))
            Call CopyMemory(ByVal dStringBuffer, ByVal dStringPointer, Len(dStringBuffer))
            Call LocalFree(dStringPointer)
            If (dStringBuffer = par_UserGroupSid) Then
              fn_checkForTokenGroup = True
              GoTo fn_checkForTokenGroup_endeSchleife:
            End If
          End If
        Next
fn_checkForTokenGroup_endeSchleife:

      End If
      Call CloseHandle(dTokenHandler)
    End If
    Call CloseHandle(dPseudoProcessHandle)
  End If

fn_checkForTokenGroup_exit:

  Exit Function

fn_checkForTokenGroup_error:
  Call MsgBox(ModuleName, "CheckForTokenGroup")
  GoTo fn_checkForTokenGroup_exit:
End Function


问:
Fast way to find number of common items python
I have a large data of 145000 items (a bill of materials) and I want to check the % of shared items between two bill of materials.

Two for loops or other methods always run in similar time periods.

What is the fastest way to do this?

First&secondbill are the lists with components in them:

```<code>for FKid in FirstBill:
      for SKid in SecondBill:
            CommonChild = (CommonChild + 1) if FKid == SKid else CommonChild
    return CommonChilds / len(FirstBill)
</code>```

答:
Assuming that ids in the bills are unique, a simpler answer would be:

```<code>percentage = sum([1 for fkid in FirstBill if fkid in SecondBill]) / len(FirstBill) * 100
</code>```

or

```<code>percentage = len(set(FirstBill).intersection(set(SecondBill))) / len(FirstBill) * 100
</code>```

Body:
I have a large data of 145000 items (a bill of materials) and I want to check the % of shared items between two bill of materials.

Two for loops or other methods always run in similar time periods.

What is the fastest way to do this?

First&secondbill are the lists with components in them:

for FKid in FirstBill:
      for SKid in SecondBill:
            CommonChild = (CommonChild + 1) if FKid == SKid else CommonChild
    return CommonChilds / len(FirstBill)

Body:
Assuming that ids in the bills are unique, a simpler answer would be:

percentage = sum([1 for fkid in FirstBill if fkid in SecondBill]) / len(FirstBill) * 100

or

percentage = len(set(FirstBill).intersection(set(SecondBill))) / len(FirstBill) * 100


问:
How to decrypt asp.net owin token in asp.net core manually?
I have an existing application which generates owin identity token with machine key approach. The same token is used to authenticate various application. One of the application is now in asp.net core. Is there any way to use same owin generated identity token in asp.net core?

or we can decode that token manually in asp.net core

答:
You can decrypt the Access Token returned from the authorization code flow directly by using IDataProtector.  we implement the IDataProtector interface and use the System.Web.Security.MachineKey.Unprotect method.
 To Make helper Method to decrypt the OWIN ticket

```<code>private class MachineKeyProtector : IDataProtector
{
    private readonly string[] _purpose =
    {
        typeof(OAuthAuthorizationServerMiddleware).Namespace,
        "Access_Token",
        "v1"
    };

    public byte[] Protect(byte[] userData)
    {
        //throw new NotImplementedException();
    }

    public byte[] Unprotect(byte[] protectedData)
    {
        return System.Web.Security.MachineKey.Unprotect(protectedData, _purpose);
    }
}
</code>```

To get ClaimsIdentity and a Dictionary of Properties. we just create an instance and pass in the Token to get the decrypted Ticket

```<code>var secureDataFormat = new TicketDataFormat(new MachineKeyProtector());
AuthenticationTicket ticket = secureDataFormat.Unprotect(accessToken);
</code>```

Above  AuthenticationTicket itself contains the ClaimsIdentity and a Dictionary of Properties.
refer IDataProtector Interface

Body:
You can decrypt the Access Token returned from the authorization code flow directly by using IDataProtector.  we implement the IDataProtector interface and use the System.Web.Security.MachineKey.Unprotect method.
 To Make helper Method to decrypt the OWIN ticket

private class MachineKeyProtector : IDataProtector
{
    private readonly string[] _purpose =
    {
        typeof(OAuthAuthorizationServerMiddleware).Namespace,
        "Access_Token",
        "v1"
    };

    public byte[] Protect(byte[] userData)
    {
        //throw new NotImplementedException();
    }

    public byte[] Unprotect(byte[] protectedData)
    {
        return System.Web.Security.MachineKey.Unprotect(protectedData, _purpose);
    }
}

To get ClaimsIdentity and a Dictionary of Properties. we just create an instance and pass in the Token to get the decrypted Ticket

var secureDataFormat = new TicketDataFormat(new MachineKeyProtector());
AuthenticationTicket ticket = secureDataFormat.Unprotect(accessToken);

Above  AuthenticationTicket itself contains the ClaimsIdentity and a Dictionary of Properties.
refer IDataProtector Interface


问:
Can Xtext be used for parsing general purpose programming languages?
I'm currently developing a general-purpose agent-based programming language (its syntaxt will be somewhat inspired by Java, and we are also using object in this language).

Since the beginning of the project we were doubtful about the fact of using ANTLR or Xtext. At that time we found out that Xtext was implementing a subset of the feature of ANTLR. So we decided to use ANLTR for our language losing the possibility to have a full-fledged Eclipse editor for free for our language (such a nice features provided by Xtext).

However, as the best of my knowledge, this summer the Xtext project has done a big step forward. Quoting from the link:

What are the limitations of Xtext?

Sven: You can implement almost any kind of programming language or DSL
  with Xtext. There is one exception, that is if you need to use so
  called  'Semantic Predicates' which is a rather complicated thing I
  don't think is worth being explained here. Very few languages really
  need this concept. However the prominent example is C/C++.  We want to
  look into that topic for the next release.

And that is also reinforced in the Xtext documentation:

What is Xtext? No matter if you want to create a small textual domain-specific language (DSL) or you want to implement a full-blown
  general purpose programming language. With Xtext you can create your
  very own languages in a snap. Also if you already have an existing
  language but it lacks decent tool support, you can use Xtext to create
  a sophisticated Eclipse-based development environment providing
  editing experience known from modern Java IDEs in a surprisingly short
  amount of time. We call Xtext a language development framework.

If Xtext has got rid of its past limitations why is it still not possible to find a complex Xtext grammar for the best known programming languages (Java, C#, etc.)?

On the ANTLR website you can find tons of such grammar examples, for what concerns Xtext instead the only sample I was able to find is the one reported in the documentation. So maybe Xtext is still not mature to be used for implementing a general purpose programming language? I'm a bit worried about this... I would not start to re-write the grammar in Xtext for then to recognize that it was not suited for that.

答:
I can't speak for what Xtext is or does well.

I can speak to the problem of developing robust tools for processing real languages, based on our experience with the DMS Software Reengineering Toolkit, which we imagine is a language manipulation framework.

First, parsing of real languages usually involves something messy in lexing and/or parsing, due to the historical ways these languages have evolved.   Java is pretty clean.  C# has context-dependent keywords and a rudimentary preprocessor sort of like C's.    C has a full blown preprocessor.  C++ is famously "hard to parse" due to ambiguities in the grammar and shenanigans with template syntax.   COBOL is fairly ugly, doesn't have any reference grammars, and comes in a variety of dialects.   PHP will turn you to stone if you look at it because it is so poorly defined.  (DMS has parsers for all of these, used in anger on real applications).

Yet you can parse all of these with most of the available parsing technologies if you try hard enough, usually by abusing the lexer or the parser to achieve your goals (how the GNU guys abused Bison to parse C++ by tangling lexical analysis with symbol table lookup is a nice ugly case in point).  But it takes a lot of effort to get the language details right, and the reference manuals are only close approximations of the truth with respect to what the compilers really accept.

If Xtext has a decent parsing engine, one can likely do this with Xtext.  A brief perusal of the Xtext site sounds like the lexers and parsers are fairly decent.  I didn't see anything about the "Semantic Predicate"s; we have them in DMS and they are lifesavers in some of the really dark corners of parsing.  Even using the really good parsing technology (we use GLR parsers), it would be very hard to parse COBOL data declarations (extracting their nesting structure during the parse) without them.

You have an interesting problem in that your language isn't well defined yet.  That will make your initial parsers somewhat messy, and you'll revise them a lot.  Here's where strong parsing technology helps you: if you can revise your grammar easily you can focus on what you want your language to look like, rather than focusing on fighting the lexer and parser.  The fact that you can change your language definition means in fact that if Xtext has some limitations, you can probably bend your language syntax to match without huge amounts of pain.  ANTLR does have the proven ability to parse a language pretty much as you imagine it, modulo the usual amount of parser hacking.

What is never discussed is what else is needed to process a language for real.  The first thing you need to be able to do is to construct ASTs, which ANTLR and YACC will help you do; I presume Xtext does also.  You also need symbol tables, control and data flow analysis (both local and global), and machinery to transform your language into something else (presumably more executable).  Doing just symbol tables you will find surprisingly hard; C++ has several hundred pages of "how to look up an identifier"; Java generics are a lot tougher to get right than you might expect.  You might also want to prettyprint the AST back to source code, if you want to offer refactorings.  (EDIT: Here both ANTLR and Xtext offer what amounts to text-template driven code generation).

Yet these are complex mechanisms that take as much time, if not more than building the parser.  The reason DMS exists isn't because it can parse (we view this just as the ante in a poker game), but because all of this other stuff is very hard and we wanted to amortize the cost of doing it all (DMS has, we think, excellent support for all of these mechanisms but YMMV).

On reading the Xtext overview, it sounds like they have some support for symbol tables but it is unclear what kind of assumption is behind it (e.g., for C++ you have to support multiple inheritance and namespaces).

If you are already started down the ANTLR road and have something running, I'd be tempted to stay the course; I doubt if Xtext will offer you a lot of additional help.  If you really really want Xtext's editor, then you can probably switch at the price of restructuring what grammar you have (this is a pretty typical price to pay when changing parsing paradigms).  Expect most of your work to appear after you get the parser right, in an ad hoc way.  I doubt you will find Xtext or ANTLR much different here.


问:
Why select returns only the first value?
There are two values in function. Input and select, everything works normally except that the select returns the first value (px). Where did I get it wrong?</p>

```<code><input id="width" onchange="Width()" type="number" placeholder="0" min="" max="" step="0.1">

<select id="widthpixselpercentage" onchange="Width()" >
<option value="px">px</option>
<option value="%">%</option>
</select>

<div id="someDiv"></div>
</code>```

```<code>function Width(){
var x = document.getElementById("width").value;
var y = document.getElementById("widthpixselpercentage").value;
        document.getElementById(someDiv).style.width = x + y;

}
</code>```

答:
If you want value from select box by using javascript:

```<code>var select_box = document.getElementById("widthpixselpercentage");
var y = select_box.options[select_box.selectedIndex].value;
</code>```

If you want text from select box by using javascript:

```<code>var select_box = document.getElementById("widthpixselpercentage");
var y = select_box.options[select_box.selectedIndex].text;
</code>```

Please try the following:

function Width(){
var x = document.getElementById("width").value;
var select_box = document.getElementById("widthpixselpercentage");
var y = select_box.options[select_box.selectedIndex].value;
        document.getElementById("someDiv").style.width = x + y;

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#someDiv{
border:1px solid;
height:5px;
}</code>```

<input id="width" onchange="Width()" type="number" placeholder="0" min="" max="" step="0.1">

<select id="widthpixselpercentage" onchange="Width()" >
<option value="px">px</option>
<option value="%">%</option>
</select>

```

Body:
There are two values in function. Input and select, everything works normally except that the select returns the first value (px). Where did I get it wrong?

<input id="width" onchange="Width()" type="number" placeholder="0" min="" max="" step="0.1">

<select id="widthpixselpercentage" onchange="Width()" >
<option value="px">px</option>
<option value="%">%</option>
</select>

function Width(){
var x = document.getElementById("width").value;
var y = document.getElementById("widthpixselpercentage").value;
        document.getElementById(someDiv).style.width = x + y;

}

Body:
If you want value from select box by using javascript:

var select_box = document.getElementById("widthpixselpercentage");
var y = select_box.options[select_box.selectedIndex].value;

If you want text from select box by using javascript:

var select_box = document.getElementById("widthpixselpercentage");
var y = select_box.options[select_box.selectedIndex].text;

Please try the following:

function Width(){
var x = document.getElementById("width").value;
var select_box = document.getElementById("widthpixselpercentage");
var y = select_box.options[select_box.selectedIndex].value;
        document.getElementById("someDiv").style.width = x + y;

}

#someDiv{
border:1px solid;
height:5px;
}

<input id="width" onchange="Width()" type="number" placeholder="0" min="" max="" step="0.1">

<select id="widthpixselpercentage" onchange="Width()" >
<option value="px">px</option>
<option value="%">%</option>
</select>

<div id="someDiv"></div>


问:
Uses of T extends U?
Lately I encountered a method defined similar to this and I don't exactly understand its usage:

```<code>public static <T, U extends T> T foo(U u) { ... }
</code>```

A sample use could be like this:

```<code>// Baz is just the containing class of foo()
Number n = Baz.foo(1);
</code>```

Where T is inferred to Number and U (probably) to Integer. But I can't wrap my head around when this is superior to e.g. this method definition:

```<code>public static <T> T bar(T t) { ... }
</code>```

If I call it like this:

```<code>Number n = Baz.bar(2);
</code>```

The code still works. T is inferred to either Number or Integer (Don't know if the argument type, in this example Integer is preferred over the call site return type Number)

I've read these questions: 1, 2 but I still don't know if the first method with 2 parameters has any advantage over the second method with only one generic.

答:
The first method

public static <T, U extends T> T foo(U u) { ... }
```

<p>means that <code>T</code> and <code>U</code> can be different types. I.e. one type <code>T</code> and one type <code>U</code> that is a sub-type of <code>T</code>.</p>

<p>With your second example</p>

<pre class="lang-java prettyprint-override"><code>public static <T> T bar(T t) { ... }
</code>```

bar(T t) must return the same type as argument t is. It can not return an object of a type that is a super-class to the argument type. That would only be possible with your first variant.

Title: Uses of T extends U?

Body:
Lately I encountered a method defined similar to this and I don't exactly understand its usage:

public static <T, U extends T> T foo(U u) { ... }

A sample use could be like this:

// Baz is just the containing class of foo()
Number n = Baz.foo(1);

Where T is inferred to Number and U (probably) to Integer. But I can't wrap my head around when this is superior to e.g. this method definition:

public static <T> T bar(T t) { ... }

If I call it like this:

Number n = Baz.bar(2);

The code still works. T is inferred to either Number or Integer (Don't know if the argument type, in this example Integer is preferred over the call site return type Number)

I've read these questions: 1, 2 but I still don't know if the first method with 2 parameters has any advantage over the second method with only one generic.

Body:
The first method

public static <T, U extends T> T foo(U u) { ... }

means that T and U can be different types. I.e. one type T and one type U that is a sub-type of T.

With your second example

public static <T> T bar(T t) { ... }

bar(T t) must return the same type as argument t is. It can not return an object of a type that is a super-class to the argument type. That would only be possible with your first variant.


答:
This is handy when you want to return a super type; exactly like you showed in your example.

You take a U as input and return a T - which is a super-type of U; the other way around to declare this would be T super U - but this is not legal in java.

This should be an example of what I mean actually. Suppose a very simple class like:

```<code>static class Holder<T> {

    private final T t;

    public Holder(T t) {
        this.t = t;
    }

    public <U super T> U whenNull(U whenNull){
        return t == null ? whenNull : t;
    }
}
</code>```

Method whenNull as it is defined would not compile, as U super T is not allowed in java.

Instead you could add another type parameter and invert the types:

```<code>static class Holder<U, T extends U> {

    private final T t;

    public Holder(T t) {
        this.t = t;
    }

    public U whenNull(U whenNull) {
        return t == null ? whenNull : t;
    }
}
</code>```

And usage would be:

```<code>Holder<Number, Integer> n = new Holder<>(null);
Number num = n.whenNull(22D);
</code>```

this allows to return a super type; but it looks very weird. We have added another type in the class declaration.

We could resort to:

```<code>static class Holder<T> {

    private final T t;

    public Holder(T t) {
        this.t = t;
    }

    public static <U, T extends U> U whenNull(U whenNull, Holder<T> holder) {
        return holder.t == null ? whenNull : holder.t;
    }
}
</code>```

or even make this method static.

For an existing limitation, you could try to do:

```<code>Optional.ofNullable(<SomeSubTypeThatIsNull>)
        .orElse(<SomeSuperType>)
</code>```

Title: Uses of T extends U?

Body:
This is handy when you want to return a super type; exactly like you showed in your example.

You take a U as input and return a T - which is a super-type of U; the other way around to declare this would be T super U - but this is not legal in java.

This should be an example of what I mean actually. Suppose a very simple class like:

static class Holder<T> {

    private final T t;

    public Holder(T t) {
        this.t = t;
    }

    public <U super T> U whenNull(U whenNull){
        return t == null ? whenNull : t;
    }
}

Method whenNull as it is defined would not compile, as U super T is not allowed in java.

Instead you could add another type parameter and invert the types:

static class Holder<U, T extends U> {

    private final T t;

    public Holder(T t) {
        this.t = t;
    }

    public U whenNull(U whenNull) {
        return t == null ? whenNull : t;
    }
}

And usage would be:

Holder<Number, Integer> n = new Holder<>(null);
Number num = n.whenNull(22D);

this allows to return a super type; but it looks very weird. We have added another type in the class declaration.

We could resort to:

static class Holder<T> {

    private final T t;

    public Holder(T t) {
        this.t = t;
    }

    public static <U, T extends U> U whenNull(U whenNull, Holder<T> holder) {
        return holder.t == null ? whenNull : holder.t;
    }
}

or even make this method static.

For an existing limitation, you could try to do:

Optional.ofNullable(<SomeSubTypeThatIsNull>)
        .orElse(<SomeSuperType>)


问:
Restrict authorization or reduce result in case specific parameter arent satisfy requirements
Describing University via software I faced an auth issue.

Previously I had only a Headmaster role, which can do and access anything.
But as for now, I need to integrate a Teacher role.

The Teacher role should have an option to access certain features, which could be easily restricted by Authorize attribute. But in some cases, I want to reduce the number of data allowed to access for this role, e.g. not all students of the universe, but the ones who study Teacher's Subject.

All of this is already described in EF, (e.g. teacher-subject, subject-students relationships). But now I struggle to refuse (return 403) request for subject or students which are not allowed to access by Teacher.

I thought about a Specification pattern usage for my Services, so the resulting data will be reduced with a Specification's filter, as it helps reduce the data amount, sometimes to no-data, but didn't help to fully refuse a request.

Could you kindly provide me a link or an architectural idea to satisfy expectations for both use-cases specified above?

```<code>// entity models
class Subject {
    ...
    public Teacher Teacher { get; set; }
    public List<Students> { get; set; }
    ...
}

class Teacher {
    ...
    public List<Subject> Subjects { get; set; }
    ...
}
class Student {
    ...
    public List<Subject> StudiedSubjects {get; set; }
    ...
}

// first use-case I want to solve
public ActionResult<List<Student>> GetStudent()
{
    // previously I just did
    return Ok(_studentsService.GetStudents());

    // but as for now in case of Teacher role accessed the method I want to
    // reduce the number of returned students
}

// second use-case I want to solve
public ActionResult<Subject> GetSubjectDetails(int subjectId)
{
    // previously I just did
    return Ok(_subjectService.GetSubject(subjectId);

    // but as for now in case of Teacher role I need to check whether its
    // allowed to get the subject and return Access denied in case its not
}

</code>```

答:
Your scenario is very practical which makes the question very interesting. But It would be nice for you to look at this documentation.

Use claims to give the teach access to the information they must be able to access. You can save a claim as .i.e. "TeacherName-TargetInforNameTheyCanAccess"; you can have as many claims as possible depending on how much information should be accessible by the teacher.

This goes the same for Students as well. You can create claims for Students that are under that Lecturers Class. Like say: "StudentName-LectureName" an you can then base your authentication by checking if the student is claimed to be under a specific lecturers class.

Body:
Describing University via software I faced an auth issue.

Previously I had only a Headmaster role, which can do and access anything.
But as for now, I need to integrate a Teacher role.

The Teacher role should have an option to access certain features, which could be easily restricted by Authorize attribute. But in some cases, I want to reduce the number of data allowed to access for this role, e.g. not all students of the universe, but the ones who study Teacher's Subject.

All of this is already described in EF, (e.g. teacher-subject, subject-students relationships). But now I struggle to refuse (return 403) request for subject or students which are not allowed to access by Teacher.

I thought about a Specification pattern usage for my Services, so the resulting data will be reduced with a Specification's filter, as it helps reduce the data amount, sometimes to no-data, but didn't help to fully refuse a request.

Could you kindly provide me a link or an architectural idea to satisfy expectations for both use-cases specified above?

// entity models
class Subject {
    ...
    public Teacher Teacher { get; set; }
    public List<Students> { get; set; }
    ...
}

class Teacher {
    ...
    public List<Subject> Subjects { get; set; }
    ...
}
class Student {
    ...
    public List<Subject> StudiedSubjects {get; set; }
    ...
}

// first use-case I want to solve
public ActionResult<List<Student>> GetStudent()
{
    // previously I just did
    return Ok(_studentsService.GetStudents());

    // but as for now in case of Teacher role accessed the method I want to
    // reduce the number of returned students
}

// second use-case I want to solve
public ActionResult<Subject> GetSubjectDetails(int subjectId)
{
    // previously I just did
    return Ok(_subjectService.GetSubject(subjectId);

    // but as for now in case of Teacher role I need to check whether its
    // allowed to get the subject and return Access denied in case its not
}


问:
FIDO - How does the FIDO server verify the integrity of inbound public key during registration phase/ceremony?
Trying to wrap my head around the FIDO protocol suit.

Premise

Authenticator has a master private key(also called attestation key)

During the registration ceremony, authenticator signs the challenge and a couple of other parameters along with the newly generated public key and sends it to the FIDO universal server via WebAuthN protocol. And the private key generated is stored in the authenticator locally.

Questions

How does the FIDO server verify the integrity of public key generated by authenticator (simply put how does the server validate the certificate chain back to root of trust)? This is assuming that there is scope for mitm attack between authenticator and web client.

Does the server have corresponding public key of attestation key/master private key built in (replicating a CA model)?

If so, do all the fido authenticators have same master key when they are created(be it software module or a hardware module)? If not how do manufacturers and FIDO servers keep up with huge number of physical authenticators and software modules being created and deployed?

答:
The authenticator is injected a private key (attestation key) before it is sold to user. The attestation certificate is trusted by FIDO server. That certificate will be used for verifying signature in attestation statement.
Let's talk about trusting a certificate. There are 2 kinds of trust: Trust and Chain of Trust.

Trust: FIDO server directly imports (stores) a known Authenticator Vendor certificate. Let's say I trust Yubico, I download Yubico key attestation certificate from Yubico site and import to my FIDO server. That certificate will be used for verifying registration from users using Yubico keys. No one can generate a valid attestation statement without attestation private. Don't worry about man-in-the-middle because the vendors may have applied a secure chip technology to protect the private key.

Chain of Trust: FIDO server obviously trusts FIDO Metadata Service (MDS) and just stores MDS certificates. MDS issues certificates for Authenticator Vendors. So, when authenticator creates attestation statement and sends it to FIDO server, Server will verify signature using attestation certificate in the attestation statement and then combine the attestation certificate with MDS certificates to do the validation.

Note that we are talking about Full Basic Attestation Model which is the most common so far. ECDAA will be different.

As explain in 1. above. Server MAY or MAY NOT have attestation public key.
Note that the attestation private keys in the authenticators are NOT distinct. Vendors produce security keys by batch. Each batch they inject the same attestation private, this is for user privacy. This is not a perfect solution. User privacy is solved perfectly by ECDAA which is not launched.

As explain by 1., 2.