问:
Mongodb-Query db using result from another query
I have multiples queries on the same collection:

1st Query:

```<code>db.getCollection('messagelogs').find({'intents.intent':'General_Positive_Feedback'},{'currentStep':1,'_id':0})
</code>```

1st Query result

```<code>{
"currentStep" : [
    "flowkuec8ta1o"
]
}
</code>```

I'm using the first query result 'flowkuec8ta1o' for 2nd query('currentStep' in query 1 result is used  as the value of key 'previousStep' in the below 2nd query)  :

2nd Query:

```<code>db.getCollection('messagelogs').find({'previousStep':'flow1pemwl7ws'},{'userMessage':1})
</code>```

2nd Query Result:

```<code>{
"_id" : ObjectId("5cec2dd29b806c4a00f91f18"),
"userMessage" : "ILikedIt#1"
 }
</code>```

How can I combine both the queries into one?

Please dont mark this question of this question. I tried that questions solution, which was not giving the desired result for me. Can anyone please help me with this?

Attaching sample document 1(Where 'currentStep' is fetched from):

```<code>{
"_id" : ObjectId("5cec2dc69b806c4a00f91f16"),
"currentStep" : [
    "flowkuec8ta1o"
],
"previousStep" : [
    "conditioncplwf7pw1",
    "condition00yokr6jv",
    "conditionzq9koi6i3"
],
"userMessage" : "Liked It :)",
"intents" : [
    {
        "_id" : ObjectId("5cec2dc69b806c4a00f91f17"),
        "intent" : "General_Positive_Feedback",
        "score" : "0.9774518966674806"
    }
]
}
</code>```

Attaching sample document 2 (Where 'currentStep' value fetched from query 1 is used as 'previousStep' in the second query)

```<code>{
"_id" : ObjectId("5cec2dd29b806c4a00f91f18"),
"currentStep" : [],
"previousStep" : [
    "flowkuec8ta1o"
],
"userMessage" : "ILikedIt#1",
    "intents" : [
    {
        "_id" : ObjectId("5cec2dd29b806c4a00f91f19"),
        "intent" : "Feedback",
        "score" : "1"
    }
]
}
</code>```

Sample output:

```<code>{
"_id" : ObjectId("5cec2dd29b806c4a00f91f18"),
"userMessage" : "ILikedIt#1"
}
</code>```

Adding sample documents as per @Fanparks request:

The below two documents matches the first query(to get the 'currentStep')

Document 1:

```<code>{
"currentStep": [
    "flowkuec8ta1o"
],
"previousStep": [
    "conditioncplwf7pw1",
    "condition00yokr6jv",
    "conditionzq9koi6i3"
],
"userMessage": "Liked It :)",
"intents": [{
    "_id": ObjectId("5cec2dc69b806c4a00f91f17"),
    "intent": "General_Positive_Feedback",
    "score": "0.9774518966674806"
}]
}
</code>```

Document 2:

```<code>{
"currentStep": [
    "flowkuec8ta1o"
],
"previousStep": [
    "conditioncplwf7pw1",
    "condition00yokr6jv",
    "conditionzq9koi6i3"
],
"userMessage": "Just Okay, Could Be better",
"intents": [{
    "_id": ObjectId("5cec2f1a9b806c4a00f91f41"),
    "intent": "General_Positive_Feedback",
    "score": "1"
}]
}
</code>```

The below documents matches the second query(Where the 'previousStep' matches the 'currentStep' fetched from the first query)

Document 1:

```<code>{
"currentStep": [],
"previousStep": [
    "flowkuec8ta1o"
],
"userMessage": "ILikedIt#1",
"intents": [{
    "_id": ObjectId("5cec2dd29b806c4a00f91f19"),
    "intent": "Feedback",
    "score": "1"
}]
}
</code>```

Document 2:

```<code>{
"currentStep" : [
    "flowkuec8ta1o"
]
}
</code>```0

Document 3:

```<code>{
"currentStep" : [
    "flowkuec8ta1o"
]
}
</code>```1

Document 4:

```<code>{
"currentStep" : [
    "flowkuec8ta1o"
]
}
</code>```2

Desired Output:

```<code>/* 1 */
{
"_id" : ObjectId("5cec2dd29b806c4a00f91f18"),
"userMessage" : "ILikedIt#1"
}

/* 2 */
{
"_id" : ObjectId("5cec2f2b9b806c4a00f91f42"),
"userMessage" : "JustOkayCouldBeBetter#1"
}

/* 3 */
{
"_id" : ObjectId("5ced84e2fdf046078c85d9ca"),
"userMessage" : "I'mGivingAPositiveFeedback"
}

/* 4 */
{
"_id" : ObjectId("5cede37dfdf046078c85d9df"),
"userMessage" : "I'm giving a positive feedback for the second time!"
}
</code>```

**Actual Output: **

```<code>/* 1 */
{
"_id" : ObjectId("5cec2dd29b806c4a00f91f18"),
"userMessage" : "ILikedIt#1"
}

/* 2 */
{
"_id" : ObjectId("5cec2f2b9b806c4a00f91f42"),
"userMessage" : "JustOkayCouldBeBetter#1"
}

/* 3 */
{
"_id" : ObjectId("5ced84e2fdf046078c85d9ca"),
"userMessage" : "I'mGivingAPositiveFeedback"
}

/* 4 */
{
"_id" : ObjectId("5cede37dfdf046078c85d9df"),
"userMessage" : "I'm giving a positive feedback for the second time!"
}

/* 5 */
{
"_id" : ObjectId("5cec2dd29b806c4a00f91f18"),
"userMessage" : "ILikedIt#1"
}

/* 6 */
{
"_id" : ObjectId("5cec2f2b9b806c4a00f91f42"),
"userMessage" : "JustOkayCouldBeBetter#1"
}

/* 7 */
{
"_id" : ObjectId("5ced84e2fdf046078c85d9ca"),
"userMessage" : "I'mGivingAPositiveFeedback"
}

/* 8 */
{
"_id" : ObjectId("5cede37dfdf046078c85d9df"),
"userMessage" : "I'm giving a positive feedback for the second time!"
}
</code>```

答:
You can use below aggregation

```<code>db.getCollection('messagelogs').aggregate([
  { "$match": { "intents.intent": "General_Positive_Feedback" }},
  { "$lookup": {
      "from": "messagelogs",
      "let": { "currentStep": "$currentStep" },
      "pipeline": [
        { "$match": { "$expr": { "$eq": ["$previousStep", "$$currentStep"] }}},
        { "$project": { "userMessage": 1 }}
      ],
      "as": "previousStep"
    }},
  { "$unwind": "$previousStep" },
  { "$replaceRoot": { "newRoot": "$previousStep" }},
  { "$group": {
    "_id": "$userMessage",
    "id": { "$first": "$_id" }
  }},
  { "$project": {
    "_id": "$id",
    "userMessage": "$_id"
  }}
])
</code>```

MongoPlayground

Body:
I have multiples queries on the same collection:

1st Query:

db.getCollection('messagelogs').find({'intents.intent':'General_Positive_Feedback'},{'currentStep':1,'_id':0})

1st Query result

{
"currentStep" : [
    "flowkuec8ta1o"
]
}

I'm using the first query result 'flowkuec8ta1o' for 2nd query('currentStep' in query 1 result is used  as the value of key 'previousStep' in the below 2nd query)  :

2nd Query:

db.getCollection('messagelogs').find({'previousStep':'flow1pemwl7ws'},{'userMessage':1})

2nd Query Result:

{
"_id" : ObjectId("5cec2dd29b806c4a00f91f18"),
"userMessage" : "ILikedIt#1"
 }

How can I combine both the queries into one?

Please dont mark this question of this question. I tried that questions solution, which was not giving the desired result for me. Can anyone please help me with this?

Attaching sample document 1(Where 'currentStep' is fetched from):

{
"_id" : ObjectId("5cec2dc69b806c4a00f91f16"),
"currentStep" : [
    "flowkuec8ta1o"
],
"previousStep" : [
    "conditioncplwf7pw1",
    "condition00yokr6jv",
    "conditionzq9koi6i3"
],
"userMessage" : "Liked It :)",
"intents" : [
    {
        "_id" : ObjectId("5cec2dc69b806c4a00f91f17"),
        "intent" : "General_Positive_Feedback",
        "score" : "0.9774518966674806"
    }
]
}

Attaching sample document 2 (Where 'currentStep' value fetched from query 1 is used as 'previousStep' in the second query)

{
"_id" : ObjectId("5cec2dd29b806c4a00f91f18"),
"currentStep" : [],
"previousStep" : [
    "flowkuec8ta1o"
],
"userMessage" : "ILikedIt#1",
    "intents" : [
    {
        "_id" : ObjectId("5cec2dd29b806c4a00f91f19"),
        "intent" : "Feedback",
        "score" : "1"
    }
]
}

Sample output:

{
"_id" : ObjectId("5cec2dd29b806c4a00f91f18"),
"userMessage" : "ILikedIt#1"
}

Adding sample documents as per @Fanparks request:

The below two documents matches the first query(to get the 'currentStep')

Document 1:

{
"currentStep": [
    "flowkuec8ta1o"
],
"previousStep": [
    "conditioncplwf7pw1",
    "condition00yokr6jv",
    "conditionzq9koi6i3"
],
"userMessage": "Liked It :)",
"intents": [{
    "_id": ObjectId("5cec2dc69b806c4a00f91f17"),
    "intent": "General_Positive_Feedback",
    "score": "0.9774518966674806"
}]
}

Document 2:

{
"currentStep": [
    "flowkuec8ta1o"
],
"previousStep": [
    "conditioncplwf7pw1",
    "condition00yokr6jv",
    "conditionzq9koi6i3"
],
"userMessage": "Just Okay, Could Be better",
"intents": [{
    "_id": ObjectId("5cec2f1a9b806c4a00f91f41"),
    "intent": "General_Positive_Feedback",
    "score": "1"
}]
}

The below documents matches the second query(Where the 'previousStep' matches the 'currentStep' fetched from the first query)

Document 1:

{
"currentStep": [],
"previousStep": [
    "flowkuec8ta1o"
],
"userMessage": "ILikedIt#1",
"intents": [{
    "_id": ObjectId("5cec2dd29b806c4a00f91f19"),
    "intent": "Feedback",
    "score": "1"
}]
}

Document 2:

{
"currentStep": [],
"previousStep": [
    "flowkuec8ta1o"
],
"userMessage": "JustOkayCouldBeBetter#1",
"intents": [{
    "_id": ObjectId("5cec2f2b9b806c4a00f91f43"),
    "intent": "Feedback",
    "score": "1"
}]
}

Document 3:

{
"currentStep": [],
"previousStep": [
    "flowkuec8ta1o"
],
"userMessage": "I'mGivingAPositiveFeedback",
"intents": [{
    "_id": ObjectId("5ced84e2fdf046078c85d9cb"),
    "intent": "Feedback",
    "score": "1"
}]
}

Document 4:

{
"currentStep": [],
"previousStep": [
    "flowkuec8ta1o"
],
"userMessage": "I'm giving a positive feedback for the second time!",
"intents": [{
    "_id": ObjectId("5cede37dfdf046078c85d9e0"),
    "intent": "Feedback",
    "score": "1"
}]
}

Desired Output:

/* 1 */
{
"_id" : ObjectId("5cec2dd29b806c4a00f91f18"),
"userMessage" : "ILikedIt#1"
}

/* 2 */
{
"_id" : ObjectId("5cec2f2b9b806c4a00f91f42"),
"userMessage" : "JustOkayCouldBeBetter#1"
}

/* 3 */
{
"_id" : ObjectId("5ced84e2fdf046078c85d9ca"),
"userMessage" : "I'mGivingAPositiveFeedback"
}

/* 4 */
{
"_id" : ObjectId("5cede37dfdf046078c85d9df"),
"userMessage" : "I'm giving a positive feedback for the second time!"
}

**Actual Output: **

/* 1 */
{
"_id" : ObjectId("5cec2dd29b806c4a00f91f18"),
"userMessage" : "ILikedIt#1"
}

/* 2 */
{
"_id" : ObjectId("5cec2f2b9b806c4a00f91f42"),
"userMessage" : "JustOkayCouldBeBetter#1"
}

/* 3 */
{
"_id" : ObjectId("5ced84e2fdf046078c85d9ca"),
"userMessage" : "I'mGivingAPositiveFeedback"
}

/* 4 */
{
"_id" : ObjectId("5cede37dfdf046078c85d9df"),
"userMessage" : "I'm giving a positive feedback for the second time!"
}

/* 5 */
{
"_id" : ObjectId("5cec2dd29b806c4a00f91f18"),
"userMessage" : "ILikedIt#1"
}

/* 6 */
{
"_id" : ObjectId("5cec2f2b9b806c4a00f91f42"),
"userMessage" : "JustOkayCouldBeBetter#1"
}

/* 7 */
{
"_id" : ObjectId("5ced84e2fdf046078c85d9ca"),
"userMessage" : "I'mGivingAPositiveFeedback"
}

/* 8 */
{
"_id" : ObjectId("5cede37dfdf046078c85d9df"),
"userMessage" : "I'm giving a positive feedback for the second time!"
}

Body:
You can use below aggregation

db.getCollection('messagelogs').aggregate([
  { "$match": { "intents.intent": "General_Positive_Feedback" }},
  { "$lookup": {
      "from": "messagelogs",
      "let": { "currentStep": "$currentStep" },
      "pipeline": [
        { "$match": { "$expr": { "$eq": ["$previousStep", "$$currentStep"] }}},
        { "$project": { "userMessage": 1 }}
      ],
      "as": "previousStep"
    }},
  { "$unwind": "$previousStep" },
  { "$replaceRoot": { "newRoot": "$previousStep" }},
  { "$group": {
    "_id": "$userMessage",
    "id": { "$first": "$_id" }
  }},
  { "$project": {
    "_id": "$id",
    "userMessage": "$_id"
  }}
])

MongoPlayground


来源: stackexchange

问:
How to detect a new component is loaded in app component or in common place?
I am using angular with ionic framework. And to navigate from one component to other I am using ionic nav controller.
All I want is whichever component is loaded, it gives the name of that component at a common place or in app component</p>

答:
You can use a global service with rxjs subject to track any component activity like created, destroy or others

TrackerService

```<code>@Injectable({providedIn:"root"}) //  root
export class TrackerService {

  private _sub = new Subject();
  constructor() { }

  public post(data:any) { //  send a data to subscriber
    this._sub.next(data)
  }

  public subscribe(fx:any) : Subscription {  //  tracker activity
    return this._sub.subscribe(fx);
  }

}
</code>```

in any component just inject the tracker server and post a data at any case init , destroy  or maybe at some cases like login ...

as example

```<code>  constructor(private _tracker:TrackerService) { }

  ngOnInit() {
    this._tracker.post({message:'FirstComponent is active'}); // send
  }

  ngOnDestroy() {
    this._tracker.post({message:'FirstComponent is deactive'});

  }
</code>```

and I have subscribe to the tracker service at app component like this

```<code>  ngOnInit() {

    this._tracker.subscribe(result => console.log(result)); // arrived

  }
</code>```

tracker subscribe method return a subscription object so you can
  unsubscribe later

stackblitz demo

ContentLicense: CC BY-SA 4.0

Body:
You can use a global service with rxjs subject to track any component activity like created, destroy or others

TrackerService

@Injectable({providedIn:"root"}) //  root
export class TrackerService {

  private _sub = new Subject();
  constructor() { }

  public post(data:any) { //  send a data to subscriber
    this._sub.next(data)
  }

  public subscribe(fx:any) : Subscription {  //  tracker activity
    return this._sub.subscribe(fx);
  }

}

in any component just inject the tracker server and post a data at any case init , destroy  or maybe at some cases like login ...

as example

  constructor(private _tracker:TrackerService) { }

  ngOnInit() {
    this._tracker.post({message:'FirstComponent is active'}); // send
  }

  ngOnDestroy() {
    this._tracker.post({message:'FirstComponent is deactive'});

  }

and I have subscribe to the tracker service at app component like this

  ngOnInit() {

    this._tracker.subscribe(result => console.log(result)); // arrived

  }

tracker subscribe method return a subscription object so you can
  unsubscribe later

stackblitz demo


问:
xpath - find multiple sequencial occurences of an element
I have an xhtml node that I need to clean, with the following innerText:

Image text goes here

I can't figure out by myself the xpath expressions that returns / finds multiple occurrences of the
 element. do I need to do recursion in the nodes and check against the last match ?

UPDATE: I'm using HtmlAgilityPack to navigate through the doc.

Thanks in advance!

Regards,
byte_slave

答:
XPath is not going to work because this is NOT XHTML. All the br tags are unclosed. Heck, even the img tag itself is imcomplete...

You need to clean this with plain text handling (regular expressions, likely) or HTML sanitizers. Look at

xmllint

and

HTML tidy

ContentLicense: CC BY-SA 3.0


问:
Oracle Forms Comment Line Shortcut
Is there any shortcut for to make all chosen lines comment lines in Oracle Forms 10g?

I've been searching some, but couldn't find it.

答: Shortcut? Such as manually typing -- at the beginning of the line? There's nothing shorter than that (if you meant something like Ctrl + B or similar), as far as I can tell.

Title: Oracle Forms Comment Line Shortcut


问:
Karate - Overview reporting without parallel runner
I have tests which can't be run parallel but need to be run sequentially , So I have individual runners with me .

But I am not getting an overview report for the same in the surefire-reports , I am only getting step by step report

答:
That's not really clear. Do you want to run every test sequencially? If yes :

```<code>`Results results = Runner.parallel(getClass(), 1, karateOutputPath);`
</code>```

If you want to run features in parallel but for need the scenarios inside a feature to run sequencially :
https://github.com/intuit/karate#parallelfalse

And if you want some features to run sequencially, and some to run in parallel, while still having a single report, you'll have to launch two runners, one in parallel, one with a single thread, with a specified tag. And then compile both reports into one. Example with Cucumber report :

generateReport(resultsParallel.getReportDir(), resultsNotParallel.getReportDir());

Body:
That's not really clear. Do you want to run every test sequencially? If yes :

`Results results = Runner.parallel(getClass(), 1, karateOutputPath);`

If you want to run features in parallel but for need the scenarios inside a feature to run sequencially :
https://github.com/intuit/karate#parallelfalse

And if you want some features to run sequencially, and some to run in parallel, while still having a single report, you'll have to launch two runners, one in parallel, one with a single thread, with a specified tag. And then compile both reports into one. Example with Cucumber report :

generateReport(resultsParallel.getReportDir(), resultsNotParallel.getReportDir());


问:
How to Get in between button tag text value in IFormCollection?
I have a search form on view that displays check boxes as a list which may be selected multi, on each item check, value comes in between button tags.

In Controller Action IFormCollection provides various key value but not that button which tags contain results, it always returns null

```<code><button type="button" data-toggle="dropdown" name="State" data-placeholder="---" class="dropdown-toggle js-select-checkboxes-btn">---</button>
                                        <div class="dropdown-menu js-dropdown-menu js-select-checkboxes">
                                            <ul>
                                                <li>
                                                    <input id="checkbox_type_1" type="checkbox" name="checkbox_type_1" class="in-checkbox">
                                                    <label for="checkbox_type_1" data-toggle="tooltip" data-placement="left" title="Tooltip on top" class="in-label">Punjab</label>
                                                </li>
                                                <li>
                                                    <input id="checkbox_type_2" type="checkbox" name="checkbox_type_2" class="in-checkbox">
                                                    <label for="checkbox_type_2" data-toggle="tooltip" data-placement="top" title="Tooltip on top" class="in-label">Sindh</label>
                                                </li>
                                                <li>
                                                    <input id="checkbox_type_3" type="checkbox" name="checkbox_type_3" class="in-checkbox">
                                                    <label for="checkbox_type_3" data-toggle="tooltip" data-placement="bottom" title="Tooltip on top" class="in-label">Balochistan</label>
                                                </li>
                                                <li>
                                                    <input id="checkbox_type_4" type="checkbox" name="checkbox_type_4" class="in-checkbox">
                                                    <label for="checkbox_type_4" data-toggle="tooltip" data-placement="bottom" title="Tooltip on top" class="in-label">Khaybar Pakhtonkhwa</label>
                                                </li>
                                                <li>
                                                    <input id="checkbox_type_5" type="checkbox" name="checkbox_type_5" class="in-checkbox">
                                                    <label for="checkbox_type_5" data-toggle="tooltip" data-placement="bottom" title="Tooltip on top" class="in-label">Azad Kashmir</label>
                                                </li>
                                                <li>
                                                    <input id="checkbox_type_6" type="checkbox" name="checkbox_type_6" class="in-checkbox">
                                                    <label for="checkbox_type_6" data-toggle="tooltip" data-placement="bottom" title="Tooltip on top" class="in-label">Gilgit Baltistan</label>
                                                </li>
                                            </ul>
                                            <!-- end of block .dropdown-menu-->
                                        </div>
</code>```

In Page Source:

```<code><button type="button" data-toggle="dropdown" data-placeholder="---" class="dropdown-toggle js-select-checkboxes-btn" aria-expanded="true">Punjab, Sindh, Balochistan</button>
</code>```

In Controller Action Result:

```<code>public IActionResult SearchPerson(IFormCollection formCollection)
    {
        string txtState = formCollection["State"]; << Null}
</code>```

I Expect the output as string i.e. in between tags

答:
Solution Found with a little Trick i.e.

Step 1. Created a hidden type input

```<code><input type="hidden" id="State" name="State" placeholder=""   class="form-control">
</code>```

Step 2. Create a javascript/jquery function to set hidden input value equals button tags inner html

```<code>function onsubmitclick() {
    var x = document.getElementById('btnState').innerHTML;
    alert(x);
    $('#State').val(x);
};
</code>```

Step 3. Call function at submit button i.e. will fire before moving to controller action.

```<code><button type="submit" onclick="onsubmitclick()" asp-controller="Home" asp-action="SearchPerson" class="form__submit" >Search</button>
</code>```

Step 4. Accessed hidden input value at controller from IFormCollection.

```<code>public IActionResult SearchPerson(IFormCollection formCollection){string txtState = formCollection["State"];}
</code>```

Done!

Body:
I have a search form on view that displays check boxes as a list which may be selected multi, on each item check, value comes in between button tags.

In Controller Action IFormCollection provides various key value but not that button which tags contain results, it always returns null

<button type="button" data-toggle="dropdown" name="State" data-placeholder="---" class="dropdown-toggle js-select-checkboxes-btn">---</button>

                                                    <input id="checkbox_type_1" type="checkbox" name="checkbox_type_1" class="in-checkbox">
                                                    Punjab

                                                    <input id="checkbox_type_2" type="checkbox" name="checkbox_type_2" class="in-checkbox">
                                                    Sindh

                                                    <input id="checkbox_type_3" type="checkbox" name="checkbox_type_3" class="in-checkbox">
                                                    Balochistan

                                                    <input id="checkbox_type_4" type="checkbox" name="checkbox_type_4" class="in-checkbox">
                                                    Khaybar Pakhtonkhwa

                                                    <input id="checkbox_type_5" type="checkbox" name="checkbox_type_5" class="in-checkbox">
                                                    Azad Kashmir

                                                    <input id="checkbox_type_6" type="checkbox" name="checkbox_type_6" class="in-checkbox">
                                                    Gilgit Baltistan

In Page Source:

<button type="button" data-toggle="dropdown" data-placeholder="---" class="dropdown-toggle js-select-checkboxes-btn" aria-expanded="true">Punjab, Sindh, Balochistan</button>

In Controller Action Result:

public IActionResult SearchPerson(IFormCollection formCollection)
    {
        string txtState = formCollection["State"]; << Null}

I Expect the output as string i.e. in between tags

Body:
Solution Found with a little Trick i.e.

Step 1. Created a hidden type input

<input type="hidden" id="State" name="State" placeholder=""   class="form-control">

Step 2. Create a javascript/jquery function to set hidden input value equals button tags inner html

function onsubmitclick() {
    var x = document.getElementById('btnState').innerHTML;
    alert(x);
    $('#State').val(x);
};

Step 3. Call function at submit button i.e. will fire before moving to controller action.

<button type="submit" onclick="onsubmitclick()" asp-controller="Home" asp-action="SearchPerson" class="form__submit" >Search</button>

Step 4. Accessed hidden input value at controller from IFormCollection.

public IActionResult SearchPerson(IFormCollection formCollection){string txtState = formCollection["State"];}

Done!


问:
Spring Data MongoDB Aggregate with many fields in _id
I would like to make an aggregate with Spring Data MongoDB and I don't know how to make this group stage :

```<code>$group: {
                    _id: {
                        field1: "$field1",
                        field2: "2017-06-21",
                        field3: "$field3"
                    },

                    ...
                }
</code>```

I don't know how to put the constant date into the second field of the _id

For the moment i do this :

```<code>groupOperation = group("field1","field3")
</code>```

But i'm not sure that it make a group stage on the value of fields and i don't no how put a new field into _id.

I don't find good doc about the operation of different stage of an aggregate in Spring data MongoDB

If someone has an idea I'm interested

Thank you in advance

答:
```<code>Fields fields = Fields.fields("field1", "field2", "field3");
GroupOperation groupOp = Aggregation.group(fields);
</code>```

This will make group block

```<code>$group: {
        _id: {
            field1: "$field1",
            field2: "$field2",
            field3: "$field3"
        }
</code>```

Body:
I would like to make an aggregate with Spring Data MongoDB and I don't know how to make this group stage :

$group: {
                    _id: {
                        field1: "$field1",
                        field2: "2017-06-21",
                        field3: "$field3"
                    },

                    ...
                }

I don't know how to put the constant date into the second field of the _id

For the moment i do this :

groupOperation = group("field1","field3")

But i'm not sure that it make a group stage on the value of fields and i don't no how put a new field into _id.

I don't find good doc about the operation of different stage of an aggregate in Spring data MongoDB

If someone has an idea I'm interested

Thank you in advance

Body:
Fields fields = Fields.fields("field1", "field2", "field3");
GroupOperation groupOp = Aggregation.group(fields);

This will make group block

$group: {
        _id: {
            field1: "$field1",
            field2: "$field2",
            field3: "$field3"
        }


问:
How to update a table using stored procedures in SQL Server
I have created a table in SQL Server called "Employee", and now I want to update the table using a stored procedure.

The table has emp_name, emp_code and status columns. Assume the table has three records: initially, in the stored procedure I want to fetch the last two records using a select statement and I have to the fetched records' status to  'Y'.

I have written a stored procedure, but it's not affecting the original table. Kindly suggest the query for the stored procedure.

Here is the query I have made:

```<code>create  procedure updtdemployee As
  select e.Emp_name ,e.Circle
  from employee e
  where e.Emp_Code ='2501' or e.Emp_Code='2502'

  begin
    update employee set status='Y' where Emp_name = employee.Emp_name
  end
</code>```

答:
```<code>-- =============================================
-- Author:      XYZ
-- Create date: xx-xx-xxxx
-- Description: Procedure for Updating  Emp Detail
-- =============================================

CREATE PROCEDURE [dbo].[SP_EmpLoyee_Update]
(
@EmpCode bigint=null,
@EmpName nvarchar(250)=null,
@MNumber nvarchar(250)=null,
@Status int=null,
@LoginUserId nvarchar(50)=null,
@Msg nvarchar(MAX)=null OUTPUT
)
AS
BEGIN TRY

UPDATE tbl_Employees
SET
EmpName=@EmpName,
MNumber=@MNumber,
Status=@Status,
ModificationDate=GETDATE()

WHERE EmpCode=@EmpCode

    SET @Msg='Employee   Updated Successfully.'

END TRY
BEGIN CATCH

    SET @Msg=ERROR_MESSAGE()

END CATCH

GO
</code>```

Body:
I have created a table in SQL Server called "Employee", and now I want to update the table using a stored procedure.

The table has emp_name, emp_code and status columns. Assume the table has three records: initially, in the stored procedure I want to fetch the last two records using a select statement and I have to the fetched records' status to  'Y'.

I have written a stored procedure, but it's not affecting the original table. Kindly suggest the query for the stored procedure.

Here is the query I have made:

create  procedure updtdemployee As
  select e.Emp_name ,e.Circle
  from employee e
  where e.Emp_Code ='2501' or e.Emp_Code='2502'

  begin
    update employee set status='Y' where Emp_name = employee.Emp_name
  end


问:
unsupported match type for string: CONTAINS_ANY
I want to validate value match of all items in string array

response.data[0].attributes.status where contains any ["active","deleted" ,"deleting","processing"]

答:
Please read the karate documentation about the contains any matcher.

contains any expect that right and left side are of type json array or json object.

A simple example with json arrays:

```<code> * match  ['active', 'deleted'] contains any ['status', 'active']
</code>```

Same for json objects:

```<code> * match  {'foo':'bar'} contains any {'foo':'bar', 'mr':'pink'}
</code>```

Your question:

You want to match that your status is one of  ["active","deleted" ,"deleting","processing"]. Or in other words, ["active","deleted" ,"deleting","processing"] contains status.

Karate speak:

```<code> * match ["active","deleted" ,"deleting","processing"] contains response.data[0].attributes.status
</code>```

Body:
Please read the karate documentation about the contains any matcher.

contains any expect that right and left side are of type json array or json object.

A simple example with json arrays:

 * match  ['active', 'deleted'] contains any ['status', 'active']

Same for json objects:

 * match  {'foo':'bar'} contains any {'foo':'bar', 'mr':'pink'}

Your question:

You want to match that your status is one of  ["active","deleted" ,"deleting","processing"]. Or in other words, ["active","deleted" ,"deleting","processing"] contains status.

Karate speak:

 * match ["active","deleted" ,"deleting","processing"] contains response.data[0].attributes.status


问:
Memset In C Using Sizeof Operator :
Here is a struct :

```<code>typedef struct tag_device_sys
{
    char device[STRING_SIZE];
    int id;
    char category;
} device_sys;
</code>```

For memset, which one should be used from below ?

```<code>memset(dev_sys, 0, (size_t)NUM_DEVICES * sizeof(device_sys));
</code>```

or

```<code>memset(dev_sys, 0, (size_t)NUM_DEVICES * sizeof(dev_sys));
</code>```

What are the differences ?

答:
```<code>memset(dev_sys, 0, (size_t)NUM_DEVICES * sizeof(*dev_sys));
</code>```

Always works as the way you've written it suggests dev_sys is either a pointer or an array. sizeof(*dev_sys) gives us the sizeof the first element.

In any case, I would write is as either

```<code>device_sys dev_sys[NUM_DEVICES];

memset(dev_sys, 0, (size_t) NUM_DEVICES * sizeof(*dev_sys));
</code>```

or

```<code>device_sys *dev_sys = (device_sys *) calloc(NUM_DEVICES, sizeof(*dev_sys));
</code>```

depending on if you want dev_sys on the stack or on the heap

Title: Memset In C Using Sizeof Operator :

Body:
Here is a struct :

typedef struct tag_device_sys
{
    char device[STRING_SIZE];
    int id;
    char category;
} device_sys;

For memset, which one should be used from below ?

memset(dev_sys, 0, (size_t)NUM_DEVICES * sizeof(device_sys));

or

memset(dev_sys, 0, (size_t)NUM_DEVICES * sizeof(dev_sys));

What are the differences ?

Body:
memset(dev_sys, 0, (size_t)NUM_DEVICES * sizeof(*dev_sys));

Always works as the way you've written it suggests dev_sys is either a pointer or an array. sizeof(*dev_sys) gives us the sizeof the first element.

In any case, I would write is as either

device_sys dev_sys[NUM_DEVICES];

memset(dev_sys, 0, (size_t) NUM_DEVICES * sizeof(*dev_sys));

or

device_sys *dev_sys = (device_sys *) calloc(NUM_DEVICES, sizeof(*dev_sys));

depending on if you want dev_sys on the stack or on the heap


问:
Golang Postgres repeatable read isolation level is not working
My understanding of the REPEATABLE READ transaction isolation level is that once it is set, the data read through in the transaction will not change. I have used the following code to verify this:

```<code>ctx = context.Background()
tx, _ := db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable})
time.Sleep(5 * time.Second)
// do query on tx
</code>```

While the process is sleeping,  I have inserted another record through the console. But the newly inserted record has appeared in the results. Why is that so? I don't want to read the records which are inserted after the transaction has begun. I also tried:

```<code>tx, _ := db.Begin()
_, err = tx.Exec(`set transaction isolation level repeatable read;`)
</code>```

But still the results are the same.

答:
The snapshot of a REPEATABLE READ or SERIALIZABLE transaction is not taken at the time when the transaction is started, but when the first SQL statement runs inside the transaction.

First, this is an optimization for the case that the transaction does not run any statement at all. Second, it is the only way to allow setting the transaction isolation level after the start of the transaction, but before any SQL statement has been run with

```<code>SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;
</code>```

Body:
My understanding of the REPEATABLE READ transaction isolation level is that once it is set, the data read through in the transaction will not change. I have used the following code to verify this:

ctx = context.Background()
tx, _ := db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable})
time.Sleep(5 * time.Second)
// do query on tx

While the process is sleeping,  I have inserted another record through the console. But the newly inserted record has appeared in the results. Why is that so? I don't want to read the records which are inserted after the transaction has begun. I also tried:

tx, _ := db.Begin()
_, err = tx.Exec(`set transaction isolation level repeatable read;`)

But still the results are the same.

Body:
The snapshot of a REPEATABLE READ or SERIALIZABLE transaction is not taken at the time when the transaction is started, but when the first SQL statement runs inside the transaction.

First, this is an optimization for the case that the transaction does not run any statement at all. Second, it is the only way to allow setting the transaction isolation level after the start of the transaction, but before any SQL statement has been run with

SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;


问:
How to set onClickListener for items in a ListView (items of listview are generated dynamically by retreiving data from firebase)
Hi Iam trying to make a chatApp.Iam successful with initial steps like user authentication,registration.After a successfull login user gets a screen as shown in this image:

Now the list of users here are generated by following code:

```<code>ListView listView;
View view;
ArrayList<String> usernames = new ArrayList<>();
String name;
FirebaseDatabase db = FirebaseDatabase.getInstance();
DatabaseReference root = db.getReference();
DatabaseReference userRef = root.child("users");

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
   Bundle savedInstanceState) {
   view = inflater.inflate(R.layout.fragment_users,container,false);
   listView =(ListView) view.findViewById(R.id.listView);
   final ArrayAdapter <String> arrayAdapter = new ArrayAdapter<String>
     (getContext(),android.R.layout.simple_list_item_1,usernames);
   listView.setAdapter(arrayAdapter);

   userRef.addChildEventListener(new ChildEventListener() {
     @Override
     public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
       String value = dataSnapshot.getValue().toString();
       try
       {
         JSONObject object = new JSONObject(value);
         name = object.getString("username");
       }
       catch(JSONException e)
       {
         e.printStackTrace();
       }

       usernames.add(name);
       arrayAdapter.notifyDataSetChanged();
     }

     @Override
     public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {}

     @Override
     public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {}

     @Override
     public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {}

     @Override
     public void onCancelled(@NonNull DatabaseError databaseError) {}
  });

  return view;
}
</code>```

Now whenever user clicks on particular name I've to take him to a messageActivity(more precisely another activity). Please tell me how I can add onClickListeners or any other possible method to do this?

答:
After

```<code>listView.setAdapter(arrayAdapter);
</code>```

create your listener like this:

```<code>listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
   @Override
   public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
        // Do what you want here
   }
});
</code>```

Body:
Hi Iam trying to make a chatApp.Iam successful with initial steps like user authentication,registration.After a successfull login user gets a screen as shown in this image:

Now the list of users here are generated by following code:

ListView listView;
View view;
ArrayList<String> usernames = new ArrayList<>();
String name;
FirebaseDatabase db = FirebaseDatabase.getInstance();
DatabaseReference root = db.getReference();
DatabaseReference userRef = root.child("users");

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
   Bundle savedInstanceState) {
   view = inflater.inflate(R.layout.fragment_users,container,false);
   listView =(ListView) view.findViewById(R.id.listView);
   final ArrayAdapter <String> arrayAdapter = new ArrayAdapter<String>
     (getContext(),android.R.layout.simple_list_item_1,usernames);
   listView.setAdapter(arrayAdapter);

   userRef.addChildEventListener(new ChildEventListener() {
     @Override
     public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
       String value = dataSnapshot.getValue().toString();
       try
       {
         JSONObject object = new JSONObject(value);
         name = object.getString("username");
       }
       catch(JSONException e)
       {
         e.printStackTrace();
       }

       usernames.add(name);
       arrayAdapter.notifyDataSetChanged();
     }

     @Override
     public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {}

     @Override
     public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {}

     @Override
     public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {}

     @Override
     public void onCancelled(@NonNull DatabaseError databaseError) {}
  });

  return view;
}

Now whenever user clicks on particular name I've to take him to a messageActivity(more precisely another activity). Please tell me how I can add onClickListeners or any other possible method to do this?

Body:
After

listView.setAdapter(arrayAdapter);

create your listener like this:

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
   @Override
   public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
        // Do what you want here
   }
});


问:
Cannot connect frontend app{Angular} to Backend{SpringBoot} in kubernetes
I am trying to containerize my angular+java app in Kubernetes cluster. I have a frontend deployment and a backend deployment in my k8 cluster. My database is in AWS{RDS}. But i am confused that what API-URL should i give in my Frontend code so that it can get connected to my backend app in k8 cluster.
For e.g :-
In local system i use something like {localhost:8080/api/customers} in my Frontend code but what should i change it to at the time of deploying in Kubernetes cluster.

I have a Kubernetes cluster setup with 1 master and 2 slave nodes, I created a deployment of my backend app and exposed it through Cluster Ip, and than i gave this cluster ip and port in my frontend application.
After that i pushed the image to docker hub and than created a k8 deployment for it, but still its not working.

My main ask is what URL and Port should i mention in my Frontend application target URL so that it can find hit my java APIs.

答: Exposing my back-end service to a Load Balancer, and than using that Load Balancer endpoint in my Front-end application worked for me.</p>


问:
How do i use password in python file?
I have written the following code to automate some of my work. But I need to use a password when logging into the application.

This will be a py file to run in cron on server. Therefore, I can not write the password clearly.

What should I do for the password? Can you give advice?

```<code>from splinter import Browser
import smtplib
import os
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import time

with Browser('chrome') as browser:
    # Visit URL
    url = "$some_url"
    browser.visit(url)
    if browser.is_text_present("All rights reserved."):
    # fill the user pass area on startpage
        browser.fill('usernameField', 'XXUSERNAME')
        browser.fill('passwordField', 'XXpassword')
    # find the submit button on the page and click it
        button = browser.find_by_id('SubmitButton')
        button.click()
    else:
            browser.quit()
            msg_text="""<p style="color:red;"><b> ERR1 </b></p>"""
#            print("Errtext")
</code>```

答:
i found this. simple but it works for my case.</p>

```<code>import keyring
service_id = 'some_app_name'
keyring.set_password(service_id, 'user', 'welcome')
password = keyring.get_password(service_id, 'user') # retrieve password
print(password)

import base64
pass1=base64.b64encode(b"welcome")
repr = base64.b64decode(b'd2VsY29tZQ==')
secret = repr.decode('utf-8')
print(secret)
</code>```

Title: How do i use password in python file?

Body:
I have written the following code to automate some of my work. But I need to use a password when logging into the application.

This will be a py file to run in cron on server. Therefore, I can not write the password clearly.

What should I do for the password? Can you give advice?

from splinter import Browser
import smtplib
import os
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import time

with Browser('chrome') as browser:
    # Visit URL
    url = "$some_url"
    browser.visit(url)
    if browser.is_text_present("All rights reserved."):
    # fill the user pass area on startpage
        browser.fill('usernameField', 'XXUSERNAME')
        browser.fill('passwordField', 'XXpassword')
    # find the submit button on the page and click it
        button = browser.find_by_id('SubmitButton')
        button.click()
    else:
            browser.quit()
            msg_text="""
 ERR1
"""
#            print("Errtext")

Body:
i found this. simple but it works for my case.

import keyring
service_id = 'some_app_name'
keyring.set_password(service_id, 'user', 'welcome')
password = keyring.get_password(service_id, 'user') # retrieve password
print(password)

import base64
pass1=base64.b64encode(b"welcome")
repr = base64.b64decode(b'd2VsY29tZQ==')
secret = repr.decode('utf-8')
print(secret)


问:
Unexpected width in shopify draggable element
I made a simple draggable list, using the shopify draggable plugin

```<code>  <ul id="myList">
    <li>Item</li>
    <li>Item</li>
    <li>Item</li>
    <li>Item</li>
    <li>Item</li>
    <li>Item</li>
    <li>Item</li>
    <li>Item</li>
    <li>Item</li>
  </ul>
</code>```

```<code>ul {
  width: 50%;
  border: 1px solid black;
  list-style: none;
  margin: 0;
  padding: 0;
}

li {
  margin: 5px;
  background: salmon;
  width: calc(100% - 10px);
  cursor: move;
}
</code>```

For some reason, when dragging, the dragged item's width gets much greater than the original item's. I suspect it's because I set the width in percentages and that it gets taken out of the parent container, so the percentage reference changes. I made a jsfiddle demo:

https://jsfiddle.net/x3jmkysq/1/

I would like it to work more like this example:
https://shopify.github.io/draggable/examples/simple-list.html
but I don't know how exactly they achieved it.

答:
Anyway, I found the solution here:
https://github.com/Shopify/draggable/issues/147

Basically there is a property to calculate the dimensions of the dragged element from the original one called constrainDimensions.

Body:
I made a simple draggable list, using the shopify draggable plugin

Item

Item

Item

Item

Item

Item

Item

Item

Item

ul {
  width: 50%;
  border: 1px solid black;
  list-style: none;
  margin: 0;
  padding: 0;
}

li {
  margin: 5px;
  background: salmon;
  width: calc(100% - 10px);
  cursor: move;
}

For some reason, when dragging, the dragged item's width gets much greater than the original item's. I suspect it's because I set the width in percentages and that it gets taken out of the parent container, so the percentage reference changes. I made a jsfiddle demo:

https://jsfiddle.net/x3jmkysq/1/

I would like it to work more like this example:
https://shopify.github.io/draggable/examples/simple-list.html
but I don't know how exactly they achieved it.


问:
Overriding bind method (Swift) - Err: Value of type 'Any' has no member 'addObserver'
I'm pretty new to Swift and "Apple" programming so excuse me if my question is silly.

I'm trying to sub-class NSPopupButton in order to add an option for binding the menu items' image property.

I want to override the "bind" function:

```<code>override func bind(_ binding: NSBindingName, to observable: Any, withKeyPath keyPath: String, options: [NSBindingOption : Any]? = nil)
</code>```

And to observe the "observable" parameter so this is the code I have written till now:

```<code>class WDPopupButton: NSPopUpButton
{
    static let ImageBindingContext: UnsafeMutableRawPointer? = UnsafeMutableRawPointer(mutating: "imageContext")

    override func bind(_ binding: NSBindingName, to observable: Any, withKeyPath keyPath: String, options: [NSBindingOption : Any]? = nil)
    {
        if(binding == NSBindingName.image)
        {
            guard let observableObject = observable as AnyObject? else
            {
                return
            }

            observable.addObserver(self, forKeyPath: keyPath, options: nil, context: WDPopupButton.ImageBindingContext)

            ...
        }
    }
}
</code>```

But I get the following error:

```<code>Value of type 'Any' has no member 'addObserver'
</code>```

My question is, what do I need to do in order to call addObserver on the observable parameter?

As you can see, I did tried to cast observable to AnyObject type but then I received another error which I couldn't find a solution for.

I changed the addObserver line to:

```<code>observableObject.addObserver(self, forKeyPath: keyPath, options: nil, context: WDPopupButton.ImageBindingContext)
</code>```

And got:

```<code>Type of expression is ambiguous without more context
</code>```

If casting observable to AnyObject is the solution, than what is this error means and what am i doing wrong?

Thanks

答:
The compiler is telling you that Any instances do not have a method called addObserver that is why observable.addObserver does not work. (Value of type 'Any' has no member 'addObserver')

For the observableObject.addObserver, it is also similar as above, AnyObject does not have addObserver method.

SOLUTION:

Don't cast to AnyObject, cast to NSObject. addObserver is accessible via NSObject instances. Then access addObserver via the casted NSObject instance

```<code>guard let observableObject = observable as? NSObject else {return}

observableObject.addObserver(self, forKeyPath: keyPath, options: nil, context: WDPopupButton.ImageBindingContext)

</code>```

Body:
I'm pretty new to Swift and "Apple" programming so excuse me if my question is silly.

I'm trying to sub-class NSPopupButton in order to add an option for binding the menu items' image property.

I want to override the "bind" function:

override func bind(_ binding: NSBindingName, to observable: Any, withKeyPath keyPath: String, options: [NSBindingOption : Any]? = nil)

And to observe the "observable" parameter so this is the code I have written till now:

class WDPopupButton: NSPopUpButton
{
    static let ImageBindingContext: UnsafeMutableRawPointer? = UnsafeMutableRawPointer(mutating: "imageContext")

    override func bind(_ binding: NSBindingName, to observable: Any, withKeyPath keyPath: String, options: [NSBindingOption : Any]? = nil)
    {
        if(binding == NSBindingName.image)
        {
            guard let observableObject = observable as AnyObject? else
            {
                return
            }

            observable.addObserver(self, forKeyPath: keyPath, options: nil, context: WDPopupButton.ImageBindingContext)

            ...
        }
    }
}

But I get the following error:

Value of type 'Any' has no member 'addObserver'

My question is, what do I need to do in order to call addObserver on the observable parameter?

As you can see, I did tried to cast observable to AnyObject type but then I received another error which I couldn't find a solution for.

I changed the addObserver line to:

observableObject.addObserver(self, forKeyPath: keyPath, options: nil, context: WDPopupButton.ImageBindingContext)

And got:

Type of expression is ambiguous without more context

If casting observable to AnyObject is the solution, than what is this error means and what am i doing wrong?

Thanks

Body:
The compiler is telling you that Any instances do not have a method called addObserver that is why observable.addObserver does not work. (Value of type 'Any' has no member 'addObserver')

For the observableObject.addObserver, it is also similar as above, AnyObject does not have addObserver method.

SOLUTION:

Don't cast to AnyObject, cast to NSObject. addObserver is accessible via NSObject instances. Then access addObserver via the casted NSObject instance

guard let observableObject = observable as? NSObject else {return}

observableObject.addObserver(self, forKeyPath: keyPath, options: nil, context: WDPopupButton.ImageBindingContext)


问:
How to distinguish between onClick and onFocus events in JavaScript?
I'm listening to the onFocus and to onClick events on the same input-element. The onFocus should always set a boolean to true and the onClick event handler should toggle this boolean.

But on a click both events are fired with the onFocus at first, so the boolean is being set to true first and then toggled by the onClick. How can I change this behaviour?

I tried to use stopPropagation inside the onClick event handler. Also setting a isClicked flag did not help. (Probably because both events are fired at the same time) (see JSFiddle)

```<code>let input = document.getElementById("input");
let isOpen = false

input.onclick = () => {
    isOpen = !isOpen
}

input.onfocus = () => {
    isOpen = true
}

input.onblur = () => {
    isOpen = false
}
</code>```

JSFiddle: http://jsfiddle.net/coh29gwe/7/

At the first click on the input the isOpen flag should be true but is false.

答:
This will solve your problem. It will allow only one update at one time.

```<code>let input = document.getElementById("input");
let isOpen = false

let updated = false;
function updateOpenedStatus(newStatus) {
    if (!updated) {
        isOpen = newStatus;
        updated = true;
        setTimeout(() => updated = false, 0);
    }
}

input.onclick = () => {
    updateOpenedStatus(!isOpen);
}

input.onfocus = () => {
    updateOpenedStatus(true);
}

input.onblur = () => {
    updateOpenedStatus(false);
}
</code>```

However, as it seems you might want to change the behaviour altogether, as this aria navigation-menu and this handles events differently from your implementation.

Body:
I'm listening to the onFocus and to onClick events on the same input-element. The onFocus should always set a boolean to true and the onClick event handler should toggle this boolean.

But on a click both events are fired with the onFocus at first, so the boolean is being set to true first and then toggled by the onClick. How can I change this behaviour?

I tried to use stopPropagation inside the onClick event handler. Also setting a isClicked flag did not help. (Probably because both events are fired at the same time) (see JSFiddle)

let input = document.getElementById("input");
let isOpen = false

input.onclick = () => {
    isOpen = !isOpen
}

input.onfocus = () => {
    isOpen = true
}

input.onblur = () => {
    isOpen = false
}

JSFiddle: http://jsfiddle.net/coh29gwe/7/

At the first click on the input the isOpen flag should be true but is false.

Body:
This will solve your problem. It will allow only one update at one time.

let input = document.getElementById("input");
let isOpen = false

let updated = false;
function updateOpenedStatus(newStatus) {
    if (!updated) {
        isOpen = newStatus;
        updated = true;
        setTimeout(() => updated = false, 0);
    }
}

input.onclick = () => {
    updateOpenedStatus(!isOpen);
}

input.onfocus = () => {
    updateOpenedStatus(true);
}

input.onblur = () => {
    updateOpenedStatus(false);
}

However, as it seems you might want to change the behaviour altogether, as this aria navigation-menu and this handles events differently from your implementation.


问:
Disable zoom with Openlayers
i'm using OpenLayers to display custom OSM maps on my website.

I've some points to respect: the map have to be fix (meaning that we can't drag it or zoom it).

I have a problem with the zoom, i can't manage to disable zoom with the mouse. Does anyone has a tip?

```<code>map = new OpenLayers.Map('map');
map.events.remove("move");
map.events.remove("movestart");
map.events.remove("moveend");
map.events.remove("zoomend");
map.events.remove("mouseover");
map.events.remove("mouseout");
map.events.remove("mousemove");
map.events.remove("zoomstart");
var nav = new OpenLayers.Control.Navigation({
  defaultDblClick: function(event) { return ; }
});
map[index].addControl(nav);
</code>```

Also, if someone has a tip to remove all Navigation events easier than that, it would be greatly appreciated.

答:
You could reset the controls array and then add the Zoom and TouchNavigation to it.

```<code>var map_controls = [];
map_controls.push( new OpenLayers.Control.Zoom() );
map_controls.push( new OpenLayers.Control.TouchNavigation() );
var map = new OpenLayers.Map({
  div: "map",
  controls: map_controls
});
</code>```

Hope it helps ! :)

Title: Disable zoom with Openlayers

Body:
i'm using OpenLayers to display custom OSM maps on my website.

I've some points to respect: the map have to be fix (meaning that we can't drag it or zoom it).

I have a problem with the zoom, i can't manage to disable zoom with the mouse. Does anyone has a tip?

map = new OpenLayers.Map('map');
map.events.remove("move");
map.events.remove("movestart");
map.events.remove("moveend");
map.events.remove("zoomend");
map.events.remove("mouseover");
map.events.remove("mouseout");
map.events.remove("mousemove");
map.events.remove("zoomstart");
var nav = new OpenLayers.Control.Navigation({
  defaultDblClick: function(event) { return ; }
});
map[index].addControl(nav);

Also, if someone has a tip to remove all Navigation events easier than that, it would be greatly appreciated.

Body:
You could reset the controls array and then add the Zoom and TouchNavigation to it.

var map_controls = [];
map_controls.push( new OpenLayers.Control.Zoom() );
map_controls.push( new OpenLayers.Control.TouchNavigation() );
var map = new OpenLayers.Map({
  div: "map",
  controls: map_controls
});

Hope it helps ! :)


问:
undefined element declaration 'xs:schema'
I am completely new to web service stuff.

I have to write rest web service client for a web service. The web service runs fine on SoapUI. WSDL file for the URL is provided to me. But when I add the wsdl file in my Eclipse project, it gives compilation error

```<code>src-resolve.4.2: Error resolving component 'xs:schema'. It was detected that 'xs:schema' is in namespace 'http://www.w3.org/2001/XMLSchema', but components from this namespace are not referenceable from schema document 'file:///E:/Ashish%20Workspace/HATStoLSAMS%20Webservice/HATS2LSAMSWS/WebContent/WEB-INF/wsdl/CorpsiteService.svc.wsdl'. If this is the incorrect namespace, perhaps the prefix of 'xs:schema' needs to be changed. If this is the correct namespace, then an appropriate 'import' tag should be added to 'file:///E:/Ashish%20Workspace/HATStoLSAMS%20Webservice/HATS2LSAMSWS/WebContent/WEB-INF/wsdl/CorpsiteService.svc.wsdl'.
</code>```

I googled a lot to get rid of these error but nothing worked.
If I ignore the errors and try creating stubs using wsimport as well as wsdl2java commands
it gives error

```<code>[ERROR] undefined element declaration 'xs:schema'
line 1 of http://chec.local/STAR.WCF/CorpsiteService.svc?singlewsdl
</code>```

I am using below command to generate stubs

```<code>wsimport -d e:\test -s E:\wssrc http://chec.local/STAR.WCF/CorpsiteService.svc?singlewsdl -wsdllocation "../../../../../WEB-INF/wsdl/CorpsiteService.svc.wsdl"
</code>```

I am stuck at this point and have been struggling on to this the whole day.
Any help regarding this would be really helpful

答:
I was facing same issue, resolved by just adding one line into maven plugin

```<code><args>
    <arg>-b</arg>
    <arg>http://www.w3.org/2001/XMLSchema.xsd</arg>
</args>
</code>```

My maven plugin is given below

```<code><plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>jaxws-maven-plugin</artifactId>
    <version>2.4.1</version>
    <executions>
        <execution>
            <id>periodictableaccessws</id>
            <goals>
                <goal>wsimport</goal>
            </goals>
            <configuration>
                <wsdlDirectory>${basedir}/src/main/resources/wsdl</wsdlDirectory>
                <args>
                    <arg>-b</arg>
                    <arg>http://www.w3.org/2001/XMLSchema.xsd</arg>
                </args>
                <wsdlFiles>
                    <wsdlFile>doosdaas.wsdl</wsdlFile>
                </wsdlFiles>
                <packageName>com.dss.doosdaas</packageName>
                <vmArgs>
                    <vmArg>-Djavax.xml.accessExternalDTD=all</vmArg>
                    <vmArg>-Djavax.xml.accessExternalSchema=all</vmArg>
                </vmArgs>
                <!--   <bindingDirectory>${basedir}/src/main/resources/jaxb</bindingDirectory>
                   <bindingFiles>
                       <bindingFile>jaxb_binding.xjb</bindingFile>
                   </bindingFiles>-->
            </configuration>
        </execution>
    </executions>
</plugin>
</code>```

Body:
I am completely new to web service stuff.

I have to write rest web service client for a web service. The web service runs fine on SoapUI. WSDL file for the URL is provided to me. But when I add the wsdl file in my Eclipse project, it gives compilation error

src-resolve.4.2: Error resolving component 'xs:schema'. It was detected that 'xs:schema' is in namespace 'http://www.w3.org/2001/XMLSchema', but components from this namespace are not referenceable from schema document 'file:///E:/Ashish%20Workspace/HATStoLSAMS%20Webservice/HATS2LSAMSWS/WebContent/WEB-INF/wsdl/CorpsiteService.svc.wsdl'. If this is the incorrect namespace, perhaps the prefix of 'xs:schema' needs to be changed. If this is the correct namespace, then an appropriate 'import' tag should be added to 'file:///E:/Ashish%20Workspace/HATStoLSAMS%20Webservice/HATS2LSAMSWS/WebContent/WEB-INF/wsdl/CorpsiteService.svc.wsdl'.

I googled a lot to get rid of these error but nothing worked.
If I ignore the errors and try creating stubs using wsimport as well as wsdl2java commands
it gives error

[ERROR] undefined element declaration 'xs:schema'
line 1 of http://chec.local/STAR.WCF/CorpsiteService.svc?singlewsdl

I am using below command to generate stubs

wsimport -d e:\test -s E:\wssrc http://chec.local/STAR.WCF/CorpsiteService.svc?singlewsdl -wsdllocation "../../../../../WEB-INF/wsdl/CorpsiteService.svc.wsdl"

I am stuck at this point and have been struggling on to this the whole day.
Any help regarding this would be really helpful

Body:
I was facing same issue, resolved by just adding one line into maven plugin

<args>
    <arg>-b</arg>
    <arg>http://www.w3.org/2001/XMLSchema.xsd</arg>
</args>

My maven plugin is given below

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>jaxws-maven-plugin</artifactId>
    <version>2.4.1</version>
    <executions>
        <execution>
            <id>periodictableaccessws</id>
            <goals>
                <goal>wsimport</goal>
            </goals>
            <configuration>
                <wsdlDirectory>${basedir}/src/main/resources/wsdl</wsdlDirectory>
                <args>
                    <arg>-b</arg>
                    <arg>http://www.w3.org/2001/XMLSchema.xsd</arg>
                </args>
                <wsdlFiles>
                    <wsdlFile>doosdaas.wsdl</wsdlFile>
                </wsdlFiles>
                <packageName>com.dss.doosdaas</packageName>
                <vmArgs>
                    <vmArg>-Djavax.xml.accessExternalDTD=all</vmArg>
                    <vmArg>-Djavax.xml.accessExternalSchema=all</vmArg>
                </vmArgs>
                <!--   <bindingDirectory>${basedir}/src/main/resources/jaxb</bindingDirectory>
                   <bindingFiles>
                       <bindingFile>jaxb_binding.xjb</bindingFile>
                   </bindingFiles>-->
            </configuration>
        </execution>
    </executions>
</plugin>


问:
transforming jquery to java script
I have this script made with jQuery which I am using to show / hide divs on my page.
I really need it to be made purely in JavaScript and I have no idea how to do this.
Could anyone help me ???
I think I need a converter or something . . .

```<code>$("#optiuni").children().click(function(){
    $("#" + $(this).attr('name')).show().siblings().hide();
    /*Gives the  link-activ class to the link that i clicked an link-inactive to all others*/
    $(this).attr('class','link-activ').siblings().attr('class','link-neactiv');
});
/*this makes shure that the first option from my list is active  incarcarea paginii*/
$("#optiuni li.prima").children().click();
</code>```

Sample markup:

```<code><div id="lista">
  <ul id="optiuni">
    <li id="titlu-lista-p"> <p class="listname-t">Past Events </p></li>

    <li name="opt-1" class="prima"><a href="#"><p class="listdata">28.02.2011</p><p class="listname">TABU Oscar Party</p> </a></li>

    <li name="opt-2" ><a href="#"><p class="listdata">24.03.2011</p><p class="listname">Cheese & Wine</p></a></li>
    <li name="opt-8"><a href="#"><p class="listdata">08.04.2011</p><p class="listname">George Baicea</p></a></li>
  </ul>
</div>

<div class="centru">
  <div id="continut" >
    <div id="opt-2" class="galerie" style="background-color: black;">
      <iframe id="gal" src="cheese/index.html"></iframe>
    </div>
    <div id="opt-1" class="galerie" style="background-color: black;">
      <iframe  src="tabu/index.html"></iframe>
    </div>

    <div id="opt-8" class="galerie" style="background-color: blue;">
      <iframe   src="no-ev/index.html"></iframe>
    </div>
  </div>
</div>
</code>```

答:
Here's an example of how you could do this based on the markup you linked to in your comment, as there are some assumptions you could make based on the jQuery version which don't hold when you see the markup.

jsFiddle with a live example.

```<code>// IE sucks
function addEvent(el, name, handler) {
  if (el.addEventListener) {
    el.addEventListener(name, handler, false);
  } else if (el.attachEvent) {
    // Make sure "this" references the element we're adding the event handler to
    el.attachEvent('on' + name, function() { handler.call(el, window.event); });
  }
}

function eachElementSibling(el, func) {
  var childNodes = el.parentNode.childNodes;
  for (var i = 0, sibling; sibling = childNodes[i]; i++) {
    if (sibling.nodeType !== 1 || sibling === el) {
      continue;
    }
    func(sibling);
  }
}

function activateLink() {
  var elToShow = document.getElementById(this.getAttribute('name'));
  elToShow.style.display = '';
  eachElementSibling(elToShow, function(s) { s.style.display = 'none'; });
  this.className = 'link-active';
  eachElementSibling(this, function(s) {
    if (s.getAttribute('name')) { s.className = 'link-neactiv'; }
  });
}

var items = document.getElementById('optiuni').getElementsByTagName('li');
var initialItem = null;
for (var i = 0, item; item = items[i]; i++) {
  // Need to filter, as non-link items are also present in the list
  if (item.getAttribute('name')) {
    addEvent(item, 'click', activateLink);
    if (item.className === 'prima') {
      initialItem= item;
    }
  }
}
if (initialItem) {
  activateLink.call(initialItem)
}
</code>```

Title: transforming jquery to java script

Body:
I have this script made with jQuery which I am using to show / hide divs on my page.
I really need it to be made purely in JavaScript and I have no idea how to do this.
Could anyone help me ???
I think I need a converter or something . . .

$("#optiuni").children().click(function(){
    $("#" + $(this).attr('name')).show().siblings().hide();
    /*Gives the  link-activ class to the link that i clicked an link-inactive to all others*/
    $(this).attr('class','link-activ').siblings().attr('class','link-neactiv');
});
/*this makes shure that the first option from my list is active  incarcarea paginii*/
$("#optiuni li.prima").children().click();

Sample markup:

Past Events

28.02.2011

TABU Oscar Party

24.03.2011

Cheese & Wine

08.04.2011

George Baicea

Body:
Here's an example of how you could do this based on the markup you linked to in your comment, as there are some assumptions you could make based on the jQuery version which don't hold when you see the markup.

jsFiddle with a live example.

// IE sucks
function addEvent(el, name, handler) {
  if (el.addEventListener) {
    el.addEventListener(name, handler, false);
  } else if (el.attachEvent) {
    // Make sure "this" references the element we're adding the event handler to
    el.attachEvent('on' + name, function() { handler.call(el, window.event); });
  }
}

function eachElementSibling(el, func) {
  var childNodes = el.parentNode.childNodes;
  for (var i = 0, sibling; sibling = childNodes[i]; i++) {
    if (sibling.nodeType !== 1 || sibling === el) {
      continue;
    }
    func(sibling);
  }
}

function activateLink() {
  var elToShow = document.getElementById(this.getAttribute('name'));
  elToShow.style.display = '';
  eachElementSibling(elToShow, function(s) { s.style.display = 'none'; });
  this.className = 'link-active';
  eachElementSibling(this, function(s) {
    if (s.getAttribute('name')) { s.className = 'link-neactiv'; }
  });
}

var items = document.getElementById('optiuni').getElementsByTagName('li');
var initialItem = null;
for (var i = 0, item; item = items[i]; i++) {
  // Need to filter, as non-link items are also present in the list
  if (item.getAttribute('name')) {
    addEvent(item, 'click', activateLink);
    if (item.className === 'prima') {
      initialItem= item;
    }
  }
}
if (initialItem) {
  activateLink.call(initialItem)
}


问:
Splitting javascript object to normal String with = sign
How can I dynamically convert a json object to the following manner
I do have </p>

```<code>{ eligible: true, qualified:true }
</code>```

<p>but I need to make it like this </p>

```<code>eligible= true, qualified=true
</code>```

答:
You can get entries of object and change the key/value to string using reduce

let obj = { eligible: true, qualified:true }

let str = Object.entries(obj).reduce((op,[key,value],index,arr)=>{
  op+= `${key}=${value}${index !== arr.length-1 ? ',' : ''} `
  return op
},'')

console.log(str.trim())```

Body:
How can I dynamically convert a json object to the following manner
I do have

{ eligible: true, qualified:true }

but I need to make it like this

eligible= true, qualified=true


问:
how get the vertices that constitute a smaller triangle in terms of the barycentric coordinates?
this post is discussing the conversion from barycentric coordinates to Cartesian coordinates.

it seems that the figure (fig_1) only illustrates 3 points

B(0,0,1), A(0,1,0), C(1,0,0)

i am trying to understand the conversion, here is my code

```<code>x_inner = np.array([0.375, 0.5  , 0.625, 0.375])
y_inner = np.array([0.21650635, 0.4330127 , 0.21650635, 0.21650635])
x_outer = np.array([0. , 0.5, 1. , 0. ])
y_outer = np.array([0.       , 0.8660254, 0.       , 0.       ])
plt.plot(x_outer,y_outer)
plt.plot(x_inner,y_inner,c='tab:orange')
plt.scatter(x_outer, y_outer)
plt.scatter(x_inner, y_inner)
</code>```

the values constitute the coordinates array come from the original post.

here is the output.

the inner orange triangle consists of 3 vertices which correspond to the points (1/4,1/4,1/2), (1/4,1/2,1/4), (1/2,1/4,1/4) in original barycentric coordinates.

the question is, how to get a smaller triangle like 1/10 of the orange one.

ps:
sorry for fig_1 doesn't match the true values.

答:
Consider a triangle ABC and a scaling factor r > 0.

The centroid of ABC is G := (A + B + C) / 3. We want to perform a uniform scaling by r that keeps G fixed. This transformation is given by h(V) := G + (V - G) * r.

To obtain the scaled triangle, A'B'C', we apply h to each of the vertices of ABC:

```<code>A' := h(A) = A * (1+2*r)/3 + B * (1-r)/3   + C * (1-r)/3
B' := h(B) = A * (1-r)/3   + B * (1+2*r)/3 + C * (1-r)/3
C' := h(C) = A * (1-r)/3   + B * (1-r)/3   + C * (1+2*r)/3
</code>```

The coefficients above are barycentric coordinates.

In the case of your inner triangle r = 1/4.

Body:
this post is discussing the conversion from barycentric coordinates to Cartesian coordinates.

it seems that the figure (fig_1) only illustrates 3 points

B(0,0,1), A(0,1,0), C(1,0,0)

i am trying to understand the conversion, here is my code

x_inner = np.array([0.375, 0.5  , 0.625, 0.375])
y_inner = np.array([0.21650635, 0.4330127 , 0.21650635, 0.21650635])
x_outer = np.array([0. , 0.5, 1. , 0. ])
y_outer = np.array([0.       , 0.8660254, 0.       , 0.       ])
plt.plot(x_outer,y_outer)
plt.plot(x_inner,y_inner,c='tab:orange')
plt.scatter(x_outer, y_outer)
plt.scatter(x_inner, y_inner)

the values constitute the coordinates array come from the original post.

here is the output.

the inner orange triangle consists of 3 vertices which correspond to the points (1/4,1/4,1/2), (1/4,1/2,1/4), (1/2,1/4,1/4) in original barycentric coordinates.

the question is, how to get a smaller triangle like 1/10 of the orange one.

ps:
sorry for fig_1 doesn't match the true values.

Body:
Consider a triangle ABC and a scaling factor r > 0.

The centroid of ABC is G := (A + B + C) / 3. We want to perform a uniform scaling by r that keeps G fixed. This transformation is given by h(V) := G + (V - G) * r.

To obtain the scaled triangle, A'B'C', we apply h to each of the vertices of ABC:

A' := h(A) = A * (1+2*r)/3 + B * (1-r)/3   + C * (1-r)/3
B' := h(B) = A * (1-r)/3   + B * (1+2*r)/3 + C * (1-r)/3
C' := h(C) = A * (1-r)/3   + B * (1-r)/3   + C * (1+2*r)/3

The coefficients above are barycentric coordinates.

In the case of your inner triangle r = 1/4.


问:
ngClass calls method Multiple times
I have created a method and attached it to ngClass for adding two styles depending upon the condition.I am also passing the number as parameter to be used in the switch case.

component.html

```<code><div class="circle" [ngClass]="setMyClassesCircle(1)">
<div class="circle" [ngClass]="setMyClassesCircle(2)">
<div class="circle" [ngClass]="setMyClassesCircle(3)">
<div class="circle" [ngClass]="setMyClassesCircle(4)">
</code>```

component.ts

```<code> setMyClassesCircle(val)
 {
   let circleClasses
   console.log('Inside method')

   switch(val)
   {

     case 1:
     {

    circleClasses = {
   'inprogress-circle': this.inProgress == val,
   'completed-circle': this.oneCompleted == true

   }
     break;
   }
   case 2:
   {
    circleClasses = {
   'inprogress-circle': this.inProgress == val,
   'completed-circle': this.twoCompleted == true
   }
     break;
   }
   case 3:
   {
    circleClasses = {
   'inprogress-circle': this.inProgress == val,
   'completed-circle': this.threeCompleted == true
   }
     break;
   }
   case 4:
   {
    circleClasses = {
   'inprogress-circle': this.inProgress == val,
   'completed-circle': this.fourCompleted == true
   }
     break;
   }
</code>```

Through this way I am binding circleClasses to my template.

But the issue I am facing is setMyClassesCircle() method is called more than 10 times, while I am calling the method only four times.'Inside method' is printed more than 10 times in my console.

I could not figure out why the method is being called these many number of times.

答:
There have been four node “Div” inside DOM, so each node called at least one time & each time your method returning different value which again raise 4 times.

Like this would be your seq:

1st Detect Change – Method called –4 Times.
2nd Detect Change – Method called –4 Times.
3rd Detect Change – Method called –4 Times.
4th Detect Change – Method called –4 Times.
So, over all your method should be called 16 times if there are 4 nodes. Try to remove 1-Node, and your method should be called 4 X 3= 12 Times. This is how Angular works!!

Title: ngClass calls method Multiple times

Body:
I have created a method and attached it to ngClass for adding two styles depending upon the condition.I am also passing the number as parameter to be used in the switch case.

component.html

component.ts

 setMyClassesCircle(val)
 {
   let circleClasses
   console.log('Inside method')

   switch(val)
   {

     case 1:
     {

    circleClasses = {
   'inprogress-circle': this.inProgress == val,
   'completed-circle': this.oneCompleted == true

   }
     break;
   }
   case 2:
   {
    circleClasses = {
   'inprogress-circle': this.inProgress == val,
   'completed-circle': this.twoCompleted == true
   }
     break;
   }
   case 3:
   {
    circleClasses = {
   'inprogress-circle': this.inProgress == val,
   'completed-circle': this.threeCompleted == true
   }
     break;
   }
   case 4:
   {
    circleClasses = {
   'inprogress-circle': this.inProgress == val,
   'completed-circle': this.fourCompleted == true
   }
     break;
   }

Through this way I am binding circleClasses to my template.

But the issue I am facing is setMyClassesCircle() method is called more than 10 times, while I am calling the method only four times.'Inside method' is printed more than 10 times in my console.

I could not figure out why the method is being called these many number of times.


答:
You can use Object.entries to get a two dimensional array of object and then use Array.prototype.map to join the array element (key, value) with an =.

Finally join the array with a , to get the expected output.

var x = { eligible: true, qualified:true };

var newX = Object.entries(x).map(el => el.join("=")).join(", ");

console.log(newX);```

Title: Splitting javascript object to normal String with = sign


问:
Unable to use the subclass
Hello I have this code :

```<code>class A:
    def __init__(self, name):
        self.name = name

class B(A):
    def __init__(self):
        super.__init__()
</code>```

But I don't achieve to use the class B :

I tried to write :

```<code>C = B()
</code>```

But I get :

```<code>TypeError
Traceback (most recent call last)
<ipython-input-7-ea9745abfeb2> in <module>()
----> 1 C = B()

<ipython-input-4-2d2ef2cc5406> in __init__(self)
  5 class B(A):
  6   def __init__(self):
----> 7     super.__init__()

TypeError: descriptor '__init__' of 'super' object needs an argument
</code>```

Could you help me please ?

答:
You must provide an argument to super,

```<code>class A:
    def __init__(self, name):
        self.name = name

class B(A):
    def __init__(self, name):
        super().__init__(name)
</code>```

or a default argument to name in A

```<code>class A:
    def __init__(self, name=''):
        self.name = name

class B(A):
    def __init__(self):
        super().__init__()   # this works, but is probably not a good idea
                             # as you might need to pass a name to A, at some moment
</code>```

maybe, in your case, B does not need an __init__?

```<code>class A:
    def __init__(self, name=''):
        self.name = name

class B(A):
    pass
</code>```

Title: Unable to use the subclass

Body:
Hello I have this code :

class A:
    def __init__(self, name):
        self.name = name

class B(A):
    def __init__(self):
        super.__init__()

But I don't achieve to use the class B :

I tried to write :

C = B()

But I get :

TypeError
Traceback (most recent call last)
<ipython-input-7-ea9745abfeb2> in <module>()
----> 1 C = B()

<ipython-input-4-2d2ef2cc5406> in __init__(self)
  5 class B(A):
  6   def __init__(self):
----> 7     super.__init__()

TypeError: descriptor '__init__' of 'super' object needs an argument

Could you help me please ?

Body:
You must provide an argument to super,

class A:
    def __init__(self, name):
        self.name = name

class B(A):
    def __init__(self, name):
        super().__init__(name)

or a default argument to name in A

class A:
    def __init__(self, name=''):
        self.name = name

class B(A):
    def __init__(self):
        super().__init__()   # this works, but is probably not a good idea
                             # as you might need to pass a name to A, at some moment

maybe, in your case, B does not need an __init__?

class A:
    def __init__(self, name=''):
        self.name = name

class B(A):
    pass


问:
TagHelper PreContent and PostContent not showing up in HTML when overriding InputTagHelper
I want to create a tag helper to put some HTML before and after <input> tags, but I want to keep the default asp-for behavior and access the ModelExpression data.

To this end, I tried to override the Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper type, as described in this post. However, even though I can verify in the debugger that the Process method is being called PreContent and PostContent are both being set, nothing shows up in the HTML other than the standard <input> tag. It works fine when creating a tag helper from scratch for another tag though.

I created a small project to demonstrate this issue. I put the entire project on GitHub, and I'm copying the specific tag helper I'm trying to create below.

    [HtmlTargetElement("input", Attributes = "asp-for,test-label")]
    public class TestTagHelper : InputTagHelper
    {
        public TestTagHelper(IHtmlGenerator generator) : base(generator)
        {
        }

        [HtmlAttributeName("test-label")]
        public string Label { get; set; }

        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            output.PreContent.SetHtmlContent($"{WebUtility.HtmlEncode(Label)} ");
            output.PostContent.SetHtmlContent($" ({WebUtility.HtmlEncode(For.Name)})"); // access information from the input tag
            base.Process(context, output);
        }
    }
```

Am I missing something obvious? Is there a caveat to doing this? Or is this something that just can't be done?

答:
For this issue, we could try to call PreElement and PostElement instead of PreContent and PostContent like

```<code>[HtmlTargetElement("input", Attributes = "asp-for,test-label")]
public class TestTagHelper : InputTagHelper
{
    public TestTagHelper(IHtmlGenerator generator) : base(generator)
    {
    }

    [HtmlAttributeName("test-label")]
    public string Label { get; set; }

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        base.Process(context, output);
        output.PreElement.SetHtmlContent($"<b>{WebUtility.HtmlEncode(Label)}</b>");
        output.PostElement.SetHtmlContent($"<i>({WebUtility.HtmlEncode(For.Name)})</i>");
    }
}
</code>```

Body:
I want to create a tag helper to put some HTML before and after <input> tags, but I want to keep the default asp-for behavior and access the ModelExpression data.

To this end, I tried to override the Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper type, as described in this post. However, even though I can verify in the debugger that the Process method is being called PreContent and PostContent are both being set, nothing shows up in the HTML other than the standard <input> tag. It works fine when creating a tag helper from scratch for another tag though.

I created a small project to demonstrate this issue. I put the entire project on GitHub, and I'm copying the specific tag helper I'm trying to create below.

    [HtmlTargetElement("input", Attributes = "asp-for,test-label")]
    public class TestTagHelper : InputTagHelper
    {
        public TestTagHelper(IHtmlGenerator generator) : base(generator)
        {
        }

        [HtmlAttributeName("test-label")]
        public string Label { get; set; }

        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            output.PreContent.SetHtmlContent($"{WebUtility.HtmlEncode(Label)} ");
            output.PostContent.SetHtmlContent($" ({WebUtility.HtmlEncode(For.Name)})"); // access information from the input tag
            base.Process(context, output);
        }
    }

Am I missing something obvious? Is there a caveat to doing this? Or is this something that just can't be done?

Body:
For this issue, we could try to call PreElement and PostElement instead of PreContent and PostContent like

[HtmlTargetElement("input", Attributes = "asp-for,test-label")]
public class TestTagHelper : InputTagHelper
{
    public TestTagHelper(IHtmlGenerator generator) : base(generator)
    {
    }

    [HtmlAttributeName("test-label")]
    public string Label { get; set; }

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        base.Process(context, output);
        output.PreElement.SetHtmlContent($"<b>{WebUtility.HtmlEncode(Label)}</b>");
        output.PostElement.SetHtmlContent($"<i>({WebUtility.HtmlEncode(For.Name)})</i>");
    }
}


问:
Uploading similar apps on Google Play and App Store
We have a company that helps people create apps for their websites, and we complately rely on webview technology, and push notifications.

We use one developer account to upload all our clients apps to both Google Play and App Store

Would this be considered illegal? Are there any restrictions on uploading similar functionality apps (webviews)?

答:
Google Play: you can't do that either:
From the Google Play Policy center, the Spam and Minimum functionality section, under "Repetitive content"

Apps that are created by an automated tool, wizard service, or based on templates and submitted to Google Play by the operator of that service on behalf of other persons are not allowed. Such apps are only permissible if they are published by an individually registered developer account belonging to the user of the automated tool, not the operator of the service.


问:
kotlin coroutine withTimeout does not cancel when using withContext to get non-blocking code
I am using withContext to transform a function into a suspending function which does not block the calling thread.
For this I used https://medium.com/@elizarov/blocking-threads-suspending-coroutines-d33e11bf4761 as reference.

Now I would like to invoke this function with a timeout. For this I use withTimeout to call the function as such:

```<code>@Test
internal fun timeout() {
    runBlocking {
        logger.info("launching")
        try {
            withTimeout(1000) {
                execute()
            }
        } catch (e: TimeoutCancellationException) {
            logger.info("timed out", e)
        }
    }
}

private suspend fun execute() {
    withContext(Dispatchers.IO) {
        logger.info("sleeping")
        Thread.sleep(2000)
    }
}
</code>```

So what I would expect is that after 1000 millis the async launched coroutine is cancelled and the TimeoutCancellationException is thrown.

But what happens is that the full 2000 millis pass and when the coroutine is completed the exception is thrown:

14:46:29.231 [main @coroutine#1] INFO  b.t.c.c.CoroutineControllerTest
  - launching

  14:46:29.250 [DefaultDispatcher-worker-1 @coroutine#1] INFO  b.t.c.c.CoroutineControllerTest - sleeping

  14:46:31.261 [main@coroutine#1] INFO  b.t.c.c.CoroutineControllerTest - timed out
  kotlinx.coroutines.TimeoutCancellationException: Timed out waiting for
  1000 ms   at
  kotlinx.coroutines.TimeoutKt.TimeoutCancellationException(Timeout.kt:128)
    at kotlinx.coroutines.TimeoutCoroutine.run(Timeout.kt:94)   at
  kotlinx.coroutines.EventLoopImplBase$DelayedRunnableTask.run(EventLoop.kt:307)
    at
  kotlinx.coroutines.EventLoopImplBase.processNextEvent(EventLoop.kt:116)
    at kotlinx.coroutines.DefaultExecutor.run(DefaultExecutor.kt:68)    at
  java.lang.Thread.run(Thread.java:748)

Am I using something wrong?

Or perhaps this is the intended behavior? In the documentation the counter also gets to 2 which means 1500 millis have passed before the coroutine is cancelled:
https://github.com/Kotlin/kotlinx.coroutines/blob/master/docs/cancellation-and-timeouts.md#timeout

答:
You can achieve progress after timeout if you launch a child coroutine and await on its completion:

```<code>fun timeout() {
    runBlocking {
        logger.info("launching")
        try {
            withTimeout(100) {
                execute()
            }
        } catch (e: TimeoutCancellationException) {
            logger.info("timed out", e)
        }
    }
}

private suspend fun execute() =
    GlobalScope.launch(Dispatchers.IO) {
        logger.info("sleeping")
        Thread.sleep(2000)
    }.join()
</code>```

With this you have decoupled the blocked child coroutine from the dispatcher in which you join() it, so the suspend fun join() can immediately react to cancellation.

Note that this is more of a workaround than a full solution because one of the threads in the IO dispatcher will still remain blocked until the sleep() expires.

Body:
I am using withContext to transform a function into a suspending function which does not block the calling thread.
For this I used https://medium.com/@elizarov/blocking-threads-suspending-coroutines-d33e11bf4761 as reference.

Now I would like to invoke this function with a timeout. For this I use withTimeout to call the function as such:

@Test
internal fun timeout() {
    runBlocking {
        logger.info("launching")
        try {
            withTimeout(1000) {
                execute()
            }
        } catch (e: TimeoutCancellationException) {
            logger.info("timed out", e)
        }
    }
}

private suspend fun execute() {
    withContext(Dispatchers.IO) {
        logger.info("sleeping")
        Thread.sleep(2000)
    }
}

So what I would expect is that after 1000 millis the async launched coroutine is cancelled and the TimeoutCancellationException is thrown.

But what happens is that the full 2000 millis pass and when the coroutine is completed the exception is thrown:

14:46:29.231 [main @coroutine#1] INFO  b.t.c.c.CoroutineControllerTest
  - launching

  14:46:29.250 [DefaultDispatcher-worker-1 @coroutine#1] INFO  b.t.c.c.CoroutineControllerTest - sleeping

  14:46:31.261 [main@coroutine#1] INFO  b.t.c.c.CoroutineControllerTest - timed out
  kotlinx.coroutines.TimeoutCancellationException: Timed out waiting for
  1000 ms   at
  kotlinx.coroutines.TimeoutKt.TimeoutCancellationException(Timeout.kt:128)
    at kotlinx.coroutines.TimeoutCoroutine.run(Timeout.kt:94)   at
  kotlinx.coroutines.EventLoopImplBase$DelayedRunnableTask.run(EventLoop.kt:307)
    at
  kotlinx.coroutines.EventLoopImplBase.processNextEvent(EventLoop.kt:116)
    at kotlinx.coroutines.DefaultExecutor.run(DefaultExecutor.kt:68)    at
  java.lang.Thread.run(Thread.java:748)

Am I using something wrong?

Or perhaps this is the intended behavior? In the documentation the counter also gets to 2 which means 1500 millis have passed before the coroutine is cancelled:
https://github.com/Kotlin/kotlinx.coroutines/blob/master/docs/cancellation-and-timeouts.md#timeout

Body:
You can achieve progress after timeout if you launch a child coroutine and await on its completion:

fun timeout() {
    runBlocking {
        logger.info("launching")
        try {
            withTimeout(100) {
                execute()
            }
        } catch (e: TimeoutCancellationException) {
            logger.info("timed out", e)
        }
    }
}

private suspend fun execute() =
    GlobalScope.launch(Dispatchers.IO) {
        logger.info("sleeping")
        Thread.sleep(2000)
    }.join()

With this you have decoupled the blocked child coroutine from the dispatcher in which you join() it, so the suspend fun join() can immediately react to cancellation.

Note that this is more of a workaround than a full solution because one of the threads in the IO dispatcher will still remain blocked until the sleep() expires.


问:
How to make my 'angular search list pipe' Case-Insensitive?
I have a list of jobs and search box. In search box , user enters the job name to search job . I made an angular pipe to search the JOB on the base of typed alphabet by user in search box,means list of job is getting updated having only those item which has typed alphabet by user
Its working perfectly, but it is case sensitive ,I want to make it case sensitive.
I already made case sensitive  "Contains" based angular pipe.I tried to make searched keyword to on the base of lowercase but did't work.

```<code>    **TS.file**
    @Pipe({ name: 'filterByName' })
    export class filterNames implements PipeTransform {
      transform(listOfNames: string[], nameToFilter: string, ): string[] {
        var upperLetter=nameToFilter.toUpperCase();
        var smallLetter=nameToFilter.toLowerCase();
        if (!listOfNames) return null;
        if (!nameToFilter) return listOfNames;
        return listOfNames.filter(n =>
   ((n.indexOf(smallLetter) >= 0)||(n.indexOf(upperLetter) >= 0))
        );
      }
    }

    **Html file:**
    <mat-form-field class="example-full-width">
      <input [(ngModel)]="filterName" matInput placeholder="Find jobs">
    <mat-form-field

    <mat-nav-list *ngIf ="showlist"  #jobs>
      <mat-list-item *ngFor="let response of JOBS| filterByName:filterName">
        {{response}}
      </mat-list-item>
    </mat-nav-list>
</code>```

I expect if user type "A" in search box , list should be updated having list item 'A' and 'a' both. Now in this case , only "A" items are updating.
kindly let me know if anymore input is required.
Thanks in advance.

答:
This can be done by forcing both the name in the listOfNames (within the filter) and the nameToFilter to uppercase.

```<code>import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'filterByName'
})
export class FilterNamesPipe implements PipeTransform {

  transform(listOfNames: string[], nameToFilter: string=''): string[] {
        var upperLetter = nameToFilter.toUpperCase();
        if (!listOfNames) return null;
        // console.log('listOfNames', listOfNames, 'nameToFilter', nameToFilter, 'upperLetter', upperLetter );
        if (!nameToFilter || nameToFilter === '') return listOfNames;
        return listOfNames.filter(name =>
          name.toUpperCase().startsWith(upperLetter)
        )
  }

}
</code>```

Stackblitz example -  https://stackblitz.com/edit/angular-so-56307438

Body:
I have a list of jobs and search box. In search box , user enters the job name to search job . I made an angular pipe to search the JOB on the base of typed alphabet by user in search box,means list of job is getting updated having only those item which has typed alphabet by user
Its working perfectly, but it is case sensitive ,I want to make it case sensitive.
I already made case sensitive  "Contains" based angular pipe.I tried to make searched keyword to on the base of lowercase but did't work.

    **TS.file**
    @Pipe({ name: 'filterByName' })
    export class filterNames implements PipeTransform {
      transform(listOfNames: string[], nameToFilter: string, ): string[] {
        var upperLetter=nameToFilter.toUpperCase();
        var smallLetter=nameToFilter.toLowerCase();
        if (!listOfNames) return null;
        if (!nameToFilter) return listOfNames;
        return listOfNames.filter(n =>
   ((n.indexOf(smallLetter) >= 0)||(n.indexOf(upperLetter) >= 0))
        );
      }
    }

    **Html file:**
    <mat-form-field class="example-full-width">
      <input [(ngModel)]="filterName" matInput placeholder="Find jobs">
    <mat-form-field

    <mat-nav-list *ngIf ="showlist"  #jobs>
      <mat-list-item *ngFor="let response of JOBS| filterByName:filterName">
        {{response}}
      </mat-list-item>
    </mat-nav-list>

I expect if user type "A" in search box , list should be updated having list item 'A' and 'a' both. Now in this case , only "A" items are updating.
kindly let me know if anymore input is required.
Thanks in advance.

Body:
This can be done by forcing both the name in the listOfNames (within the filter) and the nameToFilter to uppercase.

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'filterByName'
})
export class FilterNamesPipe implements PipeTransform {

  transform(listOfNames: string[], nameToFilter: string=''): string[] {
        var upperLetter = nameToFilter.toUpperCase();
        if (!listOfNames) return null;
        // console.log('listOfNames', listOfNames, 'nameToFilter', nameToFilter, 'upperLetter', upperLetter );
        if (!nameToFilter || nameToFilter === '') return listOfNames;
        return listOfNames.filter(name =>
          name.toUpperCase().startsWith(upperLetter)
        )
  }

}

Stackblitz example -  https://stackblitz.com/edit/angular-so-56307438


问:
Check if output from grep is empty before sending email from Crontab
I have the following entry in my Crontab which will grep my logs for any instance of error, warning, notice etc...

41 17 * * * cd /var/log/crmpicco-logs/; grep -E "error|Warning|Error|Notice|Fatal" $(find . -mtime 0 -type f) 2>&1 | mail -s "Errors/Warnings from Logs" info@ayrshireminis.com

What I would like to do is tweak it so that it only executes the mail command if the output from the grep search returns a result. So, if it's empty then I don't want to receive an email.

答:
From man mail:

```<code>   -E     If  an  outgoing message does not contain any text in its first or only message part, do not send it but discard it silently, effectively setting the skipemptybody variable at program startup.  This is useful for sending messages
          from scripts started by cron(8).
</code>```

So, i think, it is possible just to add -E key to command:

```<code>41 17 * * * cd /var/log/crmpicco-logs/; grep -E "error|Warning|Error|Notice|Fatal" $(find . -mtime 0 -type f) 2>&1 | mail -E -s "Errors/Warnings from Logs" info@ayrshireminis.com
</code>```

Body:
From man mail:

   -E     If  an  outgoing message does not contain any text in its first or only message part, do not send it but discard it silently, effectively setting the skipemptybody variable at program startup.  This is useful for sending messages
          from scripts started by cron(8).

So, i think, it is possible just to add -E key to command:

41 17 * * * cd /var/log/crmpicco-logs/; grep -E "error|Warning|Error|Notice|Fatal" $(find . -mtime 0 -type f) 2>&1 | mail -E -s "Errors/Warnings from Logs" info@ayrshireminis.com