问:
Working linq query produces the error "CA1505 : Microsoft.Maintainability"
I have a linq query that works just fine but when StyleCop is run on the the project the following error is produced: "CA1505 : Microsoft.Maintainability: Rewrite or refactor the type's methods to increase its maintainability index (MI)". I have tested removing part of the query and found that that fixes the error. The issue appears to be that the query is just too long, so I'm looking for a way to shorten it to eliminate the CA1505 error. The challenge here is that the data resides in 5 main tables, the sql equivalent to this is basically 5 union all statements. Any Suggestions?</p>

```<code>    public List<ExpiringItemModel> GetByDaysToExpire(int days)
    {
        var int1 = days - 30;
        var int2 = days - 16;
        var int3 = days - 0;

        var query = (
            from outlet in _modelContext.Outlets
            join outletcommunicationmethod in _modelContext.OutletCommunicationMethods on
                new { Id = outlet.Id }
                equals new { Id = outletcommunicationmethod.OutletId }
            join outletcarpermitagent in _modelContext.outletcarpermitagents on
                new { Id = outlet.Id } equals
                new { Id = outletcarpermitagent.OutletId }
            join outlettype in _modelContext.OutletTypes on
                new { OutletTypeId = outletcarpermitagent.OutletTypeId } equals
                new { OutletTypeId = outlettype.Id }
            where
                (outletcommunicationmethod.CommunicationMethodId == 1
                &&
                SqlFunctions.DateDiff("day", SqlFunctions.GetDate(),
                                      outletcarpermitagent.BondExpirationDate) > 0) &&

                (SqlFunctions.DateDiff("day", SqlFunctions.GetDate(),
                                        outletcarpermitagent.BondExpirationDate) == days ||
                (SqlFunctions.DateDiff("day", SqlFunctions.GetDate(),
                                        outletcarpermitagent.BondExpirationDate) == 30) ||
                (SqlFunctions.DateDiff("day", SqlFunctions.GetDate(),
                                        outletcarpermitagent.BondExpirationDate) == 14))

            select new ExpiringItemModel
            {
                Id = (Int32)outletcarpermitagent.Id,
                AgentType = outlettype.Value,
                Email = outletcommunicationmethod.Value,
                BondExpirationDate = (DateTime)outletcarpermitagent.BondExpirationDate
            }
            ).Concat
            (
                from outlet_1 in _modelContext.Outlets
                join outletcommunicationmethod_1 in _modelContext.OutletCommunicationMethods on
                    new { Id = outlet_1.Id } equals new { Id = outletcommunicationmethod_1.OutletId }
                join outlettruckpermitagent in _modelContext.outlettruckpermitagents on
                    new { Id = outlet_1.Id } equals new { Id = outlettruckpermitagent.OutletId }
                join outlettype_1 in _modelContext.OutletTypes on
                    new { OutletTypeId = outlettruckpermitagent.OutletTypeId } equals
                    new { OutletTypeId = outlettype_1.Id }
                where
                    (outletcommunicationmethod_1.CommunicationMethodId == 1
                    &&
                    SqlFunctions.DateDiff("day", SqlFunctions.GetDate(),
                                          outlettruckpermitagent.BondExpirationDate) > 0) &&

                    (SqlFunctions.DateDiff("day", SqlFunctions.GetDate(),
                                          outlettruckpermitagent.BondExpirationDate) == days ||
                    (SqlFunctions.DateDiff("day", SqlFunctions.GetDate(),
                                            outlettruckpermitagent.BondExpirationDate) == 30) ||
                    (SqlFunctions.DateDiff("day", SqlFunctions.GetDate(),
                                            outlettruckpermitagent.BondExpirationDate) == 14))

                select new ExpiringItemModel
                {
                    Id = (Int32)outlettruckpermitagent.Id,
                    AgentType = outlettype_1.Value,
                    Email = outletcommunicationmethod_1.Value,
                    BondExpirationDate = (DateTime)outlettruckpermitagent.BondExpirationDate
                }
            ).Concat
            (
                from outlet_2 in _modelContext.Outlets
                join outletcommunicationmethod_2 in _modelContext.OutletCommunicationMethods on
                    new { Id = outlet_2.Id } equals new { Id = outletcommunicationmethod_2.OutletId }
                join outletcyclepermitagent in _modelContext.outletcyclepermitagents on new { Id = outlet_2.Id } equals
                    new { Id = outletcyclepermitagent.OutletId }
                join outlettype_2 in _modelContext.OutletTypes on new { OutletTypeId = outletcyclepermitagent.OutletTypeId }
                    equals new { OutletTypeId = outlettype_2.Id }
                where
                    (outletcommunicationmethod_2.CommunicationMethodId == 1
                    &&
                    SqlFunctions.DateDiff("day", SqlFunctions.GetDate(),
                                          outletcyclepermitagent.BondExpirationDate) > 0) &&

                    (SqlFunctions.DateDiff("day", SqlFunctions.GetDate(),
                                          outletcyclepermitagent.BondExpirationDate) == days ||
                    (SqlFunctions.DateDiff("day", SqlFunctions.GetDate(),
                                            outletcyclepermitagent.BondExpirationDate) == 30) ||
                    (SqlFunctions.DateDiff("day", SqlFunctions.GetDate(),
                                            outletcyclepermitagent.BondExpirationDate) == 14))

                select new ExpiringItemModel
                {
                    Id = (Int32)outletcyclepermitagent.Id,
                    AgentType = outlettype_2.Value,
                    Email = outletcommunicationmethod_2.Value,
                    BondExpirationDate = (DateTime)outletcyclepermitagent.BondExpirationDate
                }
                ).Concat
                (
                from outlet_3 in _modelContext.Outlets
                join outletcommunicationmethod_3 in _modelContext.OutletCommunicationMethods on
                    new { Id = outlet_3.Id } equals new { Id = outletcommunicationmethod_3.OutletId }
                join outletscooteragent in _modelContext.outletscooteragentAgents on
                    new { Id = outlet_3.Id } equals
                    new { Id = outletscooteragent.OutletId }
                join outlettype_3 in _modelContext.OutletTypes on
                    new { OutletTypeId = outletscooteragent.OutletTypeId }
                    equals new { OutletTypeId = outlettype_3.Id }
                where
                    (outletcommunicationmethod_3.CommunicationMethodId == 1
                    &&
                    SqlFunctions.DateDiff("day", SqlFunctions.GetDate(),
                                          outletscooteragent.BondExpirationDate) > 0) &&

                    (SqlFunctions.DateDiff("day", SqlFunctions.GetDate(),
                                          outletscooteragent.BondExpirationDate) == days ||
                    (SqlFunctions.DateDiff("day", SqlFunctions.GetDate(),
                                            outletscooteragent.BondExpirationDate) == 30) ||
                    (SqlFunctions.DateDiff("day", SqlFunctions.GetDate(),
                                            outletscooteragent.BondExpirationDate) == 14))

                select new ExpiringItemModel
                {
                    Id = (Int32)outletscooteragent.Id,
                    AgentType = outlettype_3.Value,
                    Email = outletcommunicationmethod_3.Value,
                    BondExpirationDate = (DateTime)outletscooteragent.BondExpirationDate
                }
                ).Concat
                (
                from outlet_4 in _modelContext.Outlets
                join outletcommunicationmethod_4 in _modelContext.OutletCommunicationMethods on
                    new { Id = outlet_4.Id } equals new { Id = outletcommunicationmethod_4.OutletId }
                join outletoffroadagent in _modelContext.outletoffroadagentAgents on new { Id = outlet_4.Id } equals
                    new { Id = outletoffroadagent.OutletId }
                join outlettype_4 in _modelContext.OutletTypes on new { OutletTypeId = outletoffroadagent.OutletTypeId }
                    equals new { OutletTypeId = outlettype_4.Id }
                where
                    (outletcommunicationmethod_4.CommunicationMethodId == 1
                    &&
                    SqlFunctions.DateDiff("day", SqlFunctions.GetDate(),
                                          outletoffroadagent.BondExpirationDate) > 0) &&

                    (SqlFunctions.DateDiff("day", SqlFunctions.GetDate(),
                                             outletoffroadagent.BondExpirationDate) == days ||
                    (SqlFunctions.DateDiff("day", SqlFunctions.GetDate(),
                                            outletoffroadagent.BondExpirationDate) == 30) ||
                    (SqlFunctions.DateDiff("day", SqlFunctions.GetDate(),
                                            outletoffroadagent.BondExpirationDate) == 14))

                select new ExpiringItemModel
                {
                    Id = (Int32)outletoffroadagent.Id,
                    AgentType = outlettype_4.Value,
                    Email = outletcommunicationmethod_4.Value,
                    BondExpirationDate = (DateTime)outletoffroadagent.BondExpirationDate
                }
                );

           return query.ToList();
       }
</code>```

答:
You could split out each Concat into its own query.

For example

```<code>var query1 = from outlet in _modelContext.Outlets
              ...;

var query2 = from outlet in _modelContext.Outlets
              ...;

var fullquery = query1.Concat(query2).Concat(...);
</code>```

Body:
I have a linq query that works just fine but when StyleCop is run on the the project the following error is produced: "CA1505 : Microsoft.Maintainability: Rewrite or refactor the type's methods to increase its maintainability index (MI)". I have tested removing part of the query and found that that fixes the error. The issue appears to be that the query is just too long, so I'm looking for a way to shorten it to eliminate the CA1505 error. The challenge here is that the data resides in 5 main tables, the sql equivalent to this is basically 5 union all statements. Any Suggestions?

    public List<ExpiringItemModel> GetByDaysToExpire(int days)
    {
        var int1 = days - 30;
        var int2 = days - 16;
        var int3 = days - 0;

        var query = (
            from outlet in _modelContext.Outlets
            join outletcommunicationmethod in _modelContext.OutletCommunicationMethods on
                new { Id = outlet.Id }
                equals new { Id = outletcommunicationmethod.OutletId }
            join outletcarpermitagent in _modelContext.outletcarpermitagents on
                new { Id = outlet.Id } equals
                new { Id = outletcarpermitagent.OutletId }
            join outlettype in _modelContext.OutletTypes on
                new { OutletTypeId = outletcarpermitagent.OutletTypeId } equals
                new { OutletTypeId = outlettype.Id }
            where
                (outletcommunicationmethod.CommunicationMethodId == 1
                &&
                SqlFunctions.DateDiff("day", SqlFunctions.GetDate(),
                                      outletcarpermitagent.BondExpirationDate) > 0) &&

                (SqlFunctions.DateDiff("day", SqlFunctions.GetDate(),
                                        outletcarpermitagent.BondExpirationDate) == days ||
                (SqlFunctions.DateDiff("day", SqlFunctions.GetDate(),
                                        outletcarpermitagent.BondExpirationDate) == 30) ||
                (SqlFunctions.DateDiff("day", SqlFunctions.GetDate(),
                                        outletcarpermitagent.BondExpirationDate) == 14))

            select new ExpiringItemModel
            {
                Id = (Int32)outletcarpermitagent.Id,
                AgentType = outlettype.Value,
                Email = outletcommunicationmethod.Value,
                BondExpirationDate = (DateTime)outletcarpermitagent.BondExpirationDate
            }
            ).Concat
            (
                from outlet_1 in _modelContext.Outlets
                join outletcommunicationmethod_1 in _modelContext.OutletCommunicationMethods on
                    new { Id = outlet_1.Id } equals new { Id = outletcommunicationmethod_1.OutletId }
                join outlettruckpermitagent in _modelContext.outlettruckpermitagents on
                    new { Id = outlet_1.Id } equals new { Id = outlettruckpermitagent.OutletId }
                join outlettype_1 in _modelContext.OutletTypes on
                    new { OutletTypeId = outlettruckpermitagent.OutletTypeId } equals
                    new { OutletTypeId = outlettype_1.Id }
                where
                    (outletcommunicationmethod_1.CommunicationMethodId == 1
                    &&
                    SqlFunctions.DateDiff("day", SqlFunctions.GetDate(),
                                          outlettruckpermitagent.BondExpirationDate) > 0) &&

                    (SqlFunctions.DateDiff("day", SqlFunctions.GetDate(),
                                          outlettruckpermitagent.BondExpirationDate) == days ||
                    (SqlFunctions.DateDiff("day", SqlFunctions.GetDate(),
                                            outlettruckpermitagent.BondExpirationDate) == 30) ||
                    (SqlFunctions.DateDiff("day", SqlFunctions.GetDate(),
                                            outlettruckpermitagent.BondExpirationDate) == 14))

                select new ExpiringItemModel
                {
                    Id = (Int32)outlettruckpermitagent.Id,
                    AgentType = outlettype_1.Value,
                    Email = outletcommunicationmethod_1.Value,
                    BondExpirationDate = (DateTime)outlettruckpermitagent.BondExpirationDate
                }
            ).Concat
            (
                from outlet_2 in _modelContext.Outlets
                join outletcommunicationmethod_2 in _modelContext.OutletCommunicationMethods on
                    new { Id = outlet_2.Id } equals new { Id = outletcommunicationmethod_2.OutletId }
                join outletcyclepermitagent in _modelContext.outletcyclepermitagents on new { Id = outlet_2.Id } equals
                    new { Id = outletcyclepermitagent.OutletId }
                join outlettype_2 in _modelContext.OutletTypes on new { OutletTypeId = outletcyclepermitagent.OutletTypeId }
                    equals new { OutletTypeId = outlettype_2.Id }
                where
                    (outletcommunicationmethod_2.CommunicationMethodId == 1
                    &&
                    SqlFunctions.DateDiff("day", SqlFunctions.GetDate(),
                                          outletcyclepermitagent.BondExpirationDate) > 0) &&

                    (SqlFunctions.DateDiff("day", SqlFunctions.GetDate(),
                                          outletcyclepermitagent.BondExpirationDate) == days ||
                    (SqlFunctions.DateDiff("day", SqlFunctions.GetDate(),
                                            outletcyclepermitagent.BondExpirationDate) == 30) ||
                    (SqlFunctions.DateDiff("day", SqlFunctions.GetDate(),
                                            outletcyclepermitagent.BondExpirationDate) == 14))

                select new ExpiringItemModel
                {
                    Id = (Int32)outletcyclepermitagent.Id,
                    AgentType = outlettype_2.Value,
                    Email = outletcommunicationmethod_2.Value,
                    BondExpirationDate = (DateTime)outletcyclepermitagent.BondExpirationDate
                }
                ).Concat
                (
                from outlet_3 in _modelContext.Outlets
                join outletcommunicationmethod_3 in _modelContext.OutletCommunicationMethods on
                    new { Id = outlet_3.Id } equals new { Id = outletcommunicationmethod_3.OutletId }
                join outletscooteragent in _modelContext.outletscooteragentAgents on
                    new { Id = outlet_3.Id } equals
                    new { Id = outletscooteragent.OutletId }
                join outlettype_3 in _modelContext.OutletTypes on
                    new { OutletTypeId = outletscooteragent.OutletTypeId }
                    equals new { OutletTypeId = outlettype_3.Id }
                where
                    (outletcommunicationmethod_3.CommunicationMethodId == 1
                    &&
                    SqlFunctions.DateDiff("day", SqlFunctions.GetDate(),
                                          outletscooteragent.BondExpirationDate) > 0) &&

                    (SqlFunctions.DateDiff("day", SqlFunctions.GetDate(),
                                          outletscooteragent.BondExpirationDate) == days ||
                    (SqlFunctions.DateDiff("day", SqlFunctions.GetDate(),
                                            outletscooteragent.BondExpirationDate) == 30) ||
                    (SqlFunctions.DateDiff("day", SqlFunctions.GetDate(),
                                            outletscooteragent.BondExpirationDate) == 14))

                select new ExpiringItemModel
                {
                    Id = (Int32)outletscooteragent.Id,
                    AgentType = outlettype_3.Value,
                    Email = outletcommunicationmethod_3.Value,
                    BondExpirationDate = (DateTime)outletscooteragent.BondExpirationDate
                }
                ).Concat
                (
                from outlet_4 in _modelContext.Outlets
                join outletcommunicationmethod_4 in _modelContext.OutletCommunicationMethods on
                    new { Id = outlet_4.Id } equals new { Id = outletcommunicationmethod_4.OutletId }
                join outletoffroadagent in _modelContext.outletoffroadagentAgents on new { Id = outlet_4.Id } equals
                    new { Id = outletoffroadagent.OutletId }
                join outlettype_4 in _modelContext.OutletTypes on new { OutletTypeId = outletoffroadagent.OutletTypeId }
                    equals new { OutletTypeId = outlettype_4.Id }
                where
                    (outletcommunicationmethod_4.CommunicationMethodId == 1
                    &&
                    SqlFunctions.DateDiff("day", SqlFunctions.GetDate(),
                                          outletoffroadagent.BondExpirationDate) > 0) &&

                    (SqlFunctions.DateDiff("day", SqlFunctions.GetDate(),
                                             outletoffroadagent.BondExpirationDate) == days ||
                    (SqlFunctions.DateDiff("day", SqlFunctions.GetDate(),
                                            outletoffroadagent.BondExpirationDate) == 30) ||
                    (SqlFunctions.DateDiff("day", SqlFunctions.GetDate(),
                                            outletoffroadagent.BondExpirationDate) == 14))

                select new ExpiringItemModel
                {
                    Id = (Int32)outletoffroadagent.Id,
                    AgentType = outlettype_4.Value,
                    Email = outletcommunicationmethod_4.Value,
                    BondExpirationDate = (DateTime)outletoffroadagent.BondExpirationDate
                }
                );

           return query.ToList();
       }

Body:
You could split out each Concat into its own query.

For example

var query1 = from outlet in _modelContext.Outlets
              ...;

var query2 = from outlet in _modelContext.Outlets
              ...;

var fullquery = query1.Concat(query2).Concat(...);


来源: stackexchange

问:
Why can't read a .json?
I want to read a .json using library json-simple, my json file is:

```<code>{
    "Subjects": {
    "subject1": "MIS",
    "subject2": "DBMS",
    "subject3": "UML"
    }
}

</code>```

And my code is:

```<code>import java.io.*;
import java.util.*;
import org.json.simple.*;
import org.json.simple.parser.*;
public class JSONReadFromTheFileTest {
    public static void main(String[] args) {
        JSONParser parser = new JSONParser();
        try{
            Object obj = parser.parse(new FileReader("/Users/User/Desktop/course.json"));
            JSONObject jsonObject = (JSONObject)obj;
            JSONArray subjects = (JSONArray)jsonObject.get("Subjects");
            Iterator iterator = subjects.iterator();
            while (iterator.hasNext()) {
                System.out.println(iterator.next());
            }

        }catch(Exception e){
            e.printStackTrace();
        }
    }
}
</code>```

I would like to get in console:

```<code>subject1: MIS
subject2: DBMS
subject3: UML
</code>```

But instead of that, I just get the next error:

```<code>java.lang.ClassCastException: org.json.simple.JSONObject cannot be cast to org.json.simple.JSONArray
    at project.Main(Main.java:11)
</code>```

But I searched in internet, and I found that if I change sintaxys of the .json in the next way:

```<code>{
    "Subjects": [
    "subject1: MIS",
    "subject2: DBMS",
    "subject3: UML"
    ]
}
</code>```

I get in console what I want:

```<code>subject1: MIS
subject2: DBMS
subject3: UML
</code>```

And you may think my problem is solved, but not yet, because I want to read the json file in the first way.
I hope someone can help me. Thanks in advance.

答:
To make your code work with your json, you should not use JSONArray for "Subjects" but instead JSONObject. The reason is that [ and ] indicates beginning and ending of array element in json which is represented by JSONArray. If you have { and } element then its object represented by JSONObject. zz So replace this:

```<code>JSONArray subjects = (JSONArray)jsonObject.get("Subjects");
Iterator iterator = subjects.iterator();
while (iterator.hasNext()) {
      System.out.println(iterator.next());
}
</code>```

with following (I have not compiled it):

```<code>JSONObject subjects = (JSONObject)jsonObject.get("Subjects");
for(Iterator iterator = subjects.keySet().iterator(); iterator.hasNext();) {
    String key = (String) iterator.next();
    System.out.println(key + ": " + subjects.get(key));
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Why can't read a .json?

Body:
I want to read a .json using library json-simple, my json file is:

{
    "Subjects": {
    "subject1": "MIS",
    "subject2": "DBMS",
    "subject3": "UML"
    }
}

And my code is:

import java.io.*;
import java.util.*;
import org.json.simple.*;
import org.json.simple.parser.*;
public class JSONReadFromTheFileTest {
    public static void main(String[] args) {
        JSONParser parser = new JSONParser();
        try{
            Object obj = parser.parse(new FileReader("/Users/User/Desktop/course.json"));
            JSONObject jsonObject = (JSONObject)obj;
            JSONArray subjects = (JSONArray)jsonObject.get("Subjects");
            Iterator iterator = subjects.iterator();
            while (iterator.hasNext()) {
                System.out.println(iterator.next());
            }

        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

I would like to get in console:

subject1: MIS
subject2: DBMS
subject3: UML

But instead of that, I just get the next error:

java.lang.ClassCastException: org.json.simple.JSONObject cannot be cast to org.json.simple.JSONArray
    at project.Main(Main.java:11)

But I searched in internet, and I found that if I change sintaxys of the .json in the next way:

{
    "Subjects": [
    "subject1: MIS",
    "subject2: DBMS",
    "subject3: UML"
    ]
}

I get in console what I want:

subject1: MIS
subject2: DBMS
subject3: UML

And you may think my problem is solved, but not yet, because I want to read the json file in the first way.
I hope someone can help me. Thanks in advance.

Body:
To make your code work with your json, you should not use JSONArray for "Subjects" but instead JSONObject. The reason is that [ and ] indicates beginning and ending of array element in json which is represented by JSONArray. If you have { and } element then its object represented by JSONObject. zz So replace this:

JSONArray subjects = (JSONArray)jsonObject.get("Subjects");
Iterator iterator = subjects.iterator();
while (iterator.hasNext()) {
      System.out.println(iterator.next());
}

with following (I have not compiled it):

JSONObject subjects = (JSONObject)jsonObject.get("Subjects");
for(Iterator iterator = subjects.keySet().iterator(); iterator.hasNext();) {
    String key = (String) iterator.next();
    System.out.println(key + ": " + subjects.get(key));
}


问:
Can't access local files in data/data of some phones
I'm having three not rooted phones here. Two of them have Android 10 and one has Android 8.0. On one with Android 10 I just cant access the app files in /data/data directory with the Device File Explorer in Android Studio.
The error I get is:

`run-as: /data has wrong owner: 0/1000, not 1000´

I'm just not finding anything useful to fix this.

答:
Since I had to dive into the comments of the original question to solve it for myself, I'll repeat the answer that helped me.

I uninstalled the app, restarted my phone, installed it again with android studio and it worked like a charm after that.


问:
How do I edit an ipynb file on github?
I have a repository on GitHub where I uploaded a Jupyter Notebook file. I created another branch and want to edit the ipynb file.

Clicking the edit button produces an HTML file which is really confusing. I want to edit the ipynb file and run it before pushing the commit. How do I do this, please?

答:
.ipynb files can't be edited on GitHub online, but you can do it through GitHub Desktop.

Clone the repository which has the file you want to edit, on GitHub Desktop.

Select 'see files in explorer'. It opens the folder in which the files from your repository have been cloned. It might be called something else if you're not on Windows.

Open the relevant file(s) and make the changes and save it.

On GitHub Desktop, select the relevant repository from the 'current repository' menu on the top left if the repository is not already selected. You'll see the changes you've made when you select the file from the left pane.

Select the file(s) you've made changes to.

Click on the 'Commit to main' button on the bottom left corner. This will commit the changes to your local repository i.e. the cloned repository on your system.

Click on the 'Push origin' button on the top pane. This will commit the changes to your repository on the GitHub website.

Title: How do I edit an ipynb file on github?


问:
Error: TypeError: must be str, not NoneType while Scraping list Links from website using BeautifulSoup
I want to scrape https://ens.dk/en/our-services/oil-and-gas-related-data/monthly-and-yearly-production this website.
there are 2 set of links SI units and Oil Field units

I have tried to scrape the list of links form SI units and created function called get_gas_links

```<code>import io
import requests
import pandas as pd
from bs4 import BeautifulSoup as bs, SoupStrainer
import re

url = "https://ens.dk/en/our-services/oil-and-gas-related-data/monthly-and-yearly-production"

first_page = requests.get(url)
soup = bs(first_page.content)

def pasrse_page(link):
print(link)
df = pd.read_html(link, skiprows=1, headers=1)
return df

def get_gas_links():
glinks=[]
gas_links = soup.find_all("a", href = re.compile("si.htm"))

for i in gas_links:
    glinks.append("https://ens.dk/" + i.get("herf"))
return glinks

get_gas_links()
</code>```

Main motive to scrape 3 tables from every link however before scraping table I am trying to scrape list of links

but it shows error : TypeError: must be str, not NoneType
error_image

答:
You are using wrong regex in a wrong way. That's why soup can not find any links that fulfills the criteria.
You can check the following source and validate the the extracted_link however you want.</p>
```<code>def get_gas_links():
    glinks=[]
    gas_links = soup.find('table').find_all('a')
    for i in gas_links:
        extracted_link = i['href']
        #you can validate the extracted link however you want
        glinks.append("https://ens.dk/" + extracted_link)
    return glinks
</code>```

Body:
I want to scrape https://ens.dk/en/our-services/oil-and-gas-related-data/monthly-and-yearly-production this website.
there are 2 set of links SI units and Oil Field units

I have tried to scrape the list of links form SI units and created function called get_gas_links

import io
import requests
import pandas as pd
from bs4 import BeautifulSoup as bs, SoupStrainer
import re

url = "https://ens.dk/en/our-services/oil-and-gas-related-data/monthly-and-yearly-production"

first_page = requests.get(url)
soup = bs(first_page.content)

def pasrse_page(link):
print(link)
df = pd.read_html(link, skiprows=1, headers=1)
return df

def get_gas_links():
glinks=[]
gas_links = soup.find_all("a", href = re.compile("si.htm"))

for i in gas_links:
    glinks.append("https://ens.dk/" + i.get("herf"))
return glinks

get_gas_links()

Main motive to scrape 3 tables from every link however before scraping table I am trying to scrape list of links

but it shows error : TypeError: must be str, not NoneType
error_image

Body:
You are using wrong regex in a wrong way. That's why soup can not find any links that fulfills the criteria.
You can check the following source and validate the the extracted_link however you want.

def get_gas_links():
    glinks=[]
    gas_links = soup.find('table').find_all('a')
    for i in gas_links:
        extracted_link = i['href']
        #you can validate the extracted link however you want
        glinks.append("https://ens.dk/" + extracted_link)
    return glinks


问:
Upgrading Controller after upgrading a CustomResourceDefinition
With Kubernetes 1.22, the beta API for the CustomResourceDefinition apiextensions.k8s.io/v1beta1 was removed and replaced with apiextensions.k8s.io/v1. While changing the CRDs, I have come to realize that my older controller (operator pattern, originally written for v1alpha1) still tries to list apiextensions.k8s.io/v1alpha1 even though I have changed the CRD to apiextensions.k8s.io/v1.

I have read this source and it states that for deployment, I should change the API version but my case is an extension of this since I don't have the controller for the new API.

Do I need to write a new controller for the new API version?

答:
Do I need to write a new controller for the new API version ?

Unfortunately, it looks like it does. If you are unable to apply what is described in this similar question, because you are using a custom controller then you need to create your own new controller (if you cannot change API inside it) that will work with the supported API. Look at Custom controllers page in the official documentation.

I am not sure if the controller can manage the new API version. Even after changing the API version of the CRD to v1 from v1Alpha1, I get an error message stating that tha controller is trying to list CRD with API version v1alpha1.

It looks like the controller has some bugs. There should be no problem referencing the new API as written [in this documentation](It looks like the controller is badly written. There should be no problem referencing the new API as written in this documentation.):

The  v1.22  release will stop serving the following deprecated API versions in favor of newer and more stable API versions:

Ingress in the  extensions/v1beta1  API version will no longer be served

Migrate to use the  networking.k8s.io/v1beta1  API version, available since v1.14. >Existing persisted data can be retrieved/updated via the new version.

Kubernetes 1.16 is due to be released in September 2019, so be sure to audit your configuration and integrations now!

Change YAML files to reference the newer APIs

Update custom integrations and controllers to call the newer APIs

Update third party tools (ingress controllers, continuous delivery systems) to call the newer APIs

See also Kubernetes API and Feature Removals In 1.22: Here’s What You Need To Know.


问:
center the text in position 0, code problem xamarin
I looked everywhere, but for the moment works.

here is my code:

```<code>     <Spinner
                    android:id="@+id/departement"
                    android:layout_width="match_parent"
                    android:layout_height="25dp"
                    android:background="@color/colorAccent"
                    android:layout_marginLeft="10dp"
                    android:layout_marginRight="10dp"
                    android:gravity="center_vertical|center_horizontal"
                     />

      Spinner departement = (Spinner)sender;
      ((TextView)departement.GetChildAt(0)).SetForegroundGravity(GravityFlags.CenterHorizontal);
      ((TextView)departement.GetChildAt(0)).SetTextColor(Color.White);
</code>```

the color works, but the center position does not. do you have an idea ?

答:
You can use a new xml to define the content of that item in Spinner.

And cusotmize the style in that xml .

Item.xml

<?xml version="1.0" encoding="utf-8" ?>
    <TextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"    //center
    android:textColor="@android:color/holo_red_dark"/>   //Textcolor
```
<h4>Set in Adapter</h4>
<pre class="lang-cs prettyprint-override"><code>ArrayAdapter<string> adapter = new ArrayAdapter<string>(this,Resource.Layout.Item,items);
departement.Adapter = adapter;
</code>```

Body:
I looked everywhere, but for the moment works.

here is my code:

     <Spinner
                    android:id="@+id/departement"
                    android:layout_width="match_parent"
                    android:layout_height="25dp"
                    android:background="@color/colorAccent"
                    android:layout_marginLeft="10dp"
                    android:layout_marginRight="10dp"
                    android:gravity="center_vertical|center_horizontal"
                     />

      Spinner departement = (Spinner)sender;
      ((TextView)departement.GetChildAt(0)).SetForegroundGravity(GravityFlags.CenterHorizontal);
      ((TextView)departement.GetChildAt(0)).SetTextColor(Color.White);

the color works, but the center position does not. do you have an idea ?

Body:
You can use a new xml to define the content of that item in Spinner.

And cusotmize the style in that xml .

Item.xml

<?xml version="1.0" encoding="utf-8" ?>
    <TextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"    //center
    android:textColor="@android:color/holo_red_dark"/>   //Textcolor

Set in Adapter

ArrayAdapter<string> adapter = new ArrayAdapter<string>(this,Resource.Layout.Item,items);
departement.Adapter = adapter;


问:
Intellij IDEA debug Maven-GWT project with specific PROFILE
I have maven gwt project with many profiles which i use for replacement some params in .properties files. Can i start debugging gwt application in Intellij Idea with specific maven profile?</p>

答:
The Maven side panel can be opened with "View > Tool windows > Maven". Note that the "Profiles" section will be at the top of the list of Maven projects and it will only appear if at least one Maven project/module has at least two Profiles.

For more details, see here: https://www.jetbrains.com/help/idea/work-with-maven-profiles.html#activate_maven_profiles


问:
Angular: how to initialize variable inside *ngFor
I have an Angular template:

  <input type="radio" class="form-check-input" id="radio-{{rand}}" name="field-radio"
    [value]="item.key">

    {{ item.key }}

```

I want to execute random() function for every iteration of loop. But I get an error:

Property 'random' does not exist on type...

How can I use internal variable inside Angular template?

答:
```<code><li *ngFor="let item of list | keyvalue">
    <ng-container *ngTemplateOutlet="list; context: { item: item }"></ng-container>
</li>

<ng-template #list let-rand="rand()">
    <input type="radio" class="form-check-input" [id]="'radio-'+rand" name="field-radio" [value]="item.key">
    <label class="form-check-label" [for]="'radio-'+rand">
   {{ item.key }}
 </label>
</ng-template>
</code>```

Body:
I have an Angular template:

  <input type="radio" class="form-check-input" id="radio-{{rand}}" name="field-radio"
    [value]="item.key">

    {{ item.key }}

I want to execute random() function for every iteration of loop. But I get an error:

Property 'random' does not exist on type...

How can I use internal variable inside Angular template?


问:
How can user inputs be typed in so that I can separate each value by a comma instead of pressing Enter after each value?
Instead of having to press Enter after each value input with Scanner, is there a way to type all values at once, and then press enter and be done?

```<code>import java.util.Arrays;
import java.util.Scanner;

class Arrayex {
    public static void main(String[] args)
    {
        int [] numbers = new int[5];

        Scanner s=new Scanner(System.in);
        System.out.println("Current array: " + Arrays.toString(numbers));

        System.out.println("Type in the numbers: ");
        for(int i=0; i< numbers.length; i++)
        {
            numbers[i] = s.nextInt();
        }

        System.out.println("Array elements are: " + Arrays.toString(numbers));
    }
}
</code>```

Current array input by pressing Enter after every number

How I want to type in the numbers into the array

My friend told me I can use a String array and convert it to int array and type the string as "1,2,3,4,5".
Wouldn't this only use up the location at numbers[0] instead of numbers[0] to numbers[5]?

答:
Enter all int elements in one line using space, it will use as separate int values.
it will look like this.

No need to take input as String and parse it to an integer.

Body:
Instead of having to press Enter after each value input with Scanner, is there a way to type all values at once, and then press enter and be done?

import java.util.Arrays;
import java.util.Scanner;

class Arrayex {
    public static void main(String[] args)
    {
        int [] numbers = new int[5];

        Scanner s=new Scanner(System.in);
        System.out.println("Current array: " + Arrays.toString(numbers));

        System.out.println("Type in the numbers: ");
        for(int i=0; i< numbers.length; i++)
        {
            numbers[i] = s.nextInt();
        }

        System.out.println("Array elements are: " + Arrays.toString(numbers));
    }
}

Current array input by pressing Enter after every number

How I want to type in the numbers into the array

My friend told me I can use a String array and convert it to int array and type the string as "1,2,3,4,5".
Wouldn't this only use up the location at numbers[0] instead of numbers[0] to numbers[5]?


问:
Using POJOs in fp-ts
I want to do what I think is the simplest thing, map through a plain old Javascript object, using fp-ts constructs.

There are a lot of operators I would like to use — map, filterMap, and so on — but they seem to require the Map type (which I assume is the Javascript Map object) — and there does not seem to be any easy way to convert back and forth between Map and Javascript object, which in Typescript is the standard representation of algebraic data types and of its Record<K,V> type.

This seems like a pretty big hole.  Please don’t tell me I have to switch to lodash...

答:
fp-ts/Record lets you work with Record<K, V> as if they were a Functor in V, so you can have

import { map } from 'fp-ts/Record'

const mapped = map((v: number) => v + 1)({a: 1}) // { a: 2 }
```

Title: Using POJOs in fp-ts


问:
Use "ANCESTOR IN <list>" in AppEngine query
I have objects of type A and B where A is having many B (one-to-many).

I use it for two reasons

To be able to make transactions within the entity group

Find all B objects that is children to a list of A objects

To accomodate (1) I need A to be parent to B. Can I use this relationship to do the (2) query as well? That query would be a "ANCESTOR IN " filter, is that possible?

Otherwise I would store the relationship in two ways, both as a parent and secondly as a regular property?

答:
There is no ANCESTOR IN operator, only ANCESTOR IS -- in other words you can easily find the children of one A, but not of many.  The following will find all B entities that are children of a specific A.

```<code>parent_key = db.Key.from_path('A', parent_key_name)
children_of_a = B.all().ancestor(parent_key).fetch(100)
</code>```

It is very important to understand that all IN queries in App Engine use multiple queries behind the scenes.  If you add a parent property to query on, and you're using the high-replication datastore (you should be), you also need to understand the nuances of cross-entity group queries -- they will not be strongly consistent.  So, if you are expecting a very small list of parents (say, one or two) in most cases, and you want strong consistency, you may be better running multiple ancestor queries.  If you'll typically have many parents, and eventual consistency is ok, add a property you can query on.

ContentLicense: CC BY-SA 3.0

Body:
There is no ANCESTOR IN operator, only ANCESTOR IS -- in other words you can easily find the children of one A, but not of many.  The following will find all B entities that are children of a specific A.

parent_key = db.Key.from_path('A', parent_key_name)
children_of_a = B.all().ancestor(parent_key).fetch(100)

It is very important to understand that all IN queries in App Engine use multiple queries behind the scenes.  If you add a parent property to query on, and you're using the high-replication datastore (you should be), you also need to understand the nuances of cross-entity group queries -- they will not be strongly consistent.  So, if you are expecting a very small list of parents (say, one or two) in most cases, and you want strong consistency, you may be better running multiple ancestor queries.  If you'll typically have many parents, and eventual consistency is ok, add a property you can query on.


问:
Cant run iptables in Dockerfile
I have been battling for a while on this!  Given the following Dockerfile, if I leave the RUN iptables... lines out, then execute them manually inside the running docker container they work fine.  But if I leave them in Dockerfile I get a permissions error.

```<code>FROM ubuntu
RUN apt-get update
RUN apt-get install -y iptables
RUN iptables -I INPUT -p tcp --dport 27015 -j ACCEPT
RUN iptables -A INPUT -i eth0 -j QUEUE
</code>```

The output of docker build gives:

```<code>[+] Building 0.4s (7/8)
 => [internal] load build definition from Dockerfile                                                               0.0s
 => => transferring dockerfile: 199B                                                                               0.0s
 => [internal] load .dockerignore                                                                                0.0s
 => => transferring context: 2B                                                                                0.0s
 => [internal] load metadata for docker.io/library/ubuntu:latest                                                   0.0s
 => [1/5] FROM docker.io/library/ubuntu                                                                            0.0s
 => CACHED [2/5] RUN apt-get update                                                                                0.0s
 => CACHED [3/5] RUN apt-get install -y iptables                                                                   0.0s
 => ERROR [4/5] RUN iptables -I INPUT -p tcp --dport 27015 -j ACCEPT                                               0.3s
------
 > [4/5] RUN iptables -I INPUT -p tcp --dport 27015 -j ACCEPT:
#7 0.256 getsockopt failed strangely: Operation not permitted
------
executor failed running [/bin/sh -c iptables -I INPUT -p tcp --dport 27015 -j ACCEPT]: exit code: 1
</code>```

But if I use:

```<code>FROM ubuntu
RUN apt-get update
RUN apt-get install -y iptables
</code>```

Docker build completes OK, then I run the image with:

```<code>docker run -i -t --cap-add NET_RAW --cap-add NET_ADMIN 094d0bb9befb
</code>```

The container opens and at the command prompt I can type in the iptables rules as above.  They are accepted and work exactly as I require.

Any ideas how I can apply these iptable rules directly from the Dockerfile?

答:
how I can apply these iptable rules directly from the Dockerfile?

You can't. And they make little sense - they are affecting the temporary container created for building the image.

Each container has a separate network namespace, which includes separate interfaces and firewall. On container startup, a separate network space is created.

Create a script that will be run on CMD or ENTRYPOINT or manually on container startup and in that script add commands that should affect the current container environment..

Title: Cant run iptables in Dockerfile

Body:
I have been battling for a while on this!  Given the following Dockerfile, if I leave the RUN iptables... lines out, then execute them manually inside the running docker container they work fine.  But if I leave them in Dockerfile I get a permissions error.

FROM ubuntu
RUN apt-get update
RUN apt-get install -y iptables
RUN iptables -I INPUT -p tcp --dport 27015 -j ACCEPT
RUN iptables -A INPUT -i eth0 -j QUEUE

The output of docker build gives:

[+] Building 0.4s (7/8)
 => [internal] load build definition from Dockerfile                                                               0.0s
 => => transferring dockerfile: 199B                                                                               0.0s
 => [internal] load .dockerignore                                                                                0.0s
 => => transferring context: 2B                                                                                0.0s
 => [internal] load metadata for docker.io/library/ubuntu:latest                                                   0.0s
 => [1/5] FROM docker.io/library/ubuntu                                                                            0.0s
 => CACHED [2/5] RUN apt-get update                                                                                0.0s
 => CACHED [3/5] RUN apt-get install -y iptables                                                                   0.0s
 => ERROR [4/5] RUN iptables -I INPUT -p tcp --dport 27015 -j ACCEPT                                               0.3s
------
 > [4/5] RUN iptables -I INPUT -p tcp --dport 27015 -j ACCEPT:
#7 0.256 getsockopt failed strangely: Operation not permitted
------
executor failed running [/bin/sh -c iptables -I INPUT -p tcp --dport 27015 -j ACCEPT]: exit code: 1

But if I use:

FROM ubuntu
RUN apt-get update
RUN apt-get install -y iptables

Docker build completes OK, then I run the image with:

docker run -i -t --cap-add NET_RAW --cap-add NET_ADMIN 094d0bb9befb

The container opens and at the command prompt I can type in the iptables rules as above.  They are accepted and work exactly as I require.

Any ideas how I can apply these iptable rules directly from the Dockerfile?


问:
I made this to print "Hello World !", but now I want to know other ways to print "Hello World !" in C++, simplify it if can
I made this, but now I want to know other ways to do this, and simplify it.

```<code>#include <iostream>
#include <stdio.h>

int main()
{
    char* a[50] = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "!"};

    std::cout << a[7] << a[4] << a[11] << a[11] << a[14] << " " << a[22] << a[14] << a[17] << a[11] << a[3] << " " << a[26];

    return 0;
}
</code>```

Yes, I know cout << "hello world !"; exists, but I want to try things differently.

答:
If you "want to do thing differently" by addressing the letter by array index, yet want to simplify the array notation, I suggest this:</p>
```<code>#include <iostream>
#include <string>

int main(){
    using namespace std;
    string a="abcdefghijklmnopqrstuvwxyz!";
    cout<<a[7]<<a[4]<<a[11]<<a[11]<<a[14]<<" "<<a[22]<<a[14]<<a[17]<<a[11]<<a[3]<<" "<<a[26];
    return 0;
}
</code>```

Body:
I made this, but now I want to know other ways to do this, and simplify it.

#include <iostream>
#include <stdio.h>

int main()
{
    char* a[50] = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "!"};

    std::cout << a[7] << a[4] << a[11] << a[11] << a[14] << " " << a[22] << a[14] << a[17] << a[11] << a[3] << " " << a[26];

    return 0;
}

Yes, I know cout << "hello world !"; exists, but I want to try things differently.

Body:
If you "want to do thing differently" by addressing the letter by array index, yet want to simplify the array notation, I suggest this:

#include <iostream>
#include <string>

int main(){
    using namespace std;
    string a="abcdefghijklmnopqrstuvwxyz!";
    cout<<a[7]<<a[4]<<a[11]<<a[11]<<a[14]<<" "<<a[22]<<a[14]<<a[17]<<a[11]<<a[3]<<" "<<a[26];
    return 0;
}


问:
Get InnerHTML from Class
```<code>    <div class="quantity-selector">
    <span class="quantity-element decrease_qty">-</span>
    <span class="quantity-element quantity-digit">1</span>
    <input type="hidden" value="1" name="quantity">
    <span class="quantity-element increase_qty">+</span>
    </div>
</code>```

<p>Trying to get the innerhtml from "quantity-element quantity-digit" class </p>

答:
// with querySelector in Javascript
console.log(document.querySelector(".quantity-element.quantity-digit").innerHTML);

// with Jquery
console.log($('.quantity-element.quantity-digit').html());```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="quantity-selector">
    <span class="quantity-element decrease_qty">-</span>
    <span class="quantity-element quantity-digit">1</span>
    <input type="hidden" value="1" name="quantity">
    <span class="quantity-element increase_qty">+</span>
</div></code>```

Title: Get InnerHTML from Class

Body:
    -
    1
    <input type="hidden" value="1" name="quantity">
    +

Trying to get the innerhtml from "quantity-element quantity-digit" class

Body:
// with querySelector in Javascript
console.log(document.querySelector(".quantity-element.quantity-digit").innerHTML);

// with Jquery
console.log($('.quantity-element.quantity-digit').html());

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="quantity-selector">
    <span class="quantity-element decrease_qty">-</span>
    <span class="quantity-element quantity-digit">1</span>
    <input type="hidden" value="1" name="quantity">
    <span class="quantity-element increase_qty">+</span>
</div>


问:
php upload: zip files
Why can't I get the .zip as type and its size through an uploading form but only can get its name only?

```<code>Array
(
    [file] => Array
        (
            [name] => Array
                (
                    [0] => attachments_2011_05_20.zip
                )

            [type] => Array
                (
                    [0] =>
                )

            [tmp_name] => Array
                (
                    [0] =>
                )

            [error] => Array
                (
                    [0] => 1
                )

            [size] => Array
                (
                    [0] => 0
                )

        )

)
</code>```

Something extra should I do to get the zip size and type?

答:
LIST OF ERROR CODES
UPLOAD_ERR_OK

Value: 0; There is no error, the file uploaded with success.
UPLOAD_ERR_INI_SIZE

Value: 1; The uploaded file exceeds the upload_max_filesize directive in php.ini.
UPLOAD_ERR_FORM_SIZE

Value: 2; The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.
UPLOAD_ERR_PARTIAL

Value: 3; The uploaded file was only partially uploaded.
UPLOAD_ERR_NO_FILE

Value: 4; No file was uploaded.
UPLOAD_ERR_NO_TMP_DIR

Value: 6; Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3.
UPLOAD_ERR_CANT_WRITE

Value: 7; Failed to write file to disk. Introduced in PHP 5.1.0.
UPLOAD_ERR_EXTENSION

Value: 8; A PHP extension stopped the file upload. PHP does not provide a way to ascertain which extension caused the file upload to stop; examining the list of loaded extensions with phpinfo() may help. Introduced in PHP 5.2.0.
http://www.php.net/manual/en/features.file-upload.errors.php

Title: php upload: zip files

Body:
Why can't I get the .zip as type and its size through an uploading form but only can get its name only?

Array
(
    [file] => Array
        (
            [name] => Array
                (
                    [0] => attachments_2011_05_20.zip
                )

            [type] => Array
                (
                    [0] =>
                )

            [tmp_name] => Array
                (
                    [0] =>
                )

            [error] => Array
                (
                    [0] => 1
                )

            [size] => Array
                (
                    [0] => 0
                )

        )

)

Something extra should I do to get the zip size and type?


问:
How to limit only one active slice per pie chart on amCharts5?
I am trying to replicate the pie chart behaviour from this v4 tutorial on amCharts v5 with no luck:

https://www.amcharts.com/docs/v4/tutorials/one-pulled-slice-per-pie-chart/

The v4 code does not work on v5 (nor getting error). I have debugged it and it loops through the slices, but there is no more "isActive" property, and have not found any other similar property or method to get or set the slice state.

I have already searched in offical docs but found nothing. Seems v5 is lacking some v4 features... anyone accomplished to limit only 1 selected slice per chart?

Thanks in advance.

答:
From official amCharts tutorial "One pulled slice per pie series":

... so whenever a slice is pulled out, it becomes "active" (it's
"active" setting is set to true). And vice versa, setting it to
false will make the slice pop back into its place.

Also, when a slice (or any other object for that matter) is
clicked/tapped, it generates a "click" event. If there's an event
handler defined, it is executed.

Let's use these two bits of code to implement our task:

```<code>series.slices.template.events.on("click", function(ev) {
  series.slices.each(function(slice) {
    if (slice != ev.target && slice.get("active")) {
      slice.set("active", false);
    }
  })
});
</code>```

CodePen example:
https://codepen.io/team/amcharts/pen/dyZzQLJ

Body:
From official amCharts tutorial "One pulled slice per pie series":

... so whenever a slice is pulled out, it becomes "active" (it's
"active" setting is set to true). And vice versa, setting it to
false will make the slice pop back into its place.

Also, when a slice (or any other object for that matter) is
clicked/tapped, it generates a "click" event. If there's an event
handler defined, it is executed.

Let's use these two bits of code to implement our task:

series.slices.template.events.on("click", function(ev) {
  series.slices.each(function(slice) {
    if (slice != ev.target && slice.get("active")) {
      slice.set("active", false);
    }
  })
});

CodePen example:
https://codepen.io/team/amcharts/pen/dyZzQLJ


问:
Github actions and badges show percentage data
I have read about the way to create and add a custom workflow badge which will show whether the workflow passes or fails. But here's a question. Is it possible to output some percentage data on the badge and how to output this data?</p>

答: Recently, I have seen a way of achieving that, but it's a bit like cheating. All you need is to configure a github action dumping the data you want into your gist in a format that the badge service (e.g. shields) supports. and then use the service to provide a badge based on your gist content.


问:
How to revoke a user's google refresh token?
I let users connect their google calendar account to allow their patients to make appointments with them.

How can I revoke a user's refresh token using node js and the google calendar api? Sometimes users request that we no longer have access to their accounts. I want to fulfill their wish.

Here's the code I'm using

```<code>const {tokens} = await oauth2Client.getToken(request.query.code);
oauth2Client.setCredentials({
   access_token: tokens.access_token,
}); // use the new auth client with the access_token

let {data} = await oauth2.userinfo.get({
   auth: oauth2Client,
});
</code>```

答:
Try the revokeToken method. It requires you pass a specific accessToken to the method: oauth2client.ts#L801

Or there is the revokeCredentials method which accepts no arguments, and revokes the access token currently configured in the OAuth2 instance: oauth2client.ts#L827

It may sound strange that i am telling you to use an access token to revoke a refresh token but if you read tokenrevoke you will see that what it actually does is remove the users consent to your application.

Once the users consent is removed refresh tokens are automatically revoked.   so an access token is needed to call the api end point to revoke the refresh token.

Body:
I let users connect their google calendar account to allow their patients to make appointments with them.

How can I revoke a user's refresh token using node js and the google calendar api? Sometimes users request that we no longer have access to their accounts. I want to fulfill their wish.

Here's the code I'm using

const {tokens} = await oauth2Client.getToken(request.query.code);
oauth2Client.setCredentials({
   access_token: tokens.access_token,
}); // use the new auth client with the access_token

let {data} = await oauth2.userinfo.get({
   auth: oauth2Client,
});


问:
What does this thread join code mean?
In this code, what does the two joins and break mean? t1.join() causes t2 to stop until t1 terminates?

```<code>Thread t1 = new Thread(new EventThread("e1"));
t1.start();
Thread t2 = new Thread(new EventThread("e2"));
t2.start();
while (true) {
   try {
      t1.join();
      t2.join();
      break;
   } catch (InterruptedException e) {
      e.printStackTrace();
   }
}
</code>```

答:
The join() method is used to hold the execution of currently running thread until the specified thread is dead(finished execution).

Why we use join() method?

In normal circumstances we generally have more than one thread, thread scheduler schedules the threads, which does not guarantee the order of execution of threads.

Let's take a look at an example, create new project and copy the following code:

this is activity_main.xml code:

```<code><?xml version="1.0" encoding="utf-8"?>

<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/btn_without_join"
    app:layout_constraintTop_toTopOf="parent"
    android:text="Start Threads Without Join"/>
 <Button
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:id="@+id/btn_with_join"
     app:layout_constraintTop_toBottomOf="@id/btn_without_join"
     android:text="Start Threads With Join"/>
 <TextView
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:id="@+id/tv"
     app:layout_constraintTop_toBottomOf="@id/btn_with_join"
     />

 </androidx.constraintlayout.widget.ConstraintLayout>
</code>```

And this is code for MainActivity.java:

```<code>public class MainActivity extends AppCompatActivity {

TextView tv;
volatile  String threadName = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    tv = findViewById(R.id.tv);
    Button btn_without_join = findViewById(R.id.btn_without_join);
    btn_without_join.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            withoutJoin();
        }
    });
    Button btn_with_join = findViewById(R.id.btn_with_join);
    btn_with_join.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            withJoin();
        }
    });
}
private void withoutJoin()
{
    tv.setText("");
    Thread th1 = new Thread(new MyClass2(), "th1");
    Thread th2 = new Thread(new MyClass2(), "th2");
    Thread th3 = new Thread(new MyClass2(), "th3");
    th1.start();
    th2.start();
    th3.start();
}
private void withJoin()
{
    tv.setText("");
    Thread th1 = new Thread(new MyClass2(), "th1");
    Thread th2 = new Thread(new MyClass2(), "th2");
    Thread th3 = new Thread(new MyClass2(), "th3");
    th1.start();
    try {
        th1.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    th2.start();
    try {
        th2.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    th3.start();
}
class MyClass2 implements Runnable{

    @Override
    public void run() {
        Thread t = Thread.currentThread();
        runOnUiThread(new Runnable() {
            public void run() {
                tv.setText(tv.getText().toString()+"\n"+"Thread started: "+t.getName());
            }
        });
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ie) {
            ie.printStackTrace();
        }
        runOnUiThread(new Runnable() {
            public void run() {
                tv.setText(tv.getText().toString()+"\n"+"Thread ended: "+t.getName());
            }
        });

    }
}
}
</code>```

This will be the result if you press first button (Start Threads Without Join):

And this will be the result if you press second button (Start Threads With Join):

Title: What does this thread join code mean?

Body:
In this code, what does the two joins and break mean? t1.join() causes t2 to stop until t1 terminates?

Thread t1 = new Thread(new EventThread("e1"));
t1.start();
Thread t2 = new Thread(new EventThread("e2"));
t2.start();
while (true) {
   try {
      t1.join();
      t2.join();
      break;
   } catch (InterruptedException e) {
      e.printStackTrace();
   }
}

Body:
The join() method is used to hold the execution of currently running thread until the specified thread is dead(finished execution).

Why we use join() method?

In normal circumstances we generally have more than one thread, thread scheduler schedules the threads, which does not guarantee the order of execution of threads.

Let's take a look at an example, create new project and copy the following code:

this is activity_main.xml code:

<?xml version="1.0" encoding="utf-8"?>

<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/btn_without_join"
    app:layout_constraintTop_toTopOf="parent"
    android:text="Start Threads Without Join"/>
 <Button
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:id="@+id/btn_with_join"
     app:layout_constraintTop_toBottomOf="@id/btn_without_join"
     android:text="Start Threads With Join"/>
 <TextView
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:id="@+id/tv"
     app:layout_constraintTop_toBottomOf="@id/btn_with_join"
     />

 </androidx.constraintlayout.widget.ConstraintLayout>

And this is code for MainActivity.java:

public class MainActivity extends AppCompatActivity {

TextView tv;
volatile  String threadName = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    tv = findViewById(R.id.tv);
    Button btn_without_join = findViewById(R.id.btn_without_join);
    btn_without_join.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            withoutJoin();
        }
    });
    Button btn_with_join = findViewById(R.id.btn_with_join);
    btn_with_join.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            withJoin();
        }
    });
}
private void withoutJoin()
{
    tv.setText("");
    Thread th1 = new Thread(new MyClass2(), "th1");
    Thread th2 = new Thread(new MyClass2(), "th2");
    Thread th3 = new Thread(new MyClass2(), "th3");
    th1.start();
    th2.start();
    th3.start();
}
private void withJoin()
{
    tv.setText("");
    Thread th1 = new Thread(new MyClass2(), "th1");
    Thread th2 = new Thread(new MyClass2(), "th2");
    Thread th3 = new Thread(new MyClass2(), "th3");
    th1.start();
    try {
        th1.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    th2.start();
    try {
        th2.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    th3.start();
}
class MyClass2 implements Runnable{

    @Override
    public void run() {
        Thread t = Thread.currentThread();
        runOnUiThread(new Runnable() {
            public void run() {
                tv.setText(tv.getText().toString()+"\n"+"Thread started: "+t.getName());
            }
        });
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ie) {
            ie.printStackTrace();
        }
        runOnUiThread(new Runnable() {
            public void run() {
                tv.setText(tv.getText().toString()+"\n"+"Thread ended: "+t.getName());
            }
        });

    }
}
}

This will be the result if you press first button (Start Threads Without Join):

And this will be the result if you press second button (Start Threads With Join):


问:
How to create Pandas Series with Decimal?
I'm calculating some standard deviations which are giving FloatingPointErrors. I wanted to try converting the data series to Decimal (using https://docs.python.org/3/library/decimal.html), to see if this fixes my issue.

I can't seem to make a pandas series of decimal.

How can I take a normal pd.Series of float64 and convert to a pd.Series of decimal, such that I can do:

```<code>Series.pct_change().ewm(span=35, min_periods=35).std()
</code>```

答:
```<code>from decimal import Decimal

df['col_a'] = df['col_a'].apply(lambda x: Decimal(str(x)))
</code>```

Body:
I'm calculating some standard deviations which are giving FloatingPointErrors. I wanted to try converting the data series to Decimal (using https://docs.python.org/3/library/decimal.html), to see if this fixes my issue.

I can't seem to make a pandas series of decimal.

How can I take a normal pd.Series of float64 and convert to a pd.Series of decimal, such that I can do:

Series.pct_change().ewm(span=35, min_periods=35).std()


问:
Why does Clipboard.HasFormat( CF_HDROP ) return false in FormCreate
Why does Clipboard.HasFormat( CF_HDROP ) return false in FormCreate even though the clipboard contains Shell formats?

Edit

```<code>procedure TFormMain.FormCreate( Sender: TObject );
begin
  if Clipboard.HasFormat( CF_HDROP ) then
    MessageDlg( 'true', mtInformation, [ mbOK ], 0 )
  else
    MessageDlg( 'false', mtInformation, [ mbOK ], 0 );
end;
</code>```

This returns false but MyIdleHandler returns true:

```<code>Application.OnIdle := MyIdleHandler;

procedure TFormMain.MyIdleHandler(Sender: TObject; var Done: Boolean);
begin
    Paste1.Enabled := Clipboard.HasFormat( CF_HDROP );
end;
</code>```

答:
The problem is most likely not the one you think it is.

```<code>Clipboard.HasFormat(CF_HDROP);
</code>```

is probably true even in your FormCreate procedure. Try this with

```<code>procedure TForm1.FormCreate(Sender: TObject);
begin
  if Clipboard.HasFormat(CF_HDROP) then
    ShowMessage('Yes, Rejbrand was right!');
end;
</code>```

The rest of my answer assumes that Paste1 is a TAction, which it should be. But most likely it is a menu item, isn't it? A good advice is to start using the TActionList and TActions.

The problem is most likely that the action isn't redy to be used yet.

After all, SomeAction.Enabled := <something> statements are supposed to be run in the OnUpdate events of the corresponding actions. For instance,

```<code>procedure TForm1.ActionPasteExecute(Sender: TObject);
begin
  RichEdit1.Paste;
end;

procedure TForm1.ActionPasteUpdate(Sender: TObject);
begin
  ActionPaste.Enabled := Clipboard.HasFormat(CF_TEXT);
end;
</code>```

The OnUpdate event is executed exactly when the status of the action needs to be determined, e.g. when a popup menu containing a menu item with the action is shown.

Body:
Why does Clipboard.HasFormat( CF_HDROP ) return false in FormCreate even though the clipboard contains Shell formats?

Edit

procedure TFormMain.FormCreate( Sender: TObject );
begin
  if Clipboard.HasFormat( CF_HDROP ) then
    MessageDlg( 'true', mtInformation, [ mbOK ], 0 )
  else
    MessageDlg( 'false', mtInformation, [ mbOK ], 0 );
end;

This returns false but MyIdleHandler returns true:

Application.OnIdle := MyIdleHandler;

procedure TFormMain.MyIdleHandler(Sender: TObject; var Done: Boolean);
begin
    Paste1.Enabled := Clipboard.HasFormat( CF_HDROP );
end;

Body:
The problem is most likely not the one you think it is.

Clipboard.HasFormat(CF_HDROP);

is probably true even in your FormCreate procedure. Try this with

procedure TForm1.FormCreate(Sender: TObject);
begin
  if Clipboard.HasFormat(CF_HDROP) then
    ShowMessage('Yes, Rejbrand was right!');
end;

The rest of my answer assumes that Paste1 is a TAction, which it should be. But most likely it is a menu item, isn't it? A good advice is to start using the TActionList and TActions.

The problem is most likely that the action isn't redy to be used yet.

After all, SomeAction.Enabled := <something> statements are supposed to be run in the OnUpdate events of the corresponding actions. For instance,

procedure TForm1.ActionPasteExecute(Sender: TObject);
begin
  RichEdit1.Paste;
end;

procedure TForm1.ActionPasteUpdate(Sender: TObject);
begin
  ActionPaste.Enabled := Clipboard.HasFormat(CF_TEXT);
end;

The OnUpdate event is executed exactly when the status of the action needs to be determined, e.g. when a popup menu containing a menu item with the action is shown.


问:
SQL N To No Releationship Table
I have 3 table by this names

Supplier :For store supplier info

SupplierID
Name

1
Supplier 1

2
Supplier 2

3
Supplier 3

4
Supplier 4

Product : For store product info

ProductID
Name

1
Product 1

2
Product 2

3
Product 3

4
Product 4

5
Product 5

SupplierProduct : For store Product that supplier can supply

ProductID
SupplierID

2
1

3
1

4
1

2
2

3
2

4
2

3
3

4
3

1
4

2
4

4
4

I want to write a query that get a bunch of product ID and return the supplier ID that have all this product ID (N:N Relation) for example get product ID 2,3 and return just supplier ID 1,2

答:
You can use intersect as follows:

```<code>select distinct SupplierID
from SupplierProduct
where ProductID = 2
intersect
select SupplierID
from SupplierProduct
where ProductID = 3
</code>```

Fiddle

Title: SQL N To No Releationship Table

Body:
You can use intersect as follows:

select distinct SupplierID
from SupplierProduct
where ProductID = 2
intersect
select SupplierID
from SupplierProduct
where ProductID = 3

Fiddle


问:
Azure Peering Hub and Spoke Overlapping IP ranges possible?
I would like to setup Azure Hub-Spoke architecture with VNET Peering leveraging "transitive capability" with a VPN Gateway (or an Azure Firewall or other network virtual appliance) in the Hub network forwarding traffic between the spokes. I understand that in directly connected VNET-to-VNET peering's the IP ranges cannot overlap each other. However, when there is an Hub in the "middle" can the spokes' IP overlap? I mean, is the use of the Hub "void" the IP overlap constraint?

答:
I have tested in my environment

In Hub and Spoke model architecture in Azure, we cannot have spoke VNETs with overlapping IP addresses

The Spoke VNETs with overlapping IP addresses cannot be peered to the Hub VNET

The Hub cannot void the IP overlap constraint


问:
How pipeline execution time had been calculated in the official guide?
I'm trying to understand how the price estimation works for Azure Data Factory from the official guide, section "Estimating Price - Use Azure Data Factory to migrate data from Amazon S3 to Azure Storage

I managed to understand everything except the 292 hours that are required to complete the migration.

Could you please explain to me how did they get that number?

答:
Firstly, feel free to submit a feedback here with the MS docs team to clarify with an official response on same.

Meanwhile, I see, as they mention "In total, it takes 292 hours to complete  the migration" it would include listing from source, reading from source, writing to sink, other activities, other than the data movement itself.

If we consider approximately, for data volume of 2 PB and aggregate throughput of 2 GBps would give

2PB = 2,097,152 GB BINARY and
Aggregate throughput =
2BGps --> 2,097,152/2 = 1,048,576 secs --> 1,048,576 secs / 3600 =
291.271 hours

Again, these are hypothetical. Further you can refer Plan to manage costs for Azure Data Factory and Understanding Data Factory pricing through examples.


问:
initialise firebase in nodejs expressjs
i want to initialise a firebase (not firebase-admin) instance in Node.

```<code>import { initializeApp } from 'firebase/app';

const firebaseConfig = {
  //...
};

const app = initializeApp(firebaseConfig);
</code>```

this won't work cause node works with commonjs exports and you can't require from firebase cause there is no exports..

答:
https://www.npmjs.com/package/firebase says:

This SDK is intended for end-user client access from environments such
as the Web, mobile Web (e.g. React Native, Ionic), Node.js desktop
(e.g. Electron), or IoT devices running Node.js. If you are instead
interested in using a Node.js SDK which grants you admin access from a
privileged environment (like a server), you should use the Firebase
Admin Node.js SDK.

So use firebase-admin instead if you are planning to use firebase with the backend.

Install with npm install firebase-admin --save

To initialize define a variable export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/service-account-file.json" and

const { initializeApp } = require('firebase-admin/app');
initializeApp()
```

Title: initialise firebase in nodejs expressjs

Body:
i want to initialise a firebase (not firebase-admin) instance in Node.

import { initializeApp } from 'firebase/app';

const firebaseConfig = {
  //...
};

const app = initializeApp(firebaseConfig);

this won't work cause node works with commonjs exports and you can't require from firebase cause there is no exports..


问:
Assigning variables to output parameters in a PostgreSQL trigger
I'm starting a PostgreSQL project, after many years with Sybase and SQL Server, and am new to it's quirks, but so far have been impressed.

I've written a small function that returns OUT parameters. I pass in a clear password and the function returns the encrypted password and a salt. Here it is:

```<code>CREATE OR REPLACE FUNCTION iSecGenPwdSalt(pwdin text, out salt text, out userpassword text)
AS
$BODY$
DECLARE

    BEGIN
        -- Generate a salt...
        salt = gen_salt('bf', 10);

        -- Now generate the password hash...
        userpassword = crypt(pwdin, salt);
    END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;
ALTER FUNCTION iSecGenPwdSalt(text, out text , out text ) OWNER TO postgres;
</code>```

I'd like to call this function within a trigger and use the values to populate the password and salt columns I have, but I can't fathom the syntax. I've tried multiple variations ona theme but I'm still having problems.

select salt, userpassword from iSecGenPwdSalt('mymagicpassword');

Returns it's results beautifully, so I'd like to call this function and get the results into a pair of variables in a trigger so I can assign the values.

Here's my code:

```<code>SELECT usersalt=salt, userpwd=userpassword
  FROM iSecGenPwdSalt(NEW.systemuserpassword);
</code>```

The error I get is thus:

ERROR:  query has no destination for result data
  HINT:  If you want to discard the results of a SELECT, use PERFORM instead.
  CONTEXT:  PL/pgSQL function "isec_trg_systemuser" line 13 at SQL statement

So simply assigning a pair of variables to a resultset derived from OUT parameters in a trigger is causing me grief.

答:
This isn't really an answer to the question you're asking, but I had to do a similar thing recently, and I did it with a view and rules instead of triggers. I hope this is helpful despite not really being an answer to the question your asked directly.

Here is my user table and view:

```<code>CREATE TABLE users_t (
  username VARCHAR(16) PRIMARY KEY,
  email    VARCHAR UNIQUE,
  password CHAR(60),
  salt     CHAR(29)
);

CREATE VIEW users AS SELECT username, email, '********'::varchar AS password FROM users_t;
</code>```

The insert rule takes care of generating the salt value:

```<code>CREATE RULE users_insert_rule AS ON INSERT TO users DO INSTEAD
INSERT INTO users_t (username, email, password, salt)
  SELECT new.username, new.email, crypt(new.password, salt.salt), salt.salt
  FROM (SELECT gen_salt('bf') as salt) salt
RETURNING username, email, '********'::varchar;
</code>```

For completeness I'm including the update and delete rules, even though they aren't especially relevant:

```<code>CREATE RULE users_update_rule AS ON UPDATE TO users DO INSTEAD
  UPDATE users_t
  SET
    username = new.username,
    email = new.email,
    password = crypt(new.password, salt)
RETURNING username, email, '********'::varchar;

CREATE RULE users_delete_rule AS ON DELETE TO users DO INSTEAD
  DELETE FROM users_t WHERE username = old.username
RETURNING username, email, '********'::varchar;
</code>```

Then I wrote an authentication function which takes care of using the salt:

```<code>CREATE OR REPLACE FUNCTION authenticate(varchar, varchar) RETURNS setof users AS $$
SELECT * FROM users
WHERE username =
  (SELECT username FROM users_t
   WHERE username = $1 AND crypt($2, salt) = password)
$$ LANGUAGE sql;
</code>```

So you can "log in" by querying SELECT * FROM authenticate('username', 'password'); and your users are created by inserting into the users view. You can set the permissions such that you have an unprivileged role that can see the users view but not the underlying users_t table. This way you have an easy to interface with users table with salted passwords without having to deal with the salt in the application.

Body:
I'm starting a PostgreSQL project, after many years with Sybase and SQL Server, and am new to it's quirks, but so far have been impressed.

I've written a small function that returns OUT parameters. I pass in a clear password and the function returns the encrypted password and a salt. Here it is:

CREATE OR REPLACE FUNCTION iSecGenPwdSalt(pwdin text, out salt text, out userpassword text)
AS
$BODY$
DECLARE

    BEGIN
        -- Generate a salt...
        salt = gen_salt('bf', 10);

        -- Now generate the password hash...
        userpassword = crypt(pwdin, salt);
    END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;
ALTER FUNCTION iSecGenPwdSalt(text, out text , out text ) OWNER TO postgres;

I'd like to call this function within a trigger and use the values to populate the password and salt columns I have, but I can't fathom the syntax. I've tried multiple variations ona theme but I'm still having problems.

select salt, userpassword from iSecGenPwdSalt('mymagicpassword');

Returns it's results beautifully, so I'd like to call this function and get the results into a pair of variables in a trigger so I can assign the values.

Here's my code:

SELECT usersalt=salt, userpwd=userpassword
  FROM iSecGenPwdSalt(NEW.systemuserpassword);

The error I get is thus:

ERROR:  query has no destination for result data
  HINT:  If you want to discard the results of a SELECT, use PERFORM instead.
  CONTEXT:  PL/pgSQL function "isec_trg_systemuser" line 13 at SQL statement

So simply assigning a pair of variables to a resultset derived from OUT parameters in a trigger is causing me grief.

Body:
This isn't really an answer to the question you're asking, but I had to do a similar thing recently, and I did it with a view and rules instead of triggers. I hope this is helpful despite not really being an answer to the question your asked directly.

Here is my user table and view:

CREATE TABLE users_t (
  username VARCHAR(16) PRIMARY KEY,
  email    VARCHAR UNIQUE,
  password CHAR(60),
  salt     CHAR(29)
);

CREATE VIEW users AS SELECT username, email, '********'::varchar AS password FROM users_t;

The insert rule takes care of generating the salt value:

CREATE RULE users_insert_rule AS ON INSERT TO users DO INSTEAD
INSERT INTO users_t (username, email, password, salt)
  SELECT new.username, new.email, crypt(new.password, salt.salt), salt.salt
  FROM (SELECT gen_salt('bf') as salt) salt
RETURNING username, email, '********'::varchar;

For completeness I'm including the update and delete rules, even though they aren't especially relevant:

CREATE RULE users_update_rule AS ON UPDATE TO users DO INSTEAD
  UPDATE users_t
  SET
    username = new.username,
    email = new.email,
    password = crypt(new.password, salt)
RETURNING username, email, '********'::varchar;

CREATE RULE users_delete_rule AS ON DELETE TO users DO INSTEAD
  DELETE FROM users_t WHERE username = old.username
RETURNING username, email, '********'::varchar;

Then I wrote an authentication function which takes care of using the salt:

CREATE OR REPLACE FUNCTION authenticate(varchar, varchar) RETURNS setof users AS $$
SELECT * FROM users
WHERE username =
  (SELECT username FROM users_t
   WHERE username = $1 AND crypt($2, salt) = password)
$$ LANGUAGE sql;

So you can "log in" by querying SELECT * FROM authenticate('username', 'password'); and your users are created by inserting into the users view. You can set the permissions such that you have an unprivileged role that can see the users view but not the underlying users_t table. This way you have an easy to interface with users table with salted passwords without having to deal with the salt in the application.


问:
how to get the pure text and selected option in a p-tag?
After selecting 5 and 2, does any solution for how could get a string output like: 5 greater than 2 ?

  <select size="2">
    <option>1</option>
    <option>2</option>
    <option>3</option>
    <option>4</option>
    <option>5</option>
  </select>

 greater than

  <select size="1">
    <option>1</option>
    <option>2</option>
    <option>3</option>
    <option>4</option>
    <option>5</option>
  </select>

```

答:
Is this what you want?

function showText(ele) {
  document.getElementById("2").innerHTML = document.getElementById("1").options[document.getElementById("1").selectedIndex].text+" is greater than "+ele.options[ele.selectedIndex].text;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p class="showTxt" id="showTxt">

  <select size="2" id="1">
    <option>1</option>
    <option>2</option>
    <option>3</option>
    <option>4</option>
    <option>5</option>
  </select>
  <p> greater than</p>
  <select size="1" onchange="showText(this)">
    <option>1</option>
    <option>2</option>
    <option>3</option>
    <option>4</option>
    <option>5</option>
  </select>
</p>
<p id="2"></p></code>```

Body:
Is this what you want?

function showText(ele) {
  document.getElementById("2").innerHTML = document.getElementById("1").options[document.getElementById("1").selectedIndex].text+" is greater than "+ele.options[ele.selectedIndex].text;
}

<p class="showTxt" id="showTxt">

  <select size="2" id="1">
    <option>1</option>
    <option>2</option>
    <option>3</option>
    <option>4</option>
    <option>5</option>
  </select>
  <p> greater than</p>
  <select size="1" onchange="showText(this)">
    <option>1</option>
    <option>2</option>
    <option>3</option>
    <option>4</option>
    <option>5</option>
  </select>
</p>
<p id="2"></p>


问:
How to get a list records in 1c from JSON data
I get JSON data in 1C from the address written below. There is no problem when there is only one registration. But I cannot list many records. It gives an error "Object field not found (Key)." What do I have to do to list the records? Help, please.</p>
```<code>              Host     = "jsonplaceholder.typicode.com/";
          HTTPRequest = New HTTPRequest;
              // HTTPRequest.ResourceAddress = "todos/1";
               HTTPRequest.ResourceAddress = "photos/" ;// ThisObject.Attribute2;
               HTTPConnection         = New HTTPConnection(host,,,,,10,New OpenSSLSecureConnection);
               HTTPAnswer               = HTTPConnection.Get(HTTPRequest);
               stringAnswer= HTTPAnswer.GetBodyAsString();
               JSONReader = New JSONReader;
               JSONReader.SetString(stringAnswer);
               JsonResult = ReadJson(JSONReader,True);

                For each strResult in JsonResult Do
                    If (strResult.Key = "url") Then
                        Message(strResult.Value);
                     EndIf;
               EndDo;
</code>```

答:
Your code should be like this:

Host     = "jsonplaceholder.typicode.com/";

HTTPRequest = New HTTPRequest;

HTTPRequest.ResourceAddress = "photos/" ;

HTTPConnection   = New HTTPConnection(host,,,,,10,New OpenSSLSecureConnection);

HTTPAnswer      = HTTPConnection.Get(HTTPRequest);

stringAnswer   = HTTPAnswer.GetBodyAsString();

JSONReader       = New JSONReader;

JSONReader.SetString(stringAnswer);

JsonResult = ReadJson(JSONReader,True);

```<code>  For each strResult in JsonResult Do

  For Each curElement In strResult Do

     If (curElement.Key = "url") Then

        Message(curElement.Value);

        Break; // since the value curElement.Key = "url" can be only once, we can exit the loop

     EndIf;

  EndDo;
</code>```

 EndDo;

JsonResult is an array of values (see scr.1). Each element of the array is a map strResult (scr.2). First, in a loop, we iterate over all the elements of the array, and in a nested loop, we iterate over the matching fields.

Body:
I get JSON data in 1C from the address written below. There is no problem when there is only one registration. But I cannot list many records. It gives an error "Object field not found (Key)." What do I have to do to list the records? Help, please.

              Host     = "jsonplaceholder.typicode.com/";
          HTTPRequest = New HTTPRequest;
              // HTTPRequest.ResourceAddress = "todos/1";
               HTTPRequest.ResourceAddress = "photos/" ;// ThisObject.Attribute2;
               HTTPConnection         = New HTTPConnection(host,,,,,10,New OpenSSLSecureConnection);
               HTTPAnswer               = HTTPConnection.Get(HTTPRequest);
               stringAnswer= HTTPAnswer.GetBodyAsString();
               JSONReader = New JSONReader;
               JSONReader.SetString(stringAnswer);
               JsonResult = ReadJson(JSONReader,True);

                For each strResult in JsonResult Do
                    If (strResult.Key = "url") Then
                        Message(strResult.Value);
                     EndIf;
               EndDo;

Body:
Your code should be like this:

Host     = "jsonplaceholder.typicode.com/";

HTTPRequest = New HTTPRequest;

HTTPRequest.ResourceAddress = "photos/" ;

HTTPConnection   = New HTTPConnection(host,,,,,10,New OpenSSLSecureConnection);

HTTPAnswer      = HTTPConnection.Get(HTTPRequest);

stringAnswer   = HTTPAnswer.GetBodyAsString();

JSONReader       = New JSONReader;

JSONReader.SetString(stringAnswer);

JsonResult = ReadJson(JSONReader,True);

  For each strResult in JsonResult Do

  For Each curElement In strResult Do

     If (curElement.Key = "url") Then

        Message(curElement.Value);

        Break; // since the value curElement.Key = "url" can be only once, we can exit the loop

     EndIf;

  EndDo;

 EndDo;

JsonResult is an array of values (see scr.1). Each element of the array is a map strResult (scr.2). First, in a loop, we iterate over all the elements of the array, and in a nested loop, we iterate over the matching fields.


问:
manpath: can't set the locale; make sure $LC_* and $LANG are correct
I just installed terminator terminal emulator on my linux mint. for some reason I don't understand, it sets my password to some of the locale options. I've tried several things but they only offer a temporary fix. each time I open the terminal, it resets the locale options to my password.

```<code>LANG=koldenod19*
LANGUAGE=
LC_CTYPE="mypassword"
LC_NUMERIC=om_KE.UTF-8
LC_TIME="mypassword"
LC_COLLATE="mypassword"
LC_MONETARY=om_KE.UTF-8
LC_MESSAGES="mypassword"
LC_PAPER=om_KE.UTF-8
LC_NAME=om_KE.UTF-8
LC_ADDRESS=om_KE.UTF-8
LC_TELEPHONE=om_KE.UTF-8
LC_MEASUREMENT=om_KE.UTF-8
LC_IDENTIFICATION=om_KE.UTF-8
LC_ALL=
</code>```

I've tried using sudo dpkg-reconfigure locales and export LC_ALL="eo_US.utf8" and the problem still persists.

答:
RedHat: Change /etc/locale.conf to</p>
```<code>LANG=en_US.UTF-8
LC_ALL=en_US.utf-8
</code>```

Body:
I just installed terminator terminal emulator on my linux mint. for some reason I don't understand, it sets my password to some of the locale options. I've tried several things but they only offer a temporary fix. each time I open the terminal, it resets the locale options to my password.

LANG=koldenod19*
LANGUAGE=
LC_CTYPE="mypassword"
LC_NUMERIC=om_KE.UTF-8
LC_TIME="mypassword"
LC_COLLATE="mypassword"
LC_MONETARY=om_KE.UTF-8
LC_MESSAGES="mypassword"
LC_PAPER=om_KE.UTF-8
LC_NAME=om_KE.UTF-8
LC_ADDRESS=om_KE.UTF-8
LC_TELEPHONE=om_KE.UTF-8
LC_MEASUREMENT=om_KE.UTF-8
LC_IDENTIFICATION=om_KE.UTF-8
LC_ALL=

I've tried using sudo dpkg-reconfigure locales and export LC_ALL="eo_US.utf8" and the problem still persists.

Body:
RedHat: Change /etc/locale.conf to

LANG=en_US.UTF-8
LC_ALL=en_US.utf-8


问:
rails 3, undefined method `eq' for nil:NilClass
i'm create scaffold pucgrupo

```<code>rails g scaffold pucgrupo numero:integer clase_id:integer nombre:string
</code>```

after edit my migration

```<code>class CreatePucgrupos < ActiveRecord::Migration
  def self.up
    create_table :pucgrupos , :id => false do |t|
      t.integer :numero
      t.integer :clase_id
      t.string :nombre

      t.timestamps
    end
  end

  def self.down
    drop_table :pucgrupos
  end
end
</code>```

and eject the migration

```<code>rake db:migrate
</code>```

after when I try to create a group I get this error:

```<code>NoMethodError in PucgruposController#show

undefined method `eq' for nil:NilClass
Rails.root: /home/andres/desarrollos/rubyonrails/proyecto

Application Trace | Framework Trace | Full Trace
app/controllers/pucgrupos_controller.rb:16:in `show'
Request

Parameters:

{"id"=>"0"}
</code>```

i think that is for column does not exist "id" any ideas ?

1 edit

i'm edit migration primary_key numero:

```<code>class CreatePucgrupos < ActiveRecord::Migration
  def self.up
    create_table :pucgrupos, :id => false , :primary_key => :numero do |t|
      t.integer :numero
      t.integer :clase_id
      t.string :nombre
      t.timestamps
    end
  end

  def self.down
    drop_table :pucgrupos
  end
end
</code>```

the data insert into table, but get the same error.

2 edit

edit migration:

```<code>create_table :pucgrupos, :primary_key => :numero do |t|
  t.integer :numero
  t.integer :clase_id
  t.string :nombre
  t.timestamps
end
</code>```

the error display page is:

```<code>NoMethodError in PucgruposController#show

undefined method `eq' for nil:NilClass
Rails.root: /home/andres/desarrollos/rubyonrails/proyecto

Application Trace | Framework Trace | Full Trace
app/controllers/pucgrupos_controller.rb:16:in `show'
Request

Parameters:

{"id"=>"1"}
</code>```

3 edit

i'm edit pucgrupos_controller.rb methos show is

```<code>  def show
    @pucgrupo = Pucgrupo.find_by_numero(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @pucgrupo }
    end
  end
</code>```

the error display page

```<code>ActionController::RoutingError in Pucgrupos#index

Showing /home/andres/desarrollos/rubyonrails/proyecto/app/views/pucgrupos/index.html.erb where line #18 raised:

No route matches {:controller=>"pucgrupos", :action=>"show", :id=>#<Pucgrupo numero: 1, clase_id: 2, nombre: "aaa", created_at: "2011-08-18 17:13:07", updated_at: "2011-08-18 17:13:07">}
Extracted source (around line #18):

15:     <td><%= pucgrupo.numero %></td>
16:     <td><%= pucgrupo.clase_id %></td>
17:     <td><%= pucgrupo.nombre %></td>
18:     <td><%= link_to 'Show', pucgrupo %></td>
19:     <td><%= link_to 'Edit', edit_pucgrupo_path(pucgrupo) %></td>
20:     <td><%= link_to 'Destroy', pucgrupo, :confirm => 'Are you sure?', :method => :delete %></td>
21:   </tr>
</code>```

i'm enter rails console and typing

```<code>Pucgrupo.find_by_numero(1)
=> #<Pucgrupo numero: 1, clase_id: 2, nombre: "aaa", created_at: "2011-08-18 17:13:07", updated_at: "2011-08-18 17:13:07">
</code>```

答:
Well.  You aren't creating an id column.  If you want one, remove the following line

```<code>:id => false
</code>```

See more here, under options for create_table

:id

Whether to automatically add a primary key column. Defaults to true. Join tables for has_and_belongs_to_many should set it to false.

Body:
i'm create scaffold pucgrupo

rails g scaffold pucgrupo numero:integer clase_id:integer nombre:string

after edit my migration

class CreatePucgrupos < ActiveRecord::Migration
  def self.up
    create_table :pucgrupos , :id => false do |t|
      t.integer :numero
      t.integer :clase_id
      t.string :nombre

      t.timestamps
    end
  end

  def self.down
    drop_table :pucgrupos
  end
end

and eject the migration

rake db:migrate

after when I try to create a group I get this error:

NoMethodError in PucgruposController#show

undefined method `eq' for nil:NilClass
Rails.root: /home/andres/desarrollos/rubyonrails/proyecto

Application Trace | Framework Trace | Full Trace
app/controllers/pucgrupos_controller.rb:16:in `show'
Request

Parameters:

{"id"=>"0"}

i think that is for column does not exist "id" any ideas ?

1 edit

i'm edit migration primary_key numero:

class CreatePucgrupos < ActiveRecord::Migration
  def self.up
    create_table :pucgrupos, :id => false , :primary_key => :numero do |t|
      t.integer :numero
      t.integer :clase_id
      t.string :nombre
      t.timestamps
    end
  end

  def self.down
    drop_table :pucgrupos
  end
end

the data insert into table, but get the same error.

2 edit

edit migration:

create_table :pucgrupos, :primary_key => :numero do |t|
  t.integer :numero
  t.integer :clase_id
  t.string :nombre
  t.timestamps
end

the error display page is:

NoMethodError in PucgruposController#show

undefined method `eq' for nil:NilClass
Rails.root: /home/andres/desarrollos/rubyonrails/proyecto

Application Trace | Framework Trace | Full Trace
app/controllers/pucgrupos_controller.rb:16:in `show'
Request

Parameters:

{"id"=>"1"}

3 edit

i'm edit pucgrupos_controller.rb methos show is

  def show
    @pucgrupo = Pucgrupo.find_by_numero(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @pucgrupo }
    end
  end

the error display page

ActionController::RoutingError in Pucgrupos#index

Showing /home/andres/desarrollos/rubyonrails/proyecto/app/views/pucgrupos/index.html.erb where line #18 raised:

No route matches {:controller=>"pucgrupos", :action=>"show", :id=>#<Pucgrupo numero: 1, clase_id: 2, nombre: "aaa", created_at: "2011-08-18 17:13:07", updated_at: "2011-08-18 17:13:07">}
Extracted source (around line #18):

15:     <%= pucgrupo.numero %>
16:     <%= pucgrupo.clase_id %>
17:     <%= pucgrupo.nombre %>
18:     <%= link_to 'Show', pucgrupo %>
19:     <%= link_to 'Edit', edit_pucgrupo_path(pucgrupo) %>
20:     <%= link_to 'Destroy', pucgrupo, :confirm => 'Are you sure?', :method => :delete %>
21:

i'm enter rails console and typing

Pucgrupo.find_by_numero(1)
=> #<Pucgrupo numero: 1, clase_id: 2, nombre: "aaa", created_at: "2011-08-18 17:13:07", updated_at: "2011-08-18 17:13:07">

Body:
Well.  You aren't creating an id column.  If you want one, remove the following line

:id => false

See more here, under options for create_table

:id

Whether to automatically add a primary key column. Defaults to true. Join tables for has_and_belongs_to_many should set it to false.