问:
How to query from two collections in mongodb using aggregate?
I have the two following collections in my mongoDB:

PRODUCTS:

```<code>[
    {
        "_id": "5ebb0984e95e3e9e35aab3bf",
        "name": "Product 1",
        "brand": "ABC",
        "code": "7891910000190",
        "description": "Lorem Ipsum"
    },
    {
        "_id": "5ebdb9f3d943ae000a4a9714",
        "name": "Product 2",
        "brand": "DEF",
        "code": "7891910000190",
        "description": "Lorem Ipsum"
    }
]
</code>```

STOCK GOODS:

```<code>[
    {
        "_id": "5ed0586b7f2cfe02387d0706",
        "companyId": "5ed0491bf9a892a5fd9b4d9b",
        "branchId": "5ed049a8f9a892a5fd9b4d9e",
        "inventoryId": "5ed04d01e9e43cee79734b95",
        "productId": "5ebb0984e95e3e9e35aab3bf"
    },
    {
        "_id": "5ed058da75e4e01013f5779d",
        "companyId": "5ed0491bf9a892a5fd9b4d9b",
        "branchId": "5ed049a8f9a892a5fd9b4d9e",
        "inventoryId": "5ed04cede9e43cee79734b93",
        "productId": "5ebb0984e95e3e9e35aab3bf"
    },
    {
        "_id": "5ed059483da3bafccb34cec3",
        "companyId": "5ed0491bf9a892a5fd9b4d9b",
        "branchId": "5ed049a8f9a892a5fd9b4d9e",
        "inventoryId": "5ed04d01e9e43cee79734b95",
        "productId": "5ebb0984e95e3e9e35aab3bf"
    }
]
</code>```

I want to get the follow result:

```<code>[
    {
        "_id": "5ed0586b7f2cfe02387d0706",
        "data": {
            "_id": "5ebb0984e95e3e9e35aab3bf",
            "brand": "ABC",
            "code": "7891910000190",
            "description": "Lorem Ipsum",
            "name": "Product 1",
        }
    },
    {
        "_id": "5ed059483da3bafccb34cec3",
        "data": {
            "_id": "5ebb0984e95e3e9e35aab3bf",
            "brand": "ABC",
            "code": "7891910000190",
            "description": "Lorem Ipsum",
            "name": "Product 1",
        }
    }
]
</code>```

My NodeJS and MongoDB aggregate look like this:

```<code>const mongoose = require("mongoose");
const StockGoods = mongoose.model("StockGoods");
ObjectId = require("mongodb").ObjectID;

exports.getProducts = async (companyId, branchId, inventoryId) => {
  const response = await StockGoods.aggregate([
    {
      $match: {
        companyId: new ObjectId("5ed0491bf9a892a5fd9b4d9b"), // new ObjectId(companyId)
        inventoryId: new ObjectId("5ed04d01e9e43cee79734b95"), // new ObjectId(inventoryId)
        branchId: new ObjectId("5ed049a8f9a892a5fd9b4d9e"), // new ObjectId(branchId)
      },
    },
    {
      $lookup: {
        from: "products",
        localField: "productId",
        foreignField: "_id",
        as: "inventory_docs",
      },
    },
    {
      $project: {
        data: "$inventory_docs",
      },
    },
    { $unwind: "$data" },
  ]);
  return response;
};
</code>```

This is the same database and the aggregate function described above, you can check this: https://mongoplayground.net/p/FRgAIfO2bwh.

But, this function aggregate does not working when I use nodejs.
My API returns nothing (empty array).

Whats wrong?

答:
Issue here is the way you have stored data in collection.... StockGoods collection has companyId, inventoryId and  branchIdas a string but aggregation is looking for ObjectId aee below match criteria:

```<code> $match: {
    companyId: new ObjectId("5ed0491bf9a892a5fd9b4d9b"), // new ObjectId(companyId)
    inventoryId: new ObjectId("5ed04d01e9e43cee79734b95"), // new
    ObjectId(inventoryId)
    branchId: new ObjectId("5ed049a8f9a892a5fd9b4d9e"), // new ObjectId(branchId)
  },
</code>```

Based on the data you store in DB either you need to update match with string.

So below Aggregation will work for you..

```<code>[
 {
  "$match": {
     "companyId": "5ed0491bf9a892a5fd9b4d9b",
     "inventoryId": "5ed04d01e9e43cee79734b95",
     "branchId": "5ed049a8f9a892a5fd9b4d9e"
  }
  },
 {
  "$lookup": {
     "from": "products",
     "localField": "productId",
     "foreignField": "_id",
     "as": "inventory_docs"
  }
  },
 {
  "$project": {
     "data": "$inventory_docs"
  }
 },
{
  "$unwind": "$data"
}
</code>```

]

This works you can test in Compass Aggregator tab

Body:
I have the two following collections in my mongoDB:

PRODUCTS:

[
    {
        "_id": "5ebb0984e95e3e9e35aab3bf",
        "name": "Product 1",
        "brand": "ABC",
        "code": "7891910000190",
        "description": "Lorem Ipsum"
    },
    {
        "_id": "5ebdb9f3d943ae000a4a9714",
        "name": "Product 2",
        "brand": "DEF",
        "code": "7891910000190",
        "description": "Lorem Ipsum"
    }
]

STOCK GOODS:

[
    {
        "_id": "5ed0586b7f2cfe02387d0706",
        "companyId": "5ed0491bf9a892a5fd9b4d9b",
        "branchId": "5ed049a8f9a892a5fd9b4d9e",
        "inventoryId": "5ed04d01e9e43cee79734b95",
        "productId": "5ebb0984e95e3e9e35aab3bf"
    },
    {
        "_id": "5ed058da75e4e01013f5779d",
        "companyId": "5ed0491bf9a892a5fd9b4d9b",
        "branchId": "5ed049a8f9a892a5fd9b4d9e",
        "inventoryId": "5ed04cede9e43cee79734b93",
        "productId": "5ebb0984e95e3e9e35aab3bf"
    },
    {
        "_id": "5ed059483da3bafccb34cec3",
        "companyId": "5ed0491bf9a892a5fd9b4d9b",
        "branchId": "5ed049a8f9a892a5fd9b4d9e",
        "inventoryId": "5ed04d01e9e43cee79734b95",
        "productId": "5ebb0984e95e3e9e35aab3bf"
    }
]

I want to get the follow result:

[
    {
        "_id": "5ed0586b7f2cfe02387d0706",
        "data": {
            "_id": "5ebb0984e95e3e9e35aab3bf",
            "brand": "ABC",
            "code": "7891910000190",
            "description": "Lorem Ipsum",
            "name": "Product 1",
        }
    },
    {
        "_id": "5ed059483da3bafccb34cec3",
        "data": {
            "_id": "5ebb0984e95e3e9e35aab3bf",
            "brand": "ABC",
            "code": "7891910000190",
            "description": "Lorem Ipsum",
            "name": "Product 1",
        }
    }
]

My NodeJS and MongoDB aggregate look like this:

const mongoose = require("mongoose");
const StockGoods = mongoose.model("StockGoods");
ObjectId = require("mongodb").ObjectID;

exports.getProducts = async (companyId, branchId, inventoryId) => {
  const response = await StockGoods.aggregate([
    {
      $match: {
        companyId: new ObjectId("5ed0491bf9a892a5fd9b4d9b"), // new ObjectId(companyId)
        inventoryId: new ObjectId("5ed04d01e9e43cee79734b95"), // new ObjectId(inventoryId)
        branchId: new ObjectId("5ed049a8f9a892a5fd9b4d9e"), // new ObjectId(branchId)
      },
    },
    {
      $lookup: {
        from: "products",
        localField: "productId",
        foreignField: "_id",
        as: "inventory_docs",
      },
    },
    {
      $project: {
        data: "$inventory_docs",
      },
    },
    { $unwind: "$data" },
  ]);
  return response;
};

This is the same database and the aggregate function described above, you can check this: https://mongoplayground.net/p/FRgAIfO2bwh.

But, this function aggregate does not working when I use nodejs.
My API returns nothing (empty array).

Whats wrong?

Body:
Issue here is the way you have stored data in collection.... StockGoods collection has companyId, inventoryId and  branchIdas a string but aggregation is looking for ObjectId aee below match criteria:

 $match: {
    companyId: new ObjectId("5ed0491bf9a892a5fd9b4d9b"), // new ObjectId(companyId)
    inventoryId: new ObjectId("5ed04d01e9e43cee79734b95"), // new
    ObjectId(inventoryId)
    branchId: new ObjectId("5ed049a8f9a892a5fd9b4d9e"), // new ObjectId(branchId)
  },

Based on the data you store in DB either you need to update match with string.

So below Aggregation will work for you..

[
 {
  "$match": {
     "companyId": "5ed0491bf9a892a5fd9b4d9b",
     "inventoryId": "5ed04d01e9e43cee79734b95",
     "branchId": "5ed049a8f9a892a5fd9b4d9e"
  }
  },
 {
  "$lookup": {
     "from": "products",
     "localField": "productId",
     "foreignField": "_id",
     "as": "inventory_docs"
  }
  },
 {
  "$project": {
     "data": "$inventory_docs"
  }
 },
{
  "$unwind": "$data"
}

]

This works you can test in Compass Aggregator tab


来源: stackexchange

问:
ExpandableListAdapter vs BaseExpandableListAdapter
What is the difference between ExpandableListAdapter and BaseExpandableListAdapter beside the difference one is being interface and other one is abstract method?

Please give examples for each one about on which it should be used.

答:
ExpandableListAdapter:

ExpandableListAdapter is an Adapter that links a ExpandableListView
  with the underlying data. The implementation of this interface will
  provide the data for the children and also initiate the views for the
  children and groups.  For customization of list we need to implement
  ExpandableListAdapter in our custom adapter.

BaseExpandableListAdapter:

BaseExpandableListAdapter is a base class for the expandable list
  adapter used to provide data and Views from some data to
  ExpandableListView. For Creating a custom ExpandableListView we need
  to create a custom class and then extends BaseExpandableListAdapter
  class in that class.

Reference - this has examples also and hope this helps

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
Html tab active
I use this example code in https://www.w3schools.com/howto/howto_js_tabs.asp, i Just want that if the user click button Paris even the user refresh the page, the tab will still be in Paris

```<code><div class="tab">
  <button class="tablinks" onclick="openCity(event, 'London')" id="defaultOpen">Enrollment</button>
  <button class="tablinks" onclick="openCity(event, 'Paris')" id="secondOpen" >Student</button>
  <button class="tablinks" onclick="openCity(event, 'Tokyo')" id="thirdOpen">Parents</button>
</div>

<div id="London" class="tabcontent">
  <h3>London</h3>
  <p>London is the capital city of England.</p>
</div>

<div id="Paris" class="tabcontent">
  <h3>Paris</h3>
  <p>Paris is the capital of France.</p>
</div>

<div id="Tokyo" class="tabcontent">
  <h3>Tokyo</h3>
  <p>Tokyo is the capital of Japan.</p>
</div>

<script>
function openCity(evt, cityName) {
  var i, tabcontent, tablinks;
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }
  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }
  document.getElementById(cityName).style.display = "block";
  evt.currentTarget.className += " active";
}
//is this right?
first = document.getElementById("defaultOpen");
second = document.getElementById("secondOpen");
third = document.getElementById("thirdOpen");
if (second == ('active')){
    document.getElementById("secondOpen").click();
}else if(third == ('active')){
    document.getElementById("thirdOpen").click();
}else{
document.getElementById("defaultOpen").click();
}
</script>
</code>```

this is the example of html, I just want that if the user click the paris, even the user refresh the page the paris will active

function openCity(evt, cityName) {
  var i, tabcontent, tablinks;
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }
  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }
  document.getElementById(cityName).style.display = "block";
  evt.currentTarget.className += " active";
}

// is this right?
first = document.getElementById("defaultOpen");
second = document.getElementById("secondOpen");
third = document.getElementById("thirdOpen");
if (second == ('active')){
document.getElementById("secondOpen").click();
}else if(third == ('active')){
    document.getElementById("thirdOpen").click();
}else{
document.getElementById("defaultOpen").click();
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {font-family: Arial;}

/* Style the tab */
.tab {
  overflow: hidden;
  border: 1px solid #ccc;
  background-color: #f1f1f1;
}

/* Style the buttons inside the tab */
.tab button {
  background-color: inherit;
  float: left;
  border: none;
  outline: none;
  cursor: pointer;
  padding: 14px 16px;
  transition: 0.3s;
  font-size: 17px;
}

/* Change background color of buttons on hover */
.tab button:hover {
  background-color: #ddd;
}

/* Create an active/current tablink class */
.tab button.active {
  background-color: #ccc;
}

/* Style the tab content */
.tabcontent {
  display: none;
  padding: 6px 12px;
  border: 1px solid #ccc;
  border-top: none;
}</code>```

  <button class="tablinks" onclick="openCity(event, 'London')" id="defaultOpen">London</button>
  <button class="tablinks" onclick="openCity(event, 'Paris')">Paris</button>
  <button class="tablinks" onclick="openCity(event, 'Tokyo')">Tokyo</button>

London

London is the capital city of England.

Paris

Paris is the capital of France.

Tokyo

Tokyo is the capital of Japan.

```

答:
My idea is:
1. You must save id of tab in Local Storage of the broswer (every you click in another tab, you need to set it in this variable)
2. Every user load again this page, having function get this variable to enable tab. </p>

Title: Html tab active

Body:
I use this example code in https://www.w3schools.com/howto/howto_js_tabs.asp, i Just want that if the user click button Paris even the user refresh the page, the tab will still be in Paris

  <button class="tablinks" onclick="openCity(event, 'London')" id="defaultOpen">Enrollment</button>
  <button class="tablinks" onclick="openCity(event, 'Paris')" id="secondOpen" >Student</button>
  <button class="tablinks" onclick="openCity(event, 'Tokyo')" id="thirdOpen">Parents</button>

London

London is the capital city of England.

Paris

Paris is the capital of France.

Tokyo

Tokyo is the capital of Japan.

this is the example of html, I just want that if the user click the paris, even the user refresh the page the paris will active

function openCity(evt, cityName) {
  var i, tabcontent, tablinks;
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }
  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }
  document.getElementById(cityName).style.display = "block";
  evt.currentTarget.className += " active";
}

// is this right?
first = document.getElementById("defaultOpen");
second = document.getElementById("secondOpen");
third = document.getElementById("thirdOpen");
if (second == ('active')){
document.getElementById("secondOpen").click();
}else if(third == ('active')){
    document.getElementById("thirdOpen").click();
}else{
document.getElementById("defaultOpen").click();
}

body {font-family: Arial;}

/* Style the tab */
.tab {
  overflow: hidden;
  border: 1px solid #ccc;
  background-color: #f1f1f1;
}

/* Style the buttons inside the tab */
.tab button {
  background-color: inherit;
  float: left;
  border: none;
  outline: none;
  cursor: pointer;
  padding: 14px 16px;
  transition: 0.3s;
  font-size: 17px;
}

/* Change background color of buttons on hover */
.tab button:hover {
  background-color: #ddd;
}

/* Create an active/current tablink class */
.tab button.active {
  background-color: #ccc;
}

/* Style the tab content */
.tabcontent {
  display: none;
  padding: 6px 12px;
  border: 1px solid #ccc;
  border-top: none;
}

  <button class="tablinks" onclick="openCity(event, 'London')" id="defaultOpen">London</button>
  <button class="tablinks" onclick="openCity(event, 'Paris')">Paris</button>
  <button class="tablinks" onclick="openCity(event, 'Tokyo')">Tokyo</button>

London

London is the capital city of England.

Paris

Paris is the capital of France.

Tokyo

Tokyo is the capital of Japan.


问:
How to convert Timestamp to DateTime from firebase with flutter
I have Timestamp item in firebase. I get the item from dart code timestamp type.
It shows like 'Timestamp(seconds=1590903768, nanoseconds=26999000)' as it is.

I would like to show on my Application only Date like '2020-06-01' or '06-01'.

Please give me advice.

答:
Timestamp class has a toDate function that converts it to a DateTime object. See this for more information. Any formatting you want to do in converting it to a string can be done more easily now with intl package formatters.

Example:

```<code>Timestamp stamp = Timestamp.now();
DateTime date = stamp.toDate();
</code>```

Body:
Timestamp class has a toDate function that converts it to a DateTime object. See this for more information. Any formatting you want to do in converting it to a string can be done more easily now with intl package formatters.

Example:

Timestamp stamp = Timestamp.now();
DateTime date = stamp.toDate();


答:
To maintain state across page loads, you have to have some kind of persistent memory...  Websites do this by setting session cookies...

Ref the tutorial at w3schools: https://www.w3schools.com/js/js_cookies.asp

In your case, you need to set a value pair to store the selected tab... when the user selects it, you need to modify the value of the cookie and on page load you need to fetch the value of the cookie..

Title: Html tab active


问:
How do I build a dict from key-value pair list?
I am using boto3 to get the EC2 instance tags which has the form

[{u'Value': 'swarm manager 0', u'Key': 'Name'}, {u'Value': 'manager', u'Key': 'Role'}]
```

<p>I want to convert that to a dict like this</p>

<pre class="lang-py prettyprint-override"><code>{'Name': 'swarm manager 0', 'Role': 'manager'}
</code>```

Here's my code

tags = [{u'Value': 'swarm manager 0', u'Key': 'Name'}, {u'Value': 'manager', u'Key': 'Role'}]
tag_dict = dict()
for tag in tags:
  tag_dict[tag['Key']]=tag['Value']
print(tag_dict)
```

and https://repl.it/@trajano/GargantuanStickyNasm

Seems a bit wordy, I am thinking there should be a one or two line python thing to do that conversion.

答:
Dict comprehensions are a thing:</p>

```<code>tag_dict = {tag['Key']: tag['Value'] for tag in tags}
</code>```

Body:
I am using boto3 to get the EC2 instance tags which has the form

[{u'Value': 'swarm manager 0', u'Key': 'Name'}, {u'Value': 'manager', u'Key': 'Role'}]

I want to convert that to a dict like this

{'Name': 'swarm manager 0', 'Role': 'manager'}

Here's my code

tags = [{u'Value': 'swarm manager 0', u'Key': 'Name'}, {u'Value': 'manager', u'Key': 'Role'}]
tag_dict = dict()
for tag in tags:
  tag_dict[tag['Key']]=tag['Value']
print(tag_dict)

and https://repl.it/@trajano/GargantuanStickyNasm

Seems a bit wordy, I am thinking there should be a one or two line python thing to do that conversion.

Body:
Dict comprehensions are a thing:

tag_dict = {tag['Key']: tag['Value'] for tag in tags}


问:
Error "Couldn't reach API" when I try to log in
I install Directus CMS via git clone successful. In the database 15 tables were created. In /config folder my projectkey.php file were created too.
After installation I want to login with my credentials and get the error "Couldn't reach API".

```<code>In PHP Error log -> no entry
In Directus log -> no entry
</code>```

REST calls:

```<code>authenticate/ -> Code 200; Response: data/user
projectkey/ -> Code 200; Response: data/api
ping/ -> Code 200; Response: Pong
</code>```

In a working instance I have seen that in API Call projectkey/ are more properties. For example data/server is missing in my instance.

Does anyone have any idea what this could be?

答:
I had the same error and found the solution in the project's corresponding issue:

Check that you're using HTTPS on webservers and local... that is a new requirement added in 8.7.2 due to a cookie policy change by Chrome et al. If it STILL is an issue, please open a new ticket with exact/specific information. Thanks!

Also, just as a reminder, this is a VERY generic error and could shown for several different root causes. More specific error handling/codes is something we're adding in v9.

Enabling SSL fixed it for me.

Body:
I install Directus CMS via git clone successful. In the database 15 tables were created. In /config folder my projectkey.php file were created too.
After installation I want to login with my credentials and get the error "Couldn't reach API".

In PHP Error log -> no entry
In Directus log -> no entry

REST calls:

authenticate/ -> Code 200; Response: data/user
projectkey/ -> Code 200; Response: data/api
ping/ -> Code 200; Response: Pong

In a working instance I have seen that in API Call projectkey/ are more properties. For example data/server is missing in my instance.

Does anyone have any idea what this could be?


问:
How to pull company insights using LinkedIn API
Is there a way to pull company insights info using one of the LinkedIn API's? I have a premium account and have created an app on the LinkedIn developers platform. I can’t seem to find a way to fetch company data such as number of employees (by category and total), headcount growth (3m, 6m, 1yr, 2yr), job openings by category, etc.

Any idea on how to resolve this issue?

答:
you can do this easily using organizationPageStatistics and brandPageStatistics APIs
just request the following link

GET https://api.linkedin.com/v2/organizationPageStatistics?q=organization&organization={organization URN}

if you need to read more you can read the documentation
Documentation


问:
How to convert string number into numeric number with given string, Java
I would like to extract number from a given string sentence and convert into a numeric value.
For example,

Input: "Hello I have two passwords with dk12kdkd and 2kdkae5."

output: "Hello I have two passwords with dkONETWOkdkd and TWOkdkaeFIVE."

I am confused with how to extract numbers and change value to get back original one.

Thanks for the help!

```<code>public class Main {

  public static Pattern pattern = Pattern.compile("\\d+");

  public static void main(String[] args) {
    String testString = "Hello I have two passwords with dk12kdkd and 25kdkae5.";
    String singleDigits[] = {"ZERO", "ONE", "TWO", "THREE",
            "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE"};

    Matcher matcher = pattern.matcher(str);

    while (matcher.find()) {
        str = str.replace(matcher.group(),
                String.valueOf(Integer.parseInt(matcher.group()));
    } // confused from here.
}
</code>```

答:
```<code>public class Main {

    public static void main(String[] args) {
        String testString = "Hello I have two passwords with dk12kdkd and 25kdkae5.";
        String singleDigits[] = { "ZERO", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE" };
        HashMap<String, String> dict = new HashMap<>();
        for (int i = 0; i < singleDigits.length; i++) {
            dict.put(String.valueOf(i), singleDigits[i]);
        }
        for (char s : testString.toCharArray()) {
            if (dict.containsKey(String.valueOf(s)))
                testString = testString.replace(String.valueOf(s), dict.get(String.valueOf(s)));
        }
        System.out.println(testString);
    }
}
</code>```

Output

Hello I have two passwords with dkONETWOkdkd and TWOFIVEkdkaeFIVE.

Body:
I would like to extract number from a given string sentence and convert into a numeric value.
For example,

Input: "Hello I have two passwords with dk12kdkd and 2kdkae5."

output: "Hello I have two passwords with dkONETWOkdkd and TWOkdkaeFIVE."

I am confused with how to extract numbers and change value to get back original one.

Thanks for the help!

public class Main {

  public static Pattern pattern = Pattern.compile("\\d+");

  public static void main(String[] args) {
    String testString = "Hello I have two passwords with dk12kdkd and 25kdkae5.";
    String singleDigits[] = {"ZERO", "ONE", "TWO", "THREE",
            "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE"};

    Matcher matcher = pattern.matcher(str);

    while (matcher.find()) {
        str = str.replace(matcher.group(),
                String.valueOf(Integer.parseInt(matcher.group()));
    } // confused from here.
}

Body:
public class Main {

    public static void main(String[] args) {
        String testString = "Hello I have two passwords with dk12kdkd and 25kdkae5.";
        String singleDigits[] = { "ZERO", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE" };
        HashMap<String, String> dict = new HashMap<>();
        for (int i = 0; i < singleDigits.length; i++) {
            dict.put(String.valueOf(i), singleDigits[i]);
        }
        for (char s : testString.toCharArray()) {
            if (dict.containsKey(String.valueOf(s)))
                testString = testString.replace(String.valueOf(s), dict.get(String.valueOf(s)));
        }
        System.out.println(testString);
    }
}

Output

Hello I have two passwords with dkONETWOkdkd and TWOFIVEkdkaeFIVE.


问:
Not understanding Android Mediaplayer Synchronization
Recently I've been learning Android from Beginning Android games when I came across this code:

```<code>    MediaPlayer mediaPlayer;
    boolean isPrepared = false;
    public AndroidMusic(AssetFileDescriptor assetDescriptor) {
        mediaPlayer = new MediaPlayer();
        try {
            mediaPlayer.setDataSource(assetDescriptor.getFileDescriptor(),
                    assetDescriptor.getStartOffset(),
                    assetDescriptor.getLength());
            mediaPlayer.prepare();
            isPrepared = true;
            mediaPlayer.setOnCompletionListener(this);
        } catch (Exception e) {
            throw new RuntimeException("Couldn't load music");
        }
    }
    public void dispose() {
        if (mediaPlayer.isPlaying())
            mediaPlayer.stop();
        mediaPlayer.release();
    }
    public boolean isLooping() {
        return mediaPlayer.isLooping();
    }

    public boolean isPlaying() {
        return mediaPlayer.isPlaying();
    }

    public boolean isStopped() {
        return !isPrepared;
    }
    public void pause() {
        if (mediaPlayer.isPlaying())
            mediaPlayer.pause();
    }
    public void play() {
        if (mediaPlayer.isPlaying())
            return;
        try {
            synchronized (this) {
                if (!isPrepared)
                    mediaPlayer.prepare();
                mediaPlayer.start();
            }
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void setLooping(boolean isLooping) {
        mediaPlayer.setLooping(isLooping);
    }

    public void setVolume(float volume) {
        mediaPlayer.setVolume(volume, volume);
    }
    public void stop() {
        mediaPlayer.stop();
        synchronized (this) {
            isPrepared = false;
        }
    }
    public void onCompletion(MediaPlayer player) {
        synchronized (this) {
            isPrepared = false;
        }
    }
}
</code>```

I'm very confused as to why we need to synchronize things here. Will there be more than one thing accessing these synchronized blocks? The book states, " The method
OnCompletionListener.onCompletion() might be called in a separate thread, and since
we set the isPrepared member in this method, we have to make sure that it is safe from
concurrent modifications. "
CallBacks are new to me, but I assume that when the MediaPlayer finishes, onCompletion is called. How will this onCompletion be called from a separate thread? Won't it be called on the thread that's executing this class? Eg, Thread 1 is executing play() and eventually the file ends, so onCompletion() is called on Thread 1. How will this be called on Thread 2? The synchronization on onCompletion() confuses me most, as with the other ones I somewhat understand that a different thread(UI thread) might edit the value of isPrepared in stop(), so that needs to be synchronized. The book's explanation further confuses me. How does this synchronization work, and what purpose does it serve?

答:
In simple term, the synchronized access can be thought of sequential access. For eg: If there is a variable which can be modified by two different methods running in two different threads without synchronized access, there might be high chance that :

The change made by one Thread in that variable is not seen by the other Thread.

The other Thread starts the modification taking the half-changed values of the variable done by the first Thread.

Such part of the method are called Critical Region of the method and basically, with synchronized keyword, if a Thread accesses that variable, it applies lock on that variable before going to Critical Region so, other Thread cannot access it simultaneously. It helps to prevent weird modifications.

Now, talking about MediaPlayer, there are two versions of preparing the MediaPlayer object: prepare(suitable for local files) and prepareAsync()(suitable for remote files). The Async version returns immediately without blocking the UI thread and does its background processing in a new Thread. When prepareAsync() is completed in that new Thread, a callback is returned to the Main Thread. We can set a listener for such callback via setOnPreparedListener(OnPreparedListener listener). Other than that, normally, the MediaPlayer instance is created and managed in the MainThread(UI Thread) so, there in no need of synchronized keyword. But, as @Ariel Perez said, it's always your choice and you can have two separate threads: one for setting data source on the player object and another for starting the playback.

Body:
Recently I've been learning Android from Beginning Android games when I came across this code:

    MediaPlayer mediaPlayer;
    boolean isPrepared = false;
    public AndroidMusic(AssetFileDescriptor assetDescriptor) {
        mediaPlayer = new MediaPlayer();
        try {
            mediaPlayer.setDataSource(assetDescriptor.getFileDescriptor(),
                    assetDescriptor.getStartOffset(),
                    assetDescriptor.getLength());
            mediaPlayer.prepare();
            isPrepared = true;
            mediaPlayer.setOnCompletionListener(this);
        } catch (Exception e) {
            throw new RuntimeException("Couldn't load music");
        }
    }
    public void dispose() {
        if (mediaPlayer.isPlaying())
            mediaPlayer.stop();
        mediaPlayer.release();
    }
    public boolean isLooping() {
        return mediaPlayer.isLooping();
    }

    public boolean isPlaying() {
        return mediaPlayer.isPlaying();
    }

    public boolean isStopped() {
        return !isPrepared;
    }
    public void pause() {
        if (mediaPlayer.isPlaying())
            mediaPlayer.pause();
    }
    public void play() {
        if (mediaPlayer.isPlaying())
            return;
        try {
            synchronized (this) {
                if (!isPrepared)
                    mediaPlayer.prepare();
                mediaPlayer.start();
            }
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void setLooping(boolean isLooping) {
        mediaPlayer.setLooping(isLooping);
    }

    public void setVolume(float volume) {
        mediaPlayer.setVolume(volume, volume);
    }
    public void stop() {
        mediaPlayer.stop();
        synchronized (this) {
            isPrepared = false;
        }
    }
    public void onCompletion(MediaPlayer player) {
        synchronized (this) {
            isPrepared = false;
        }
    }
}

I'm very confused as to why we need to synchronize things here. Will there be more than one thing accessing these synchronized blocks? The book states, " The method
OnCompletionListener.onCompletion() might be called in a separate thread, and since
we set the isPrepared member in this method, we have to make sure that it is safe from
concurrent modifications. "
CallBacks are new to me, but I assume that when the MediaPlayer finishes, onCompletion is called. How will this onCompletion be called from a separate thread? Won't it be called on the thread that's executing this class? Eg, Thread 1 is executing play() and eventually the file ends, so onCompletion() is called on Thread 1. How will this be called on Thread 2? The synchronization on onCompletion() confuses me most, as with the other ones I somewhat understand that a different thread(UI thread) might edit the value of isPrepared in stop(), so that needs to be synchronized. The book's explanation further confuses me. How does this synchronization work, and what purpose does it serve?


问:
"-eq" operator always rings true for string comparisons between double brackets
For example:

```<code>A="T"
if [[ $A -eq "M" ]]; then
    echo "$A"
fi
</code>```

this will always echo T.

答:
-eq is meant for integer comparisons. And between [[ and ]], if operands around -eq (and -ne, -lt, etc.) are not integers but valid variable names, bash assumes these are variables and tries to dereference them (recursively). In that same context, an unset/empty variable's value is considered to be zero; so, you're basically comparing 0 to 0 there. See this transcript:

```<code>$ unset A M T
$ A="T"
$ if [[ $A -eq "M" ]]; then
>     echo "$A"
> fi
T
$
$ T="1"
$ A="T"
$ if [[ $A -eq "M" ]]; then
>     echo "$A"
> fi
$
</code>```

When T is assigned a number other than zero, it doesn't ring true anymore.

For further information, refer to:

Conditional Constructs § [[..]],

Shell Arithmetic.

Body:
For example:

A="T"
if [[ $A -eq "M" ]]; then
    echo "$A"
fi

this will always echo T.

Body:
-eq is meant for integer comparisons. And between [[ and ]], if operands around -eq (and -ne, -lt, etc.) are not integers but valid variable names, bash assumes these are variables and tries to dereference them (recursively). In that same context, an unset/empty variable's value is considered to be zero; so, you're basically comparing 0 to 0 there. See this transcript:

$ unset A M T
$ A="T"
$ if [[ $A -eq "M" ]]; then
>     echo "$A"
> fi
T
$
$ T="1"
$ A="T"
$ if [[ $A -eq "M" ]]; then
>     echo "$A"
> fi
$

When T is assigned a number other than zero, it doesn't ring true anymore.

For further information, refer to:

Conditional Constructs § [[..]],

Shell Arithmetic.


问:
Joining items in list with specific conditions Python
I am currently dealing with 100,000+ lines in a csv file with a structure like this:

```<code>//f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11
1,false,false,0,"0","0","0","<color=asdf>d1, d2, d3<br>d4"d5", d6.</color>, 0, 1, false"
2,true,false,0,"0","0","0","<color=qwer>d1, "d2, d3"<br> d3<br>d4"d5" d6.</color>, 0, 1, false"
...
</code>```

The top line has the structure of the file.

I have been trying to loop through the code each line, assign the corresponding value to each value (f1, f2...), and modify the texts using generators, but I am faced with the problem of splitting the code correctly.

If I simply split the lines using line.split(','), I will have:

['1', 'false', 'false', '0', '"0"', '"0"', '"0"', '"<color=asdf>d1', 'd2', 'd3
d4"d5"', 'd6.</color>, 0, 1, false"' with list length of 14

when I want:

['1', 'false', 'false', '0', '"0"', '"0"', '"0"', '"<color=asdf>d1, d2, d3
d4"d5", d6.</color>, 0, 1, false"' with list length of 11, so that the length of the list corresponds to the description line f1, f2... f11

It seems to me that commas within quotation marks ("") is causing this problem with .split(',') method by splitting everything.

I have been trying to find a way I could merge the 'correct' items together, but to no avail. Can anyone help me with this issue?

答:
For this answer I will be assuming that the color tag corresponds to the column f8, and that the following integers and boolean correspond to the columns f9, f10, and f11 respectively. This does not match the placement of the quotation mark at the end of the boolean column, but it is the most obvious way I can think of to ensure that the example rows are indeed 14 and 11 columns long, respectively. If this was not the intended structure of the csv file, please clarify and I would be happy to edit the answer accordingly.

Instead of combining the strings yourself, you can use the parser from the standard library module csv to parse the file for you. For instance, a file named datafile.csv could be displayed with:

import csv
with open("datafile.csv", 'r') as csvfile:
    csvreader = csv.reader(csvfile)
    for row in csvreader:
        print(row)
```

<p>That said, testing this on the rows you provided gives</p>

```['1', 'false', 'false', '0', '0', '0', '0', '<color=asdf>d1, d2, d3
d4d5"', ' d6.</color>', ' 0', ' 1', ' false"']
['2', 'true', 'false', '0', '0', '0', '0', '<color=qwer>d1, d2', ' d3"
 d3
d4"d5" d6.</color>', ' 0', ' 1', ' false"']
```

<p>which does not match the result you were looking for. This is because the color tag, which I assume was meant to be one column, contains unescaped quotation marks. Thus, the parser can't tell where the column is supposed to end. If you control the code producing the csv file it would probably be best to change it there, but if you can't change the generation of the data file you will have to solve this problem too.</p>

<p>If the column f8 always corresponds to a color tag, you could use this knowledge to split it off and then split the remainder of the line on the commas. For this we can use the regular expressions module. Instead of using <code>line.split(',')</code> we split the line in 3 portions: the part before the color tag, the tag itself, and the part after. This can be done with</p>

<pre class="lang-py prettyprint-override"><code>result = re.match(r"(.*),(\"\<color.*\</color\>),(.*)", line)
</code>```

result will contain a Match object, which will have 'capture groups' corresponding to the places surrounded by parentheses. we can extract these capture groups from the object by calling the method Match.group, with as an argument the position of the group. The first and third group can safely be split on commas, since we have already observed that they only contain simple data without commas inside, and the second group containing the color tag does not need to be split since it contains a single column. Thus, we obtain the final list with

result.group(1).split(',') + [result.group(2)] + result.group(3).split(',')
```

<p>if the placement of the quotation mark is as in the provided data but you would like to change it to be close to the color tag this can be done by removing the quote from the end of the third capture group and adding it to the second. Thus, the expression above becomes</p>

<pre class="lang-py prettyprint-override"><code>result.group(1).split(',') + [result.group(2) + '"'] + result.group(3)[:-1].split(',')
</code>```

where [:-1] is used to slice off the last character. Combining the initial regex match statement with the expression above and using them to replace line.split(',') should yield the desired result. With this method, displaying all rows of the csv file would work like so:

import re
with open("testing.csv", 'r') as csvfile:
    for line in csvfile.readlines():
        print(line)
        result = re.match(r"(.*),(\"\<color.*\</color\>),(.*)", line)
        print(result.group(1).split(',') + [result.group(2) + '"'] + result.group(3)[:-1].split(','))
```

I hope that this has helped you solve your problem. If not, please feel free to ask.

Body:
I am currently dealing with 100,000+ lines in a csv file with a structure like this:

//f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11
1,false,false,0,"0","0","0","<color=asdf>d1, d2, d3
d4"d5", d6.</color>, 0, 1, false"
2,true,false,0,"0","0","0","<color=qwer>d1, "d2, d3"
 d3
d4"d5" d6.</color>, 0, 1, false"
...

The top line has the structure of the file.

I have been trying to loop through the code each line, assign the corresponding value to each value (f1, f2...), and modify the texts using generators, but I am faced with the problem of splitting the code correctly.

If I simply split the lines using line.split(','), I will have:

['1', 'false', 'false', '0', '"0"', '"0"', '"0"', '"<color=asdf>d1', 'd2', 'd3
d4"d5"', 'd6.</color>, 0, 1, false"' with list length of 14

when I want:

['1', 'false', 'false', '0', '"0"', '"0"', '"0"', '"<color=asdf>d1, d2, d3
d4"d5", d6.</color>, 0, 1, false"' with list length of 11, so that the length of the list corresponds to the description line f1, f2... f11

It seems to me that commas within quotation marks ("") is causing this problem with .split(',') method by splitting everything.

I have been trying to find a way I could merge the 'correct' items together, but to no avail. Can anyone help me with this issue?

Body:
For this answer I will be assuming that the color tag corresponds to the column f8, and that the following integers and boolean correspond to the columns f9, f10, and f11 respectively. This does not match the placement of the quotation mark at the end of the boolean column, but it is the most obvious way I can think of to ensure that the example rows are indeed 14 and 11 columns long, respectively. If this was not the intended structure of the csv file, please clarify and I would be happy to edit the answer accordingly.

Instead of combining the strings yourself, you can use the parser from the standard library module csv to parse the file for you. For instance, a file named datafile.csv could be displayed with:

import csv
with open("datafile.csv", 'r') as csvfile:
    csvreader = csv.reader(csvfile)
    for row in csvreader:
        print(row)

That said, testing this on the rows you provided gives

['1', 'false', 'false', '0', '0', '0', '0', '<color=asdf>d1, d2, d3<br>d4d5"', ' d6.</color>', ' 0', ' 1', ' false"']
['2', 'true', 'false', '0', '0', '0', '0', '<color=qwer>d1, d2', ' d3"<br> d3<br>d4"d5" d6.</color>', ' 0', ' 1', ' false"']

which does not match the result you were looking for. This is because the color tag, which I assume was meant to be one column, contains unescaped quotation marks. Thus, the parser can't tell where the column is supposed to end. If you control the code producing the csv file it would probably be best to change it there, but if you can't change the generation of the data file you will have to solve this problem too.

If the column f8 always corresponds to a color tag, you could use this knowledge to split it off and then split the remainder of the line on the commas. For this we can use the regular expressions module. Instead of using line.split(',') we split the line in 3 portions: the part before the color tag, the tag itself, and the part after. This can be done with

result = re.match(r"(.*),(\"\<color.*\</color\>),(.*)", line)

result will contain a Match object, which will have 'capture groups' corresponding to the places surrounded by parentheses. we can extract these capture groups from the object by calling the method Match.group, with as an argument the position of the group. The first and third group can safely be split on commas, since we have already observed that they only contain simple data without commas inside, and the second group containing the color tag does not need to be split since it contains a single column. Thus, we obtain the final list with

result.group(1).split(',') + [result.group(2)] + result.group(3).split(',')

if the placement of the quotation mark is as in the provided data but you would like to change it to be close to the color tag this can be done by removing the quote from the end of the third capture group and adding it to the second. Thus, the expression above becomes

result.group(1).split(',') + [result.group(2) + '"'] + result.group(3)[:-1].split(',')

where [:-1] is used to slice off the last character. Combining the initial regex match statement with the expression above and using them to replace line.split(',') should yield the desired result. With this method, displaying all rows of the csv file would work like so:

import re
with open("testing.csv", 'r') as csvfile:
    for line in csvfile.readlines():
        print(line)
        result = re.match(r"(.*),(\"\<color.*\</color\>),(.*)", line)
        print(result.group(1).split(',') + [result.group(2) + '"'] + result.group(3)[:-1].split(','))

I hope that this has helped you solve your problem. If not, please feel free to ask.


问:
Code does not reflect on UI after button set visible
i have an update panel with Content Template in my aspx as follows.

```<code><asp:UpdatePanel ID="UpdatePanel1" runat="server">
</asp:UpdatePanel>
</code>```

Within the content template, I have 5 dropdowns with AutoPostBack="true"and a button which is a PostBackTrigger.

The dropdowns are sequential dependent on previous selection for binding.
After the 3rd dropdown has its index changed, the button will be set visible and the 4th dropdown bind.

However with the button set visible and 4th dropdown index changed (which should bind the next (5th dropdown), the user interface stopped working.

I did a step through, the code runs well however the 5th dropdown just doesn't get bind by the data. And the user interface works if the button just stay hidden, but i need it to be visible.

Any idea why?

答: Managed to resolve it, by adding the 5th drop down as a PostBackTrigger.</p>

Body:
i have an update panel with Content Template in my aspx as follows.

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
</asp:UpdatePanel>

Within the content template, I have 5 dropdowns with AutoPostBack="true"and a button which is a PostBackTrigger.

The dropdowns are sequential dependent on previous selection for binding.
After the 3rd dropdown has its index changed, the button will be set visible and the 4th dropdown bind.

However with the button set visible and 4th dropdown index changed (which should bind the next (5th dropdown), the user interface stopped working.

I did a step through, the code runs well however the 5th dropdown just doesn't get bind by the data. And the user interface works if the button just stay hidden, but i need it to be visible.

Any idea why?


问:
In a watchOS how to create a link to settings - general - wake screen
In a watchOS how to create a link, URL schema or deep-link to settings - general  - wake screen?

in my watchOS app, I run a test to find out if the wake screen is set to 15 seconds or 70 seconds. If the test fails when the app becomes inactive after 15 seconds i want to redirect the user to the wake screen settings in the setting app so they can change the setting to 70 seconds.

thanks

答: In general you should be able to just setup background modes and establish a WKExtendedRuntimeSession to facilitate whatever you're trying to accomplish.</p>


问:
Convert razor view into pdf file
I have an application where admin can user order details in an email after its completed in email  and copy is saved in server. I have a view "~/order/MyOrder.cshtml?id=Q5/KCbPNhXKx7EWffTprWg==" which user can see after logging in to check their status. But when order is fulfilled admin send an email to user with order status and in a pdf file with all the information. I am trying to create a pdf file from the view mention above and planning to attache that file to an email. What the best way to do this. I saw few solution's here but i am not able to figure out bet way to handle this.  I am using ITexSharp for this.

```<code>        string html = RenderViewToString(ControllerContext,
    "/order/MyOrder.cshtml?Auth=Q5/KCbPNhXKx7EWffTprWg==",
    model, true);

        using (MemoryStream stream = new System.IO.MemoryStream())
        {
            StringReader sr = new StringReader(html);
            Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 100f, 0f);
            PdfWriter writer = PdfWriter.GetInstance(pdfDoc, stream);
            pdfDoc.Open();
            XMLWorkerHelper.GetInstance().ParseXHtml(writer, pdfDoc, sr);
            pdfDoc.Close();
            var Filename =  File(stream.ToArray(), "application/pdf", "Grid.pdf");
            zip.AddFile(Filename.FileDownloadName, "Pdf");
        }
</code>```

and RanderViewToString function:

```<code>static string RenderViewToString(ControllerContext context,
                            string viewPath,
                            object model = null,
                            bool partial = false)
{
    // first find the ViewEngine for this view
    ViewEngineResult viewEngineResult = null;
    if (partial)
        viewEngineResult = ViewEngines.Engines.FindPartialView(context, viewPath);
    else
        viewEngineResult = ViewEngines.Engines.FindView(context, viewPath, null);

    if (viewEngineResult == null)
        throw new FileNotFoundException("View cannot be found.");

    // get the view and attach the model to view data
    var view = viewEngineResult.View;
    context.Controller.ViewData.Model = model;

    string result = null;

    using (var sw = new StringWriter())
    {
        var ctx = new ViewContext(context, view,
                                    context.Controller.ViewData,
                                    context.Controller.TempData,
                                    sw);
        view.Render(ctx, sw);
        result = sw.ToString();
    }

    return result;
}
</code>```

I am getting "Value cannot be null.Parameter name: view'" error. I am not sure how to pass the view with parameters to convert it to string.

答:
I recommend you try Rotativa

https://github.com/webgio/Rotativa

```<code>  public ActionResult PrintIndex()
  {
          return new ActionAsPdf("Index", new { name = "Giorgio" }) { FileName = "Test.pdf" };
   }
</code>```

Title: Convert razor view into pdf file

Body:
I have an application where admin can user order details in an email after its completed in email  and copy is saved in server. I have a view "~/order/MyOrder.cshtml?id=Q5/KCbPNhXKx7EWffTprWg==" which user can see after logging in to check their status. But when order is fulfilled admin send an email to user with order status and in a pdf file with all the information. I am trying to create a pdf file from the view mention above and planning to attache that file to an email. What the best way to do this. I saw few solution's here but i am not able to figure out bet way to handle this.  I am using ITexSharp for this.

        string html = RenderViewToString(ControllerContext,
    "/order/MyOrder.cshtml?Auth=Q5/KCbPNhXKx7EWffTprWg==",
    model, true);

        using (MemoryStream stream = new System.IO.MemoryStream())
        {
            StringReader sr = new StringReader(html);
            Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 100f, 0f);
            PdfWriter writer = PdfWriter.GetInstance(pdfDoc, stream);
            pdfDoc.Open();
            XMLWorkerHelper.GetInstance().ParseXHtml(writer, pdfDoc, sr);
            pdfDoc.Close();
            var Filename =  File(stream.ToArray(), "application/pdf", "Grid.pdf");
            zip.AddFile(Filename.FileDownloadName, "Pdf");
        }

and RanderViewToString function:

static string RenderViewToString(ControllerContext context,
                            string viewPath,
                            object model = null,
                            bool partial = false)
{
    // first find the ViewEngine for this view
    ViewEngineResult viewEngineResult = null;
    if (partial)
        viewEngineResult = ViewEngines.Engines.FindPartialView(context, viewPath);
    else
        viewEngineResult = ViewEngines.Engines.FindView(context, viewPath, null);

    if (viewEngineResult == null)
        throw new FileNotFoundException("View cannot be found.");

    // get the view and attach the model to view data
    var view = viewEngineResult.View;
    context.Controller.ViewData.Model = model;

    string result = null;

    using (var sw = new StringWriter())
    {
        var ctx = new ViewContext(context, view,
                                    context.Controller.ViewData,
                                    context.Controller.TempData,
                                    sw);
        view.Render(ctx, sw);
        result = sw.ToString();
    }

    return result;
}

I am getting "Value cannot be null.Parameter name: view'" error. I am not sure how to pass the view with parameters to convert it to string.

Body:
I recommend you try Rotativa

https://github.com/webgio/Rotativa

  public ActionResult PrintIndex()
  {
          return new ActionAsPdf("Index", new { name = "Giorgio" }) { FileName = "Test.pdf" };
   }


问:
why doesnt everyone use frameworks
well lot of forums and even this site is full of questions where people don't use any framework(whetever language they use) and they are stuck on code for common tasks like logins,database accesses,etc while frameworks provide code that works correctly for these routine tasks. Then why do people still go without frameworks? i want to know this because i am trying to build something of substantial scale so i was deciding if i really need a framework or a homegrown solution would be better? a homegrown solution can be a great learning experience but is there something more to it? </p>

答:
People go without framework for several different reasons, in my opinion the choice of developing in-house functionality is not always a bad choice.

Frameworks often don't implement all functionalities required but often add extra functionalities that will never be used making the code base unecessary "bloated".

Implementing a framework often requires a steep learning curve and often it is easier to implement certain functionality in house.

However often a framework can be the best choice but developers jump into coding without doing enough research beforehand.

Title: why doesnt everyone use frameworks


问:
How can I set the permission like r_emailaddress and r_fullprofile in linked in application
I want LinkedIn profile fields of the user like firstname,lastname,phone & emailId. But with r_liteprofile it is not giving me the phone_no and email. So, how can I set the  r_basicprofile or r_fullprofile. So, i get it directly in my site with new updated version of API.

As I am using the below API endpoint

curl_setopt($ch, CURLOPT_URL,"https://api.linkedin.com/v2/me/~?oauth2_access_token=".json_decode($server_output)->access_token."&format=json");

答:
just add it as param to your request

https://api.linkedin.com/v2/me/~?oauth2_access_token=XXXXXXXXXX&scope=r_liteprofile%20r_emailaddress%20w_member_social

you can find more info in the documentation

https://learn.microsoft.com/en-us/linkedin/shared/authentication/authorization-code-flow?context=linkedin/marketing/context


问:
How do I fix my variables on my code as it does not appear
So when I ran this code below, I noticed that my variables myName and myAge didn't function at all. An I getting something wrong here?

This program says hello and asks for my name.

print ('Hello world!')

print ('What is your name?') # ask for their name

myName = input('Michael')

print ('It is good to meet you, ' + myName)

print('The length of your name is:')

print (len(myName))

print ('What is your age?') # ask for their age

myAge = input('16')

print('You will be " + str(int(myAge) + 1) + ' in a year.')
```

答:
If you type the input() means that you expect an input from the user i guess you want something like

```<code>print ('Hello world!')

print ('What is your name?') # ask for their name

myName = 'Michael'

print ('It is good to meet you, ' + myName)

print('The length of your name is:')

print (myName)

print ('What is your age?') # ask for their age

myAge = '16'

print("You will be " + str(int(myAge) + 1) + " in a year.")
</code>```

look that the variables are assigned as

```<code>variable = "value"
</code>```

Body:
If you type the input() means that you expect an input from the user i guess you want something like

print ('Hello world!')

print ('What is your name?') # ask for their name

myName = 'Michael'

print ('It is good to meet you, ' + myName)

print('The length of your name is:')

print (myName)

print ('What is your age?') # ask for their age

myAge = '16'

print("You will be " + str(int(myAge) + 1) + " in a year.")

look that the variables are assigned as

variable = "value"


问:
How to label values beyond threshold in plot type 'h'
Using the mtcars dataset and plot function with argument  type= 'h', I would like to label observations with  mtcars$wt >4 only, but did not manage. I tried:

```<code> plot(mtcars$wt,type = 'h',ylim = c(0,6))
    abline(h=4)
    text(mtcars$wt,row.names(mtcars[mtcars$wt >4,]),pos =3,col='blue',cex=0.6))
</code>```

But all bars get labelled:

I also tried the solution provided at Add labels to plot for specific values in R , but did not manage to make it work.

It would be great if the labels could also be on top of the bar with a 45 degree angle to avoid overlapping

答:
There may be several ways to fix this. I tried this:

```<code>plot(mtcars$wt,type = 'h',ylim = c(0,6))
abline(h=4)
labs <- ifelse(mtcars$wt >4, row.names(mtcars), "")
text(mtcars$wt,labs,pos =3,col='blue',cex=0.6)
</code>```

For the second part of your question, I would have to use ggplot and ggrepel, it may not be exactly what you after, but it can avoid overlapping:

```<code>library(ggrepel)
library(tidyverse)
mtcars$x = 1:length(mtcars$wt)
mtcars %>%
  ggplot(aes(x= x, xend =x, y = 0, yend= wt))+
  geom_segment() +
  geom_text_repel(aes(x= x, y = wt, label = labs),
                      angle = 45
)
</code>```

Body:
Using the mtcars dataset and plot function with argument  type= 'h', I would like to label observations with  mtcars$wt >4 only, but did not manage. I tried:

 plot(mtcars$wt,type = 'h',ylim = c(0,6))
    abline(h=4)
    text(mtcars$wt,row.names(mtcars[mtcars$wt >4,]),pos =3,col='blue',cex=0.6))

But all bars get labelled:

I also tried the solution provided at Add labels to plot for specific values in R , but did not manage to make it work.

It would be great if the labels could also be on top of the bar with a 45 degree angle to avoid overlapping

Body:
There may be several ways to fix this. I tried this:

plot(mtcars$wt,type = 'h',ylim = c(0,6))
abline(h=4)
labs <- ifelse(mtcars$wt >4, row.names(mtcars), "")
text(mtcars$wt,labs,pos =3,col='blue',cex=0.6)

For the second part of your question, I would have to use ggplot and ggrepel, it may not be exactly what you after, but it can avoid overlapping:

library(ggrepel)
library(tidyverse)
mtcars$x = 1:length(mtcars$wt)
mtcars %>%
  ggplot(aes(x= x, xend =x, y = 0, yend= wt))+
  geom_segment() +
  geom_text_repel(aes(x= x, y = wt, label = labs),
                      angle = 45
)


问:
Convert SQL query to SQL functions?
I'm working on SQL functions

I create a query and query successful run but I wan to convert them SQL functions

I'm returning two parameter in query days and years

I want to convert SQL query to SQL function see below image

sql query

```<code>    Declare @dateofbirth datetime
    Declare @currentdatetime datetime
    Declare @years varchar(4)
    Declare @days varchar(4)
    set @dateofbirth = '2020-01-25 '
    set @currentdatetime  = getdate()
    select @years = datediff(year,@dateofbirth,@currentdatetime)
    select @days = datediff(DAY,@dateofbirth,@currentdatetime)
    select @years   + ' years,'
    select @days   + ' days,'
</code>```

can I use Multi-statement table-valued functions (MSTVF) because my query return multiple parameter days and years?

3 function available in ssms

table-valued functions

new inline table valued function

scalar multi statement table valued function

scalar-valued functions

aggregate functions

I am not sure which function should be use?

I want to convert SQL query to SQL function?

答:
You can use a Scalar Function to achieve this.

But you have to use the CONCAT function at the output, there is no other option to return multi select query in function.

You can also use Table Valued function to get the output in Table format.

```<code>CREATE Function dbo.Years_Days(@dateofbirth datetime, @currentdatetime datetime)
RETURNS VARCHAR(MAX) AS
BEGIN
    Declare @years varchar(4)
    Declare @days varchar(4)

    set @currentdatetime  = ISNULL(@currentdatetime,getdate());
    select @years = datediff(year,@dateofbirth,@currentdatetime)
    select @days = datediff(DAY,@dateofbirth,@currentdatetime)

    RETURN  @years   + ' years,' + @days   + ' days,'
END

SELECT dbo.Years_Days(  '2020-01-25 ', NULL);
</code>```

The type of function depends on the Return Data Type

If the returned datatype is a Table then it needs to be a Table-Valued Function.

Further, click below link:

Functions In SQL Server

Title: Convert SQL query to SQL functions?

Body:
I'm working on SQL functions

I create a query and query successful run but I wan to convert them SQL functions

I'm returning two parameter in query days and years

I want to convert SQL query to SQL function see below image

sql query

    Declare @dateofbirth datetime
    Declare @currentdatetime datetime
    Declare @years varchar(4)
    Declare @days varchar(4)
    set @dateofbirth = '2020-01-25 '
    set @currentdatetime  = getdate()
    select @years = datediff(year,@dateofbirth,@currentdatetime)
    select @days = datediff(DAY,@dateofbirth,@currentdatetime)
    select @years   + ' years,'
    select @days   + ' days,'

can I use Multi-statement table-valued functions (MSTVF) because my query return multiple parameter days and years?

3 function available in ssms

table-valued functions

new inline table valued function

scalar multi statement table valued function

scalar-valued functions

aggregate functions

I am not sure which function should be use?

I want to convert SQL query to SQL function?

Body:
You can use a Scalar Function to achieve this.

But you have to use the CONCAT function at the output, there is no other option to return multi select query in function.

You can also use Table Valued function to get the output in Table format.

CREATE Function dbo.Years_Days(@dateofbirth datetime, @currentdatetime datetime)
RETURNS VARCHAR(MAX) AS
BEGIN
    Declare @years varchar(4)
    Declare @days varchar(4)

    set @currentdatetime  = ISNULL(@currentdatetime,getdate());
    select @years = datediff(year,@dateofbirth,@currentdatetime)
    select @days = datediff(DAY,@dateofbirth,@currentdatetime)

    RETURN  @years   + ' years,' + @days   + ' days,'
END

SELECT dbo.Years_Days(  '2020-01-25 ', NULL);

The type of function depends on the Return Data Type

If the returned datatype is a Table then it needs to be a Table-Valued Function.

Further, click below link:

Functions In SQL Server


问:
JSON - make subchild as a condition for IF Statement
I have a JSON from an API with this content:

```<code>"items":[
     {
      id: *id here*,
      variant: {
             variant_name: *name here*,
             variant_id: *id here*,
             stores: {
                   0:
                      store_id: *STOREID1*,
                      available_for_sale: true
                   1:
                      store_id: *STOREID2*,
                      available_for_sale: true
     }
   }
}]
</code>```

I want to select the items with the same store ID and Available for sale status. I have tried this but this isn't working:

```<code>if(items.variant.stores.store_id === "STOREID1" && items.variant.stores.available_for_sale === 'true'){
</code>```

But it says

```<code>Uncaught TypeError: Cannot read property 'store_id' of undefined
</code>```

EDIT:

I tried this:

```<code> if(items.variants.stores.store_id["******"] && items.variants.stores.available_for_sale['true']){
</code>```

But it still gives the same error.

EDIT 2:

Edited the Question for more clarification.

答:
items is an array, you need to iterate over it and filter the items you want

const items = [{
    id: 1,
    variant: {
      variant_name: '*name here*',
      variant_id: 111,
      stores: { store_id: 1111, available_for_sale: true }
    }
  },
  {
    id: 2,
    variant: {
      variant_name: 'name here',
      variant_id: 222,
      stores: { store_id: 2222, available_for_sale: true }
    }
  }
];

const result = items.filter(({variant: v}) => (
    v.stores.store_id === 2222 && v.stores.available_for_sale
));

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I have a JSON from an API with this content:

"items":[
     {
      id: *id here*,
      variant: {
             variant_name: *name here*,
             variant_id: *id here*,
             stores: {
                   0:
                      store_id: *STOREID1*,
                      available_for_sale: true
                   1:
                      store_id: *STOREID2*,
                      available_for_sale: true
     }
   }
}]

I want to select the items with the same store ID and Available for sale status. I have tried this but this isn't working:

if(items.variant.stores.store_id === "STOREID1" && items.variant.stores.available_for_sale === 'true'){

But it says

Uncaught TypeError: Cannot read property 'store_id' of undefined

EDIT:

I tried this:

 if(items.variants.stores.store_id["******"] && items.variants.stores.available_for_sale['true']){

But it still gives the same error.

EDIT 2:

Edited the Question for more clarification.

Body:
items is an array, you need to iterate over it and filter the items you want

const items = [{
    id: 1,
    variant: {
      variant_name: '*name here*',
      variant_id: 111,
      stores: { store_id: 1111, available_for_sale: true }
    }
  },
  {
    id: 2,
    variant: {
      variant_name: 'name here',
      variant_id: 222,
      stores: { store_id: 2222, available_for_sale: true }
    }
  }
];

const result = items.filter(({variant: v}) => (
    v.stores.store_id === 2222 && v.stores.available_for_sale
));

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Apache 2.2 mod_rewrite help
I am trying to get Apache 2.2 mod_rewrite to get clean urls.
I have links such as

```<code><ul>
<li><a href="index.php?view=pageName">Page Name</a></li>
<li><a href="index.php?view=pageName2">Page Name2</a></li>
<li><a href="index.php?view=pageName3">Page Name3</a></li>
</ul>
</code>```

and url comes out to be

```<code>http://example.com/user/index.php?view=pageName
</code>```

I would like to clean the url in the address bar it to this

```<code>http://example.com/user/pageName
</code>```

Edit: This is what's in my httpd.conf if it's any use.

```<code><Directory "C:/Apache2.2/htdocs/user">
    Options Indexes FollowSymLinks
    AllowOverride all
    order allow,deny
    Allow from all
</Directory>
</code>```

Using phpinfo() I have verified that mod_rewrite is loaded and I have this in my .htaccess (user file, Not root .htaccess) and not virtual user on apache

```<code>RewriteEngine on
RewriteBase /user/ #Edited rewrite base added in, but not helping much.
RewriteOptions Inherit
RewriteRule ^/user/([a-zA-Z])/?$ index.php?view=$1  [NC,L]
</code>```

Edit: the rest of my .htaccess

```<code>#Ensure browser reads Header
Header unset ETag
FileETag None
Header unset Last-Modified

#Set caching expires
Header set Expires On
ExpiresDefault "access plus 30 days"

#gzip
<FilesMatch "\.(js|css)$">
SetOutputFilter DEFLATE
</FilesMatch>
</code>```

does not work the same on all menu links which are identical in html structure, and not working properly. IE: It sends me to http://example.com/user/?view=pageName, but is loading the root HTML file content.

If I change this line

```<code>RewriteRule ^/user/([a-zA-Z])/?$ index.php?view=$1  [NC,L]
</code>```

to

```<code>RewriteRule ^index\.php$ http://www.google.com  [NC,L]
</code>```

I get sent to google as expected. So obviously I must be doing something wrong with the matching and replacing, but what am I doing wrong?
Thanks in advance.

Edit:
access.log and error.log are error free.

答:
```<code>RewriteRule ^/user/([a-zA-Z]+)?$ index.php?view=$1  [NC,L]
</code>```

you are missing the + so you are not matching words, just a single char

Title: Apache 2.2 mod_rewrite help

Body:
I am trying to get Apache 2.2 mod_rewrite to get clean urls.
I have links such as

Page Name

Page Name2

Page Name3

and url comes out to be

http://example.com/user/index.php?view=pageName

I would like to clean the url in the address bar it to this

http://example.com/user/pageName

Edit: This is what's in my httpd.conf if it's any use.

<Directory "C:/Apache2.2/htdocs/user">
    Options Indexes FollowSymLinks
    AllowOverride all
    order allow,deny
    Allow from all
</Directory>

Using phpinfo() I have verified that mod_rewrite is loaded and I have this in my .htaccess (user file, Not root .htaccess) and not virtual user on apache

RewriteEngine on
RewriteBase /user/ #Edited rewrite base added in, but not helping much.
RewriteOptions Inherit
RewriteRule ^/user/([a-zA-Z])/?$ index.php?view=$1  [NC,L]

Edit: the rest of my .htaccess

#Ensure browser reads Header
Header unset ETag
FileETag None
Header unset Last-Modified

#Set caching expires
Header set Expires On
ExpiresDefault "access plus 30 days"

#gzip
<FilesMatch "\.(js|css)$">
SetOutputFilter DEFLATE
</FilesMatch>

does not work the same on all menu links which are identical in html structure, and not working properly. IE: It sends me to http://example.com/user/?view=pageName, but is loading the root HTML file content.

If I change this line

RewriteRule ^/user/([a-zA-Z])/?$ index.php?view=$1  [NC,L]

to

RewriteRule ^index\.php$ http://www.google.com  [NC,L]

I get sent to google as expected. So obviously I must be doing something wrong with the matching and replacing, but what am I doing wrong?
Thanks in advance.

Edit:
access.log and error.log are error free.

Body:
RewriteRule ^/user/([a-zA-Z]+)?$ index.php?view=$1  [NC,L]

you are missing the + so you are not matching words, just a single char


问:
Change opacity of images that weren't selected, but keep select image visible
basically when you select an image all the others change to 0.4 opacity, but the image I click on stays the same..

Here's my current code

This is just one of the images for an example, they are all the same, only difference is instead of the tennis wrap class it would be track-wrap (different wrap names for each wrap, other classes inside the wraps are the same).
``

```<code>   <div class="tennis-wrap map-markers-wrap">
        <div id="draggable1" class="location-imgs tennis ui-widget-content">
            <img src="<?php echo get_template_directory_uri();?>/lib/img/tennis.png" alt="">

            <div class="location-list">
                <h3>Sports and Wellbeing</h3>
                <ol>
                    <li><span>Willow Urban Retreat & Day Spa</span></li>
                    <li><span>Harold Holt Swim Centre</span></li>
                    <li><span>St James Valley Cricket Club</span></li>
                    <li><span>East Malvern Junior Football Club</span></li>
                    <li><span>East Malvern Tennis Club</span></li>
                    <li><span>Cabrini Health</span></li>
                </ol>
            </div>

            <div class="cross">
                <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 14 14">
                <path id="ic_add_24px" d="M19,13H13v6H11V13H5V11h6V5h2v6h6Z" transform="translate(-5 -5)"/>
                </svg>
            </div>
        </div>
        <div class="location-pins">
            <div class="tennis-one location-number orange">1</div>
            <div class="tennis-two location-number orange">2</div>
            <div class="tennis-three location-number orange">3</div>
            <div class="tennis-four location-number orange">4</div>
            <div class="tennis-five location-number orange">5</div>
            <div class="tennis-six location-number orange">6</div>
        </div>
    </div>
</code>```

``

```<code> $(".map-markers-wrap").each(function () {
    var _this = $(this);

    _this.find(".cross").click(function () {
      var _this_cross = $(this);
      $(".location-list").hide();
      $(".location-pins").hide();

      $('img').not(this).stop().animate({
        opacity: 0.4
      }, 300);
      $(this).stop().animate({
        opacity: 1.0
      }, 300);

      setTimeout(function () {
        _this_cross.closest('.map-markers-wrap').find(".location-pins").show();
        _this_cross.closest('.map-markers-wrap').find(".location-list").show();

      }, 100)
    });
  });
</code>```

From my understanding this code should check if image is not in this div, then it will change the opacity to 0.4, which it does, but it also changes the image that I click to 0.4 when it should be 1.0
Maybe I have a miss-understanding of the this keyword?
Any help would be appreciated.

答:
$(this) is one of the divs, e.g.
, so your call to $(this).stop().animate(...) will select the
, not the desired  inside the clicked
.

Try:

```<code>// Select all <img> tags not in this div:
$('.map-markers-wrap').not(_this).find('img').stop().animate({
  opacity: 0.4
}, 300);

// Select <img> tag in this div:
$(_this).find('img').stop().animate({
  opacity: 1.0
}, 300);

</code>```

Where _this is each .map-markers-wrap div.

Body:
basically when you select an image all the others change to 0.4 opacity, but the image I click on stays the same..

Here's my current code

This is just one of the images for an example, they are all the same, only difference is instead of the tennis wrap class it would be track-wrap (different wrap names for each wrap, other classes inside the wraps are the same).
``

            <img src="<?php echo get_template_directory_uri();?>/lib/img/tennis.png" alt="">

Sports and Wellbeing

Willow Urban Retreat & Day Spa

Harold Holt Swim Centre

St James Valley Cricket Club

East Malvern Junior Football Club

East Malvern Tennis Club

Cabrini Health

                <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 14 14">
                <path id="ic_add_24px" d="M19,13H13v6H11V13H5V11h6V5h2v6h6Z" transform="translate(-5 -5)"/>
                </svg>

1

2

3

4

5

6

``

 $(".map-markers-wrap").each(function () {
    var _this = $(this);

    _this.find(".cross").click(function () {
      var _this_cross = $(this);
      $(".location-list").hide();
      $(".location-pins").hide();

      $('img').not(this).stop().animate({
        opacity: 0.4
      }, 300);
      $(this).stop().animate({
        opacity: 1.0
      }, 300);

      setTimeout(function () {
        _this_cross.closest('.map-markers-wrap').find(".location-pins").show();
        _this_cross.closest('.map-markers-wrap').find(".location-list").show();

      }, 100)
    });
  });

From my understanding this code should check if image is not in this div, then it will change the opacity to 0.4, which it does, but it also changes the image that I click to 0.4 when it should be 1.0
Maybe I have a miss-understanding of the this keyword?
Any help would be appreciated.

Body:
$(this) is one of the divs, e.g. <div class="tennis-wrap map-markers-wrap">, so your call to $(this).stop().animate(...) will select the <div>, not the desired <img> inside the clicked <div>.

Try:

// Select all <img> tags not in this div:
$('.map-markers-wrap').not(_this).find('img').stop().animate({
  opacity: 0.4
}, 300);

// Select <img> tag in this div:
$(_this).find('img').stop().animate({
  opacity: 1.0
}, 300);

Where _this is each .map-markers-wrap div.


问:
dispose method not getting called
In my main page, I have two tabs, named tab 1 and tab 2.  When switch to tab 2, it has an icon on upper right corner.When icon is clicked, it will open page C.

I notice when I switch from tab 1 to tab2, it will call dispose in tab 1.
When I switch from tab 2 to tab 1, tab2 dispose will be called.

However when I click the icon in tab 2 to navigate to page c, dispose in tab 2 is not getting called.
How can I make dispose method called when I click the icon to navigate to page C?

答: You're using the Navigator.pushNamed method to push page C on top. This creates a stack of pages, so the tabbed pages are not disposed, they're still there just not visibly. Use Navigator.pushReplacementNamed instead to replace the current page and take the old one off the stack and dispose it.

Title: dispose method not getting called


问:
SQL query to find duplicate records and discount from COUNT with condition AND
I am using below SQL query to count the records. I would like to discount the duplicate testID after I got the count.

example:

```<code>select count (*) from PRODUCT MP
   join PRODUCT_UOM pu on pu.PRODUCT_KEY = mp.PRODUCT_KEY
   join UOM u on u.UOM_ID = pu.UOM_ID
   join PRODUCT_BARCODE pb on pb.PRODUCT_UOM_KEY = pu.PRODUCT_UOM_KEY
</code>```

the excel data when query select * looks like below:

i want to discount the records which TESTID AND NAME is duplicate.

total count = 6 - 2 = 4

I understand there is distinct query which i can used, but i am not sure how to make condition with 2 columns, when duplicate then do not count them.

答:
If it is just the count that is important to you could simply use GROUP BY on TESTID, NAME and then count the number of rows in that query like so :

```<code>SELECT count(t.*) from (

   select * from PRODUCT MP
   join PRODUCT_UNIT pu on pu.PRODUCT_KEY = mp.PRODUCT_KEY
   join UNIT u on u.UNIT_ID = pu.UNIT_ID
   join PRODUCT_BAR pb on pb.PRODUCT_UNIT_KEY = pu.PRODUCT_UNIT_KEY

   GROUP BY TESTID, NAME
) t;
</code>```

Body:
I am using below SQL query to count the records. I would like to discount the duplicate testID after I got the count.

example:

select count (*) from PRODUCT MP
   join PRODUCT_UOM pu on pu.PRODUCT_KEY = mp.PRODUCT_KEY
   join UOM u on u.UOM_ID = pu.UOM_ID
   join PRODUCT_BARCODE pb on pb.PRODUCT_UOM_KEY = pu.PRODUCT_UOM_KEY

the excel data when query select * looks like below:

i want to discount the records which TESTID AND NAME is duplicate.

total count = 6 - 2 = 4

I understand there is distinct query which i can used, but i am not sure how to make condition with 2 columns, when duplicate then do not count them.

Body:
If it is just the count that is important to you could simply use GROUP BY on TESTID, NAME and then count the number of rows in that query like so :

SELECT count(t.*) from (

   select * from PRODUCT MP
   join PRODUCT_UNIT pu on pu.PRODUCT_KEY = mp.PRODUCT_KEY
   join UNIT u on u.UNIT_ID = pu.UNIT_ID
   join PRODUCT_BAR pb on pb.PRODUCT_UNIT_KEY = pu.PRODUCT_UNIT_KEY

   GROUP BY TESTID, NAME
) t;


问:
How do I build a dict from key-value pair list?
I am using boto3 to get the EC2 instance tags which has the form

[{u'Value': 'swarm manager 0', u'Key': 'Name'}, {u'Value': 'manager', u'Key': 'Role'}]
```

<p>I want to convert that to a dict like this</p>

<pre class="lang-py prettyprint-override"><code>{'Name': 'swarm manager 0', 'Role': 'manager'}
</code>```

Here's my code

tags = [{u'Value': 'swarm manager 0', u'Key': 'Name'}, {u'Value': 'manager', u'Key': 'Role'}]
tag_dict = dict()
for tag in tags:
  tag_dict[tag['Key']]=tag['Value']
print(tag_dict)
```

and https://repl.it/@trajano/GargantuanStickyNasm

Seems a bit wordy, I am thinking there should be a one or two line python thing to do that conversion.

答:
Similar to comprehensions, dict accepts an iterable of pairs, which can be a comprehension as well:

```<code>from operator import itemgetter
dict(map(itemgetter('Key', 'Value'), tags))
</code>```

OR

```<code>dict(itemgetter('Key', 'Value')(x) for x in tags)
</code>```

In python 3.6+, dicts are ordered, so if your dictionary always has 'Value' before 'Key', you can do

```<code>dict(x.values()[::-1] for x in tags)
</code>```

Of course this latter method is not worth using in a production environment as it is too unreliable.

Body:
I am using boto3 to get the EC2 instance tags which has the form

[{u'Value': 'swarm manager 0', u'Key': 'Name'}, {u'Value': 'manager', u'Key': 'Role'}]

I want to convert that to a dict like this

{'Name': 'swarm manager 0', 'Role': 'manager'}

Here's my code

tags = [{u'Value': 'swarm manager 0', u'Key': 'Name'}, {u'Value': 'manager', u'Key': 'Role'}]
tag_dict = dict()
for tag in tags:
  tag_dict[tag['Key']]=tag['Value']
print(tag_dict)

and https://repl.it/@trajano/GargantuanStickyNasm

Seems a bit wordy, I am thinking there should be a one or two line python thing to do that conversion.

Body:
Similar to comprehensions, dict accepts an iterable of pairs, which can be a comprehension as well:

from operator import itemgetter
dict(map(itemgetter('Key', 'Value'), tags))

OR

dict(itemgetter('Key', 'Value')(x) for x in tags)

In python 3.6+, dicts are ordered, so if your dictionary always has 'Value' before 'Key', you can do

dict(x.values()[::-1] for x in tags)

Of course this latter method is not worth using in a production environment as it is too unreliable.


问:
Reject / Bad Records Table in BigQuery
I am looking for a reject link type of solution in a dedup scenario. For example in the following code:

```<code>MERGE
temp.many_random t
USING
( SELECT DISTINCT * FROM temp.many_random WHERE d=CURRENT_DATE() )
ON FALSE
WHEN NOT MATCHED
BY SOURCE AND d=CURRENT_DATE() THEN DELETE
WHEN NOT MATCHED BY TARGET THEN INSERT ROW
</code>```

Can I replace THEN DELETE with something like INSERT INTO TABLE (different than the compare tables) so that we can capture these rejects and troubleshoot for pipeline analysis?

答:
If I understand the problem, you want the result of a MERGE query to write to 2 different tables.

Since MERGE can't do that, I'll suggest to write 2 queries:

One that does whatever the primary query is doing.

A second almost identical one, but that writes the wrong records to a different table.

Title: Reject / Bad Records Table in BigQuery

Body:
I am looking for a reject link type of solution in a dedup scenario. For example in the following code:

MERGE
temp.many_random t
USING
( SELECT DISTINCT * FROM temp.many_random WHERE d=CURRENT_DATE() )
ON FALSE
WHEN NOT MATCHED
BY SOURCE AND d=CURRENT_DATE() THEN DELETE
WHEN NOT MATCHED BY TARGET THEN INSERT ROW

Can I replace THEN DELETE with something like INSERT INTO TABLE (different than the compare tables) so that we can capture these rejects and troubleshoot for pipeline analysis?


问:
SwiftUI: How to convert an Image to jpeg data?
In UIImage, there is the jpegData() method which turns the image into an NSData object of jpeg data.

What would the analogue be for the Image class?

答:
The SwiftUI Image is analog of UIImageView, not UIImage. So if you need to operate with image model, you have to store it explicitly as UIImage and operate with it, providing into view as in below example:

```<code>struct ContentView: View {
   let imageModel: UIImage        // << model

   var body: some View {
      Image(uiImage: imageModel)  // << view
        .onTapGesture {
            // work with model

            let data = self.imageModel.jpegData(compressionQuality: 0.5)
            // .. do something with data
        }
   }
}
</code>```

Body:
The SwiftUI Image is analog of UIImageView, not UIImage. So if you need to operate with image model, you have to store it explicitly as UIImage and operate with it, providing into view as in below example:

struct ContentView: View {
   let imageModel: UIImage        // << model

   var body: some View {
      Image(uiImage: imageModel)  // << view
        .onTapGesture {
            // work with model

            let data = self.imageModel.jpegData(compressionQuality: 0.5)
            // .. do something with data
        }
   }
}


问:
how to use Mockito or PowerMock to set a private field in a class
I have a following code

```<code>@RunWith(PowerMockRunner.class)
public NeedToTestClass () {
     private String needToSetValueField;

     ......

     public String needToTestMethod() {
           return "the field value is " + this.needToSetValueField;
     }
}
</code>```

Is there anyway I can set(or mock) the needToSetValueField when I try to test the method? Please help. Thanks.

答: @Taschi should get the credit. A simple reflection can be used to set a private variable in the class. What can be done in unit test is to mock the class NeedToTestClass using spy annotation and then use reflection to set the private variable needToSetValueField. Thanks.</p>

Body:
I have a following code

@RunWith(PowerMockRunner.class)
public NeedToTestClass () {
     private String needToSetValueField;

     ......

     public String needToTestMethod() {
           return "the field value is " + this.needToSetValueField;
     }
}

Is there anyway I can set(or mock) the needToSetValueField when I try to test the method? Please help. Thanks.


问:
socket send part down but receive part Up , possible?
I am wondering if it is possible to have a socket with send which doens't work (because buffer of peer is full maybe) while receive part still working ?

EDIT:

In case of a peer which doesn't perform a half close connection, and which it is too long to process its receive buffer (so its receive buffer is full), can I have an error only on my send part ?

答:
You can have a socket through which you can't send if you close your side of the connection (half-closed connection). You can do that with shutdown(2). When you half-close the connection in this way you're saying "I don't have anything else to say, but if you send be stuff I'll look at it".

The buffer on the other side should make no difference. When you send something, you don't put it in the buffer of your peer. You put it in a buffer in your kernel, and the kernel later sends it to the peer.

There is little chance of having a working connection and filling your buffers to the point you get errors from send(2).


问:
How to write C# LINQ code to select based on condition
I am looking to convert a list of one type to another type by a conversion method but only selectively (if the conversion result is null or not). It is shown in code below.

```<code>private List<B> GetBList(List<A> aList)
{
    List<B> bList = new List<B>();
    foreach (A a in aList)
    {
        B b = GetB(a);
        if (b != null)
        {
            bList.Add(b);
        }
    }
    return bList;
}

private B GetB(A a)
{
    if (a != null)
    {
        return new B();
    }
    return null;
}
</code>```

Is there a way to write it using LINQ something like below. The issue with below function is that it will always move the data even if the conversion result is null. Result has to be array (array of B) and the input has to be list (list of A).

```<code>private B[] GetBList(List<A> aList)
{
    return aList.Select(GetB)?.ToArray() ?? Array.Empty<A>();
}
</code>```

Please suggest. Thanks in advance!

答:
You can select with Select(x => GetB(x)) which will return converted object. Then you should filter it with Where(x => x != null). Then convert it to array.

Note that I have used ? after aList as aList?.Select so it will handle case when aList object is null.

```<code>private B[] GetBList(List<A> aList)
{
    return aList?.Select(x => GetB(x)).Where(x => x != null).ToArray() ?? Array.Empty<B>();
}
</code>```

Edit You can use Select(GetB) instead if Select(x => GetB(x)) also.

```<code>private B[] GetBList(List<A> aList)
{
    return aList?.Select(GetB).Where(x => x != null).ToArray() ?? Array.Empty<B>();
}
</code>```

Body:
I am looking to convert a list of one type to another type by a conversion method but only selectively (if the conversion result is null or not). It is shown in code below.

private List GetBList(List aList)
{
    List bList = new List();
    foreach (A a in aList)
    {
        B b = GetB(a);
        if (b != null)
        {
            bList.Add(b);
        }
    }
    return bList;
}

private B GetB(A a)
{
    if (a != null)
    {
        return new B();
    }
    return null;
}

Is there a way to write it using LINQ something like below. The issue with below function is that it will always move the data even if the conversion result is null. Result has to be array (array of B) and the input has to be list (list of A).

private B[] GetBList(List aList)
{
    return aList.Select(GetB)?.ToArray() ?? Array.Empty();
}

Please suggest. Thanks in advance!

Body:
You can select with Select(x => GetB(x)) which will return converted object. Then you should filter it with Where(x => x != null). Then convert it to array.

Note that I have used ? after aList as aList?.Select so it will handle case when aList object is null.

private B[] GetBList(List<A> aList)
{
    return aList?.Select(x => GetB(x)).Where(x => x != null).ToArray() ?? Array.Empty<B>();
}

Edit You can use Select(GetB) instead if Select(x => GetB(x)) also.

private B[] GetBList(List<A> aList)
{
    return aList?.Select(GetB).Where(x => x != null).ToArray() ?? Array.Empty<B>();
}


问:
How to fix a Classifier from the Confusion Matrix?
I understand what a confusion matrix is. However, I found very little information on how to fix the classification thereafter.

The class 'Manufacturing' is clearly the main source of confusion but how do I fix it?

答: You may try different classifiers based on your use-case. I think it may because of fewer samples for class  "manufacturing". If u want to fix classifier than u will have to balance the sample distribution first. If u want to try a new classifier than classifiers is available. U can evaluate one by one. Else it depends on the nature of data as well eg. how many features per documents, which features u select, etc. I hope this explanation will help you.</p>


问:
How to deal with dates in global system
Let's say that I need to create 'chat-like' system. Of course I need to deal with dates somehow.
I read about it a lot and I have some knowledge but I really don't know how to use it.

I would like to store message date in UTC (postgres 12)

Each user should be able to select his time zone and this time zone should be saved into database (standard approach)

When message is retrieved from database I need to convert message date into valid local date based on user selected timezone.

This is really all I need to do and here problem starts:

In postgres date is stored with offset f.e 2020-05-01 00:00:00+02, but I want to store timezone in another table, not here

How can I store user timezone? I should use names like "EST5EDT" or use time offsets as integer?

Where can I find list of all timezones to present user? (Each global website f.e. facebook has list of timezones with offsets, where can I find list of all valid timezones?)

How can I select date with user appropriate timezone? f.e.

```<code>SELECT convert_to_user_date("Date", "timezonename??")
FROM "Messages"
</code>```

Is this correct way to achieve my goal?

答:
Use the data type timestamp with time zone. Don't be worried by the name — that data type really represents an absolute point of time and does not store time zone information.

The only thing you have to do is to set the timezone parameter correctly for the time zone of the client connection, then the value will be represented correctly in that time zone. PostgreSQL does all the work for you.

If you don't like the string representation (e.g., you are disturbed by the time zone offset displayed), use to_char to format the output the way you like:

```<code>CREATE TABLE dates (x timestamp with time zone NOT NULL);

SET timezone = 'Europe/Vienna';

INSERT INTO dates VALUES ('2020-06-01 03:00:00');

SET timezone = 'Asia/Kolkata';

SELECT to_char(x, 'YYYY-MM-DD HH24:MI:SS') FROM dates;

       to_char
---------------------
 2020-06-01 06:30:00
(1 row)
</code>```

Title: How to deal with dates in global system

Body:
Let's say that I need to create 'chat-like' system. Of course I need to deal with dates somehow.
I read about it a lot and I have some knowledge but I really don't know how to use it.

I would like to store message date in UTC (postgres 12)

Each user should be able to select his time zone and this time zone should be saved into database (standard approach)

When message is retrieved from database I need to convert message date into valid local date based on user selected timezone.

This is really all I need to do and here problem starts:

In postgres date is stored with offset f.e 2020-05-01 00:00:00+02, but I want to store timezone in another table, not here

How can I store user timezone? I should use names like "EST5EDT" or use time offsets as integer?

Where can I find list of all timezones to present user? (Each global website f.e. facebook has list of timezones with offsets, where can I find list of all valid timezones?)

How can I select date with user appropriate timezone? f.e.

SELECT convert_to_user_date("Date", "timezonename??")
FROM "Messages"

Is this correct way to achieve my goal?

Body:
Use the data type timestamp with time zone. Don't be worried by the name — that data type really represents an absolute point of time and does not store time zone information.

The only thing you have to do is to set the timezone parameter correctly for the time zone of the client connection, then the value will be represented correctly in that time zone. PostgreSQL does all the work for you.

If you don't like the string representation (e.g., you are disturbed by the time zone offset displayed), use to_char to format the output the way you like:

CREATE TABLE dates (x timestamp with time zone NOT NULL);

SET timezone = 'Europe/Vienna';

INSERT INTO dates VALUES ('2020-06-01 03:00:00');

SET timezone = 'Asia/Kolkata';

SELECT to_char(x, 'YYYY-MM-DD HH24:MI:SS') FROM dates;

       to_char
---------------------
 2020-06-01 06:30:00
(1 row)