问:
Function not sending alert in browser HTML, JavaScript
Newbie to HTML and Javascript here.

I am coding up a very basic program that allows a user to enter a card number and the browser should say if it is a valid number (between 13-16 digits) or not.

The website pulls up and shows everything I want it to, but when a number is entered (valid or invalid) the alert is not sent to say if the number was good or not.

Any suggestions on how I can fix this?

```<code><!doctype html>

<html lang="en">
<head>
  <meta charset="utf-8">
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <title>Card Reader</title>
  <link type=’text/css’/>
  <script>
    'use strict';
    function getNumber(cardNum) {
        if (cardNum.length > 16 || cardNum.length < 13) {
            alert(‘This is not valid.’);
            return false;}
        else {
            alert(‘This is valid.’);
            return true;}
    }
  </script>
</head>

<body onload=“document.cardNum()”>

<h4> Enter Credit Card Number: </h4>
<form>
    <input type='text' id=‘cardNum’ name=‘cardNum’/>
    <br>
    <input type="submit" value=Submit onclick = “getNumber(cardNum)”/>
</form>

</body>
</html>
</code>```

答:
There was 3 things i fixed;
1- onload=“document.cardNum()” , there is no function like that so your page crashes immediately so no further script executes
2- I dont know if it is spoilt during paste but some of your quotes are not valid, you should use " and '
3- This one just prevents working right; In your function you pass input's reference and check HTML element's length you need to check input's value

<!doctype html>

  <meta charset="utf-8">
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <title>Card Reader</title>
  <link type=’text/css’/>

 Enter Credit Card Number:

<form>
    <input type='text' id="cardNum" name="cardNum"/>

    <input type="submit" value=Submit onclick = "getNumber(cardNum)"/>
</form>

```

Body:
Newbie to HTML and Javascript here.

I am coding up a very basic program that allows a user to enter a card number and the browser should say if it is a valid number (between 13-16 digits) or not.

The website pulls up and shows everything I want it to, but when a number is entered (valid or invalid) the alert is not sent to say if the number was good or not.

Any suggestions on how I can fix this?

<!doctype html>

  <meta charset="utf-8">
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <title>Card Reader</title>
  <link type=’text/css’/>

 Enter Credit Card Number:

<form>
    <input type='text' id=‘cardNum’ name=‘cardNum’/>

    <input type="submit" value=Submit onclick = “getNumber(cardNum)”/>
</form>

Body:
There was 3 things i fixed;
1- onload=“document.cardNum()” , there is no function like that so your page crashes immediately so no further script executes
2- I dont know if it is spoilt during paste but some of your quotes are not valid, you should use " and '
3- This one just prevents working right; In your function you pass input's reference and check HTML element's length you need to check input's value

<!doctype html>

<html lang="en">
<head>
  <meta charset="utf-8">
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <title>Card Reader</title>
  <link type=’text/css’/>
  <script>
    function getNumber(cardNum) {
        if (cardNum.value.length > 16 || cardNum.value.length < 13) {
            alert("This is not valid.");
            return false;}
        else {
            alert("This is valid.");
            return true;}
    }
  </script>
</head>

<body>

<h4> Enter Credit Card Number: </h4>
<form>
    <input type='text' id="cardNum" name="cardNum"/>
    <br>
    <input type="submit" value=Submit onclick = "getNumber(cardNum)"/>
</form>

</body>
</html>


来源: stackexchange

问:
Why does this python bs4&csv writer code write in BOM?
I am extracting a multi-language table from HTML with bs4 and save it as csv.
But whatever I do with encoding=utf-8, I have the same result of getting a BOM written csv file.
Is there any easy way to change it using simple options when scraping and saving the HTML?
(I changed utf-8 to euc-** options since the target website is written in multinational languages but it was in vain)</p>

```<code>soup=bs(res.text,'html.parser',from_encoding='utf8')

    resultset = soup.find('table',class_="type_12345")

    print(resultset)
    records=[]
    for tr in resultset.find_all('tr'):
        tds = tr.find_all('td')
        #url = tds[2].a.get('href')
        records.append([elem.text.encode('utf8') for elem in tds])

    with open('whystillBOM.csv', 'a',encoding="utf-8-sig") as f:
        writer = csv.writer(f)
        writer.writerows(records)
</code>```

答:
'utf-8-sig' encoding automatically writes the BOM for Microsoft's version of UTF-8.  If you don't want the BOM, just use UTF-8.

If there's a possibility that the files that you are reading contain a BOM, then you can decode them as utf-8-sig and standard UTF-8 will still be decoded without error.

ContentLicense: CC BY-SA 4.0

Body:
I am extracting a multi-language table from HTML with bs4 and save it as csv.
But whatever I do with encoding=utf-8, I have the same result of getting a BOM written csv file.
Is there any easy way to change it using simple options when scraping and saving the HTML?
(I changed utf-8 to euc-** options since the target website is written in multinational languages but it was in vain)

soup=bs(res.text,'html.parser',from_encoding='utf8')

    resultset = soup.find('table',class_="type_12345")

    print(resultset)
    records=[]
    for tr in resultset.find_all('tr'):
        tds = tr.find_all('td')
        #url = tds[2].a.get('href')
        records.append([elem.text.encode('utf8') for elem in tds])

    with open('whystillBOM.csv', 'a',encoding="utf-8-sig") as f:
        writer = csv.writer(f)
        writer.writerows(records)


问:
Json parsing with dotted path in python
Is there any python library (PyPI) available from which I can parse json with :

```<code>1.  dot separated path
2.  order independant in case of array
</code>```

Data :

```<code>  "attr1": [
    {
      "attr2": "val2"
    },
    {
      "attr3": {
        "attr4": "val4"
      }
    }
  ]
}
</code>```

Here, I am having path such as 'attr1.attr3.attr4'. From which I need to get value 'val4'.
With the use of dotty dict library, I must provide position in case of array: 'attr1.1.attr3.attr4'. But position can vary. It may possible that 'attr3' comes first in 'attr1'.

So, is there any library available which can provide

```<code>1.  'val4' when I pass 'attr1.attr3.attr4' path  (Not 'attr1.1.attr3.attr4')
2.  'val2' when I pass 'attr1.attr2' (Not 'attr1.0.attr2')
</code>```

答:
I have created a function which would parse the string that you provide it to with the dictionary object. Hope it helps you.

The advantage here is, you never parse the whole dictionary and just get the values that are required. for example if you wanted to access 4 keys separated by . then complexity will be 4. It will always return the result in o(n) where n is the number of keys.

```<code>def get_value(dotted_str, dict_obj):
    names = dotted_str.split('.')
    current_level = dict_obj
    for index, name in enumerate(names):
        if index:
            if isinstance(current_level, list):
                current_level = current_level[int(name)]
            else:
                current_level = current_level[name]
    return current_level

a_dict = {"a": {"this": 100, "is": 500, "nested": [{"first": 0}, {"second": ["I", "am", "list"]}]}, "b": [1, 2, 3, 4]}
get_value("a_dict.a.nested.1.second", a_dict)
</code>```

Output of above code is:

```<code>['I', 'am', 'list']
</code>```

Title: Json parsing with dotted path in python

Body:
Is there any python library (PyPI) available from which I can parse json with :

1.  dot separated path
2.  order independant in case of array

Data :

  "attr1": [
    {
      "attr2": "val2"
    },
    {
      "attr3": {
        "attr4": "val4"
      }
    }
  ]
}

Here, I am having path such as 'attr1.attr3.attr4'. From which I need to get value 'val4'.
With the use of dotty dict library, I must provide position in case of array: 'attr1.1.attr3.attr4'. But position can vary. It may possible that 'attr3' comes first in 'attr1'.

So, is there any library available which can provide

1.  'val4' when I pass 'attr1.attr3.attr4' path  (Not 'attr1.1.attr3.attr4')
2.  'val2' when I pass 'attr1.attr2' (Not 'attr1.0.attr2')

Body:
I have created a function which would parse the string that you provide it to with the dictionary object. Hope it helps you.

The advantage here is, you never parse the whole dictionary and just get the values that are required. for example if you wanted to access 4 keys separated by . then complexity will be 4. It will always return the result in o(n) where n is the number of keys.

def get_value(dotted_str, dict_obj):
    names = dotted_str.split('.')
    current_level = dict_obj
    for index, name in enumerate(names):
        if index:
            if isinstance(current_level, list):
                current_level = current_level[int(name)]
            else:
                current_level = current_level[name]
    return current_level

a_dict = {"a": {"this": 100, "is": 500, "nested": [{"first": 0}, {"second": ["I", "am", "list"]}]}, "b": [1, 2, 3, 4]}
get_value("a_dict.a.nested.1.second", a_dict)

Output of above code is:

['I', 'am', 'list']


问:
Error: Property [kpi_description] does not exist on this collection instancein Laravel
In my Laravel-5.8 project, I have this code:

Controller

```<code>public function index()
{
  $userEmployee = Auth::user()->employee_id;
  $goals = AppraisalGoal::where('employee_id', $userEmployee)->get();

  return view('appraisal.appraisal_goals.index')->with('goals', $goals);
}
</code>```

model

```<code>class AppraisalGoal extends Model
{
  protected $table = 'appraisal_goals';
  protected $primaryKey = 'id';

  protected $fillable = [
              'weighted_score',
              'employee_comment',
              'goal_title',
          ];

  public function appraisalgoaldetail(){
    return $this->hasMany('App\Models\Appraisal\AppraisalGoalDetail');
  }
}

class AppraisalGoalDetail extends Model
{
 protected $table = 'appraisal_goal_details';
 protected $fillable = [
              'kpi_description',
          ];

 public function appraisalgoal()
 {
    return $this->belongsTo('App\Models\Appraisal\AppraisalGoal');
}
}
</code>```

the function appraisalgoaldetail() is hasMany relationtionship.

view

```<code> @foreach($goals as $key => $goal)
    <td>
      {{$key+1}}
    </td>
    <td>
      {{$goal->appraisalgoaldetail->kpi_description ?? '' }}
    </td>
    <td>
       {{$goal->goal_title ?? '' }}
    </td>
 @endforeach
</code>```

When I ran the code, I got this error:

Property [kpi_description] does not exist on this collection instance. (View: C:\xampp\htdocs\accly\resources\views\appraisal_goals\index.blade.php)

How do I resolve it?

Thank you

答:
Here you written HasMany relation with AppraisalGoal and AppraisalGoalDetail.
So
$goal->appraisalgoaldetail
 will be resulted in an array. As a result you are trying to get the kpi_description from an array. I think this is the problem you are facing.

For find out the problem try

```<code>@foreach($goals as $key => $goal)
<td>
  {{$key+1}}
</td>
<td>
  {{$goal->appraisalgoaldetail[0]['kpi_description'] ?? '' }}
</td>
<td>
   {{$goal->goal_title ?? '' }}
</td>
@endforeach
</code>```

Or use a foreach like

```<code>@foreach($goals as $key => $goal)
<td>
  {{$key+1}}
</td>
<td>
  @foreach($goal->appraisalgoaldetail as $app)
    <div>{{ $app->appraisalgoaldetail }}</div>
  @endforeach
</td>
<td>
   {{$goal->goal_title ?? '' }}
</td>

@endforeach
</code>```

Body:
In my Laravel-5.8 project, I have this code:

Controller

public function index()
{
  $userEmployee = Auth::user()->employee_id;
  $goals = AppraisalGoal::where('employee_id', $userEmployee)->get();

  return view('appraisal.appraisal_goals.index')->with('goals', $goals);
}

model

class AppraisalGoal extends Model
{
  protected $table = 'appraisal_goals';
  protected $primaryKey = 'id';

  protected $fillable = [
              'weighted_score',
              'employee_comment',
              'goal_title',
          ];

  public function appraisalgoaldetail(){
    return $this->hasMany('App\Models\Appraisal\AppraisalGoalDetail');
  }
}

class AppraisalGoalDetail extends Model
{
 protected $table = 'appraisal_goal_details';
 protected $fillable = [
              'kpi_description',
          ];

 public function appraisalgoal()
 {
    return $this->belongsTo('App\Models\Appraisal\AppraisalGoal');
}
}

the function appraisalgoaldetail() is hasMany relationtionship.

view

 @foreach($goals as $key => $goal)

      {{$key+1}}

      {{$goal->appraisalgoaldetail->kpi_description ?? '' }}

       {{$goal->goal_title ?? '' }}

 @endforeach

When I ran the code, I got this error:

Property [kpi_description] does not exist on this collection instance. (View: C:\xampp\htdocs\accly\resources\views\appraisal_goals\index.blade.php)

How do I resolve it?

Thank you

Body:
Here you written HasMany relation with AppraisalGoal and AppraisalGoalDetail.
So
$goal->appraisalgoaldetail
 will be resulted in an array. As a result you are trying to get the kpi_description from an array. I think this is the problem you are facing.

For find out the problem try

@foreach($goals as $key => $goal)
<td>
  {{$key+1}}
</td>
<td>
  {{$goal->appraisalgoaldetail[0]['kpi_description'] ?? '' }}
</td>
<td>
   {{$goal->goal_title ?? '' }}
</td>
@endforeach

Or use a foreach like

@foreach($goals as $key => $goal)
<td>
  {{$key+1}}
</td>
<td>
  @foreach($goal->appraisalgoaldetail as $app)
    <div>{{ $app->appraisalgoaldetail }}</div>
  @endforeach
</td>
<td>
   {{$goal->goal_title ?? '' }}
</td>

@endforeach


问:
Can I use Linq syntax for join queries in sqlite-net-pcl?
So I have a query

```<code>var query = "SELECT * " +
    " FROM OptionItem i" +
    " INNER JOIN Account_OptionList_OptionItem j" +
    " ON i.Id = j.Item_Id" +
    $" WHERE j.Account_Id={accountId}" +
    $" AND j.List_Id={listId}";

return _database.Query<OptionItem>(query);
</code>```

I feel safer using linq syntax (so compiler tells me if I mucked up). But when I try this:

```<code>return from i in _database.Table<OptionItem>()
        join j in _database.Table<Account_OptionList_OptionItem>()
        on i.Id equals j.Item_Id
        where j.Account_Id == accountId
        && j.List_Id == listId
        select i;
</code>```

or this:

```<code>return _database.Table<Account_OptionList_OptionItem>()
    .Where(x => x.Account_Id == accountId && x.List_Id == listId)
    .Join(_database.Table<OptionItem>().Where(x => x.Group_Id == listId),
        join => join.Item_Id,
        item => item.Id,
        (join, inner) => inner);
</code>```

It takes a lot longer (I think it pulls the table into memory and then just uses System.Linq). Is there a way to use Linq syntax without getting a performance hit? (is there a library that supports this?)

EDIT: I'm using the nuget package:
https://www.nuget.org/packages/sqlite-net-pcl/

答:
It depends on your ORM and Database, however in most cases the syntax is the same.
But it's not clear what do you wanna select and what is your model.
If you could provide your model I can help.</p>

Body:
So I have a query

var query = "SELECT * " +
    " FROM OptionItem i" +
    " INNER JOIN Account_OptionList_OptionItem j" +
    " ON i.Id = j.Item_Id" +
    $" WHERE j.Account_Id={accountId}" +
    $" AND j.List_Id={listId}";

return _database.Query<OptionItem>(query);

I feel safer using linq syntax (so compiler tells me if I mucked up). But when I try this:

return from i in _database.Table<OptionItem>()
        join j in _database.Table<Account_OptionList_OptionItem>()
        on i.Id equals j.Item_Id
        where j.Account_Id == accountId
        && j.List_Id == listId
        select i;

or this:

return _database.Table<Account_OptionList_OptionItem>()
    .Where(x => x.Account_Id == accountId && x.List_Id == listId)
    .Join(_database.Table<OptionItem>().Where(x => x.Group_Id == listId),
        join => join.Item_Id,
        item => item.Id,
        (join, inner) => inner);

It takes a lot longer (I think it pulls the table into memory and then just uses System.Linq). Is there a way to use Linq syntax without getting a performance hit? (is there a library that supports this?)

EDIT: I'm using the nuget package:
https://www.nuget.org/packages/sqlite-net-pcl/


问:
How to fetch the entire JSON array based on index using simple JSON Library
I just have the below format of JSON request: (The original JSON is huge so sharing the sample from blog)

Sample Request:

```<code>{
  "testData": [
    {
      "firstName": "Lokesh",
      "lastName": "Gupta",
      "website": "howtodoinjava.com"
    },
    {
      "firstName": "Brian",
      "lastName": "Schultz",
      "website": "example.com"
    }
  ]
}
</code>```

I just have below method which should get the each index of the above JSONArray. The above request should return size() == 2. And I just want to print the entire array[0], and array[1] in each iteration as like below.

```<code>public static void constructJSON(CheckoutDTO result)throws Exception
    {
        String jsonBody = result.getJson();
        JSONObject object = parseAndReturnObj(jsonBody);
        JSONArray array= (JSONArray) object.get("testData");
        int index=0;
        for(int i=0;i<array.size();i++)
        {
            index++;
            JSONObject objects = (JSONObject) array.get("");

            Sysout(objects); // Here I just want to print the array[0] index as entire JSONObject.
            }

        }
    }
</code>```

The above code I just want to print the each index of the array. Like the first iteration I just want to print below:

array[0]:

```<code>  {
        "firstName": "Lokesh",
        "lastName": "Gupta",
        "website": "howtodoinjava.com"
  }
</code>```

Second Iteration It should print below:

array[1]:

```<code>     {
            "firstName": "Brian",
            "lastName": "Schultz",
            "website": "example.com"
     }
</code>```

The above request may have "n" number of array[n]. I just want to print the Systout(Objects) in the for loop as above format.

Using Simple json library to read the JSONObject.

```<code>   <dependency>
        <groupId>com.googlecode.json-simple</groupId>
        <artifactId>json-simple</artifactId>
    </dependency>
</code>```

Can anyone help me to achieve this?

答:
You can simply write System.out.println(object);. JSONObject's toString() method will automatically convert it to json. Your for loop can be modified as

```<code>for (int i = 0; i < array.size(); i++) {
    index++;
    JSONObject object = (JSONObject) array.get(i);
    System.out.println(object);
}
</code>```

Body:
I just have the below format of JSON request: (The original JSON is huge so sharing the sample from blog)

Sample Request:

{
  "testData": [
    {
      "firstName": "Lokesh",
      "lastName": "Gupta",
      "website": "howtodoinjava.com"
    },
    {
      "firstName": "Brian",
      "lastName": "Schultz",
      "website": "example.com"
    }
  ]
}

I just have below method which should get the each index of the above JSONArray. The above request should return size() == 2. And I just want to print the entire array[0], and array[1] in each iteration as like below.

public static void constructJSON(CheckoutDTO result)throws Exception
    {
        String jsonBody = result.getJson();
        JSONObject object = parseAndReturnObj(jsonBody);
        JSONArray array= (JSONArray) object.get("testData");
        int index=0;
        for(int i=0;i<array.size();i++)
        {
            index++;
            JSONObject objects = (JSONObject) array.get("");

            Sysout(objects); // Here I just want to print the array[0] index as entire JSONObject.
            }

        }
    }

The above code I just want to print the each index of the array. Like the first iteration I just want to print below:

array[0]:

  {
        "firstName": "Lokesh",
        "lastName": "Gupta",
        "website": "howtodoinjava.com"
  }

Second Iteration It should print below:

array[1]:

     {
            "firstName": "Brian",
            "lastName": "Schultz",
            "website": "example.com"
     }

The above request may have "n" number of array[n]. I just want to print the Systout(Objects) in the for loop as above format.

Using Simple json library to read the JSONObject.

   <dependency>
        <groupId>com.googlecode.json-simple</groupId>
        <artifactId>json-simple</artifactId>
    </dependency>

Can anyone help me to achieve this?

Body:
You can simply write System.out.println(object);. JSONObject's toString() method will automatically convert it to json. Your for loop can be modified as

for (int i = 0; i < array.size(); i++) {
    index++;
    JSONObject object = (JSONObject) array.get(i);
    System.out.println(object);
}


问:
Including and excluding specific records
I want to find some of buyer who had special condition (in this case, transaction >= 600000 called star member)

In this case, I want to find out star member (transaction >= 600000) who exists in January 2020 and March 2020, but it does not include star member who is doing transaction in February 2020.

here's my syntax

```<code>SELECT users_id
FROM order_star_member
GROUP BY users_id
HAVING SUM(CASE WHEN MONTHNAME(createdAt) = 'January'
                THEN total_price_star_member END) >= 600000
   AND SUM(CASE WHEN MONTHNAME(createdAt) = 'March'
                THEN total_price_star_member END) >= 600000
    AND NOT EXISTS (SELECT 1 FROM order_star_member
    GROUP BY users_id
    having sum(case when monthname(createdAt) = 'February'
    THEN total_price_star_member END) >= 600000);
</code>```

and here's my fiddle

```<code>https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=2c85037215fe71f700b51c8fd3a5ae76
</code>```

on my fiddle, the expected result are the users_Id 15 because that id order at january and march but not in february

答:
First in the inner t we group by month to determine all the star members.

The outer grouping groups by user_id. Their score is the sum of their star_member.

For February (m=2 (February being the second month) on the first line of the query below) if they are a star_member, they get an penalty (-100) as an arbitrary value that the SUM cannot overcome.

The only way a month_score=2 can exist if if a user has a star_member being true (1) for both January and March but not February.

```<code>SELECT users_id, SUM(IF(m=2 and star_member, -100, star_member)) as month_score
FROM
  (SELECT users_id,
          MONTH(createdAt) as m,
          SUM(total_price_star_member) >= 600000 as star_member
  FROM order_star_member
  WHERE createdAt BETWEEN '20190101' AND '20190331'
  GROUP BY users_id, m
) t
GROUP BY users_id
HAVING month_score=2
</code>```

fiddle

Body:
I want to find some of buyer who had special condition (in this case, transaction >= 600000 called star member)

In this case, I want to find out star member (transaction >= 600000) who exists in January 2020 and March 2020, but it does not include star member who is doing transaction in February 2020.

here's my syntax

SELECT users_id
FROM order_star_member
GROUP BY users_id
HAVING SUM(CASE WHEN MONTHNAME(createdAt) = 'January'
                THEN total_price_star_member END) >= 600000
   AND SUM(CASE WHEN MONTHNAME(createdAt) = 'March'
                THEN total_price_star_member END) >= 600000
    AND NOT EXISTS (SELECT 1 FROM order_star_member
    GROUP BY users_id
    having sum(case when monthname(createdAt) = 'February'
    THEN total_price_star_member END) >= 600000);

and here's my fiddle

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=2c85037215fe71f700b51c8fd3a5ae76

on my fiddle, the expected result are the users_Id 15 because that id order at january and march but not in february

Body:
First in the inner t we group by month to determine all the star members.

The outer grouping groups by user_id. Their score is the sum of their star_member.

For February (m=2 (February being the second month) on the first line of the query below) if they are a star_member, they get an penalty (-100) as an arbitrary value that the SUM cannot overcome.

The only way a month_score=2 can exist if if a user has a star_member being true (1) for both January and March but not February.

SELECT users_id, SUM(IF(m=2 and star_member, -100, star_member)) as month_score
FROM
  (SELECT users_id,
          MONTH(createdAt) as m,
          SUM(total_price_star_member) >= 600000 as star_member
  FROM order_star_member
  WHERE createdAt BETWEEN '20190101' AND '20190331'
  GROUP BY users_id, m
) t
GROUP BY users_id
HAVING month_score=2

fiddle


问:
How to use more than one embla carousel in a single webpage
I'm trying to integrate embla in angular. it works when I have a single slider in my page but when I try to make it more than one, the code breaks guess I'm getting something wrong in my ts code.

I followed this example on stackblitz https://stackblitz.com/edit/angular-embla?file=src%2Fapp%2Fapp.component.ts

Is it possbile to have more than one on a page with embla?

答:
I have modified the angular embla stackblitz sample to include navigation buttons and pagination similar to the code sample that you shared. I simply took the code from the codesandbox sample and made it work with angular. There could be better ways to do this. Also, in my opinion, it would be better to use a carousel plugin that is built to be used with angular.

https://stackblitz.com/edit/angular-embla-twfhsc?file=src%2Fapp%2Fapp.component.ts


问:
Show first 3 lines in HTML paragraph
I want to show only the first 3 lines of the paragraph below using HTML formatting. I am searching on W3Schools but it doesn't show how to do it.</p>

```<code><body>

loremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremlor
loremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremlore
loremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremlore
loremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremlore
loremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremlore

</body>
</code>```

答:
You can use -webkit-line-clamp property with div.

div {
  width: 100%;
  line-height: 1.2em;
  height: 3.6em;
  background-color: gainsboro;
  overflow: hidden;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  loremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremlore
  loremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremlore
  loremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremlore
  loremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremlore
  loremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremlore
</div></code>```

Title: Show first 3 lines in HTML paragraph

Body:
I want to show only the first 3 lines of the paragraph below using HTML formatting. I am searching on W3Schools but it doesn't show how to do it.

loremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremlor
loremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremlore
loremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremlore
loremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremlore
loremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremlore

Body:
You can use -webkit-line-clamp property with div.

div {
  width: 100%;
  line-height: 1.2em;
  height: 3.6em;
  background-color: gainsboro;
  overflow: hidden;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
}

<div>
  loremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremlore
  loremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremlore
  loremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremlore
  loremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremlore
  loremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremloremlore
</div>


问:
angular material chips placeholder float up instead of getting attached at the end
I am trying to use Angular material Chips. chips are working properly but there is an issue with a placeholder.

my expected behavior for a placeholder is placeholder attaching at the end of the chips list
  like expected.
 placeholder behavior that I am getting is placeholder floating above list.

```<code>        <mat-form-field class="example-chip-list">
            <mat-chip-list #chipList aria-label="Senders list">
                <mat-chip *ngFor="let sender of Senders"
                [selectable]="selectable" [removable]="removable" (removed)="remove(sender)">
                {{sender}}
                    <mat-icon matChipRemove *ngIf="removable">cancel</mat-icon>
                </mat-chip>
                <input placeholder="add sender..."
                        [matChipInputFor]="chipList"
                        [matChipInputSeparatorKeyCodes]="separatorKeysCodes"
                        [matChipInputAddOnBlur]="addOnBlur"
                        (matChipInputTokenEnd)="add($event)">
            </mat-chip-list>
        </mat-form-field>
</code>```

答:
Issue solved,

I am using angular material version 8.2.3 in which place holder is floating above while in material 9 it is after list.

Body:
I am trying to use Angular material Chips. chips are working properly but there is an issue with a placeholder.

my expected behavior for a placeholder is placeholder attaching at the end of the chips list
  like expected.
 placeholder behavior that I am getting is placeholder floating above list.

        <mat-form-field class="example-chip-list">
            <mat-chip-list #chipList aria-label="Senders list">
                <mat-chip *ngFor="let sender of Senders"
                [selectable]="selectable" [removable]="removable" (removed)="remove(sender)">
                {{sender}}
                    <mat-icon matChipRemove *ngIf="removable">cancel</mat-icon>
                </mat-chip>
                <input placeholder="add sender..."
                        [matChipInputFor]="chipList"
                        [matChipInputSeparatorKeyCodes]="separatorKeysCodes"
                        [matChipInputAddOnBlur]="addOnBlur"
                        (matChipInputTokenEnd)="add($event)">
            </mat-chip-list>
        </mat-form-field>


问:
CI/CD pipeline with PostgreSQL failed with "Database is uninitialized and superuser password is not specified" error
I'm using Bitbucket pipeline with PosgreSQL for CI/CD. According to this documentation PostgreSQL service has been described in bitbucket-pipelines.yml this way:

```<code>definitions:
  services:
    postgres:
      image: postgres:9.6-alpine
</code>```

It worked just fine until now. But all my latest pipelines failed with following error:

```<code>   Error: Database is uninitialized and superuser password is not specified.
   You must specify POSTGRES_PASSWORD for the superuser. Use
   "-e POSTGRES_PASSWORD=password" to set it in "docker run".

   You may also use POSTGRES_HOST_AUTH_METHOD=trust to allow all connections
   without a password. This is *not* recommended. See PostgreSQL
   documentation about "trust":
   https://www.postgresql.org/docs/current/auth-trust.html
</code>```

How can I fix it? There was no changes in bitbucket-pipelines.yml file which could be the reason of such error..

答:
If you are having issues connecting Django to PostgreSQL via Docker for the first time, then add the POSTGRES_HOST_AUTH_METHOD: trust to your docker-compose.yml file:

db:
  image: postgres:11
  environment:
    POSTGRES_HOST_AUTH_METHOD: trust

This solve the connection issue for me.

Please also be aware that "This is not recommended. See PostgreSQL documentation about "trust": https://www.postgresql.org/docs/current/auth-trust.html"

Body:
I'm using Bitbucket pipeline with PosgreSQL for CI/CD. According to this documentation PostgreSQL service has been described in bitbucket-pipelines.yml this way:

definitions:
  services:
    postgres:
      image: postgres:9.6-alpine

It worked just fine until now. But all my latest pipelines failed with following error:

   Error: Database is uninitialized and superuser password is not specified.
   You must specify POSTGRES_PASSWORD for the superuser. Use
   "-e POSTGRES_PASSWORD=password" to set it in "docker run".

   You may also use POSTGRES_HOST_AUTH_METHOD=trust to allow all connections
   without a password. This is *not* recommended. See PostgreSQL
   documentation about "trust":
   https://www.postgresql.org/docs/current/auth-trust.html

How can I fix it? There was no changes in bitbucket-pipelines.yml file which could be the reason of such error..


问:
How to check if any checkbox is selected or not in android with kotlin?
```<code>    submit_btn.setOnClickListener {
                var result = ""
                if(rb_gender.checkedRadioButtonId != -1)
                    {
                        result += " Gender: "
                    }
                    if(rb_male.isChecked) result += " Male \n"
                    if(rb_female.isChecked)  result += "Female \n"

       result += " Language Known:  "

            if(cb_english.isChecked) result+= " English"
            if(cb_hindi.isChecked) result+= " Hindi "
            if(cb_punjabi.isChecked) result+= " Punjabi"

               else   result = " PLEASE SELECT GENDER AND LANGUAGE \n"

            result_textView.text = result
        }
    }
}
</code>```

<p>//This code is not working on some condition like if I select Male and English then complier run else part......but that's not true</p>

答:
Try this : </p>

```<code>    var flag = 0

        if(cb_english.isChecked) {
                result+= " English"
                flag = 1
        }
        if(cb_hindi.isChecked) {
                result+= " Hindi "
                flag = 1
        }
        if(cb_punjabi.isChecked) {
                result+= " Punjabi"
                flag = 1
        }
        if(flag == 0){
                result = " PLEASE SELECT LANGUAGE \n"
        }
</code>```

Body:
    submit_btn.setOnClickListener {
                var result = ""
                if(rb_gender.checkedRadioButtonId != -1)
                    {
                        result += " Gender: "
                    }
                    if(rb_male.isChecked) result += " Male \n"
                    if(rb_female.isChecked)  result += "Female \n"

       result += " Language Known:  "

            if(cb_english.isChecked) result+= " English"
            if(cb_hindi.isChecked) result+= " Hindi "
            if(cb_punjabi.isChecked) result+= " Punjabi"

               else   result = " PLEASE SELECT GENDER AND LANGUAGE \n"

            result_textView.text = result
        }
    }
}

//This code is not working on some condition like if I select Male and English then complier run else part......but that's not true

Body:
Try this :

    var flag = 0

        if(cb_english.isChecked) {
                result+= " English"
                flag = 1
        }
        if(cb_hindi.isChecked) {
                result+= " Hindi "
                flag = 1
        }
        if(cb_punjabi.isChecked) {
                result+= " Punjabi"
                flag = 1
        }
        if(flag == 0){
                result = " PLEASE SELECT LANGUAGE \n"
        }


问:
Correct modification of state arrays in React.js
I want to add an element to the end of a state array, is this the correct way to do it?

```<code>this.state.arrayvar.push(newelement);
this.setState({ arrayvar:this.state.arrayvar });
</code>```

I'm concerned that modifying the array in-place with push might cause trouble - is it safe?

The alternative of making a copy of the array, and setStateing that seems wasteful.

答:
For added new element into the array, push() should be the answer.

For remove element and update state of array, below code works for me. splice(index, 1) can not work.

```<code>const [arrayState, setArrayState] = React.useState<any[]>([]);
...

// index is the index for the element you want to remove
const newArrayState = arrayState.filter((value, theIndex) => {return index !== theIndex});
setArrayState(newArrayState);
</code>```

Body:
I want to add an element to the end of a state array, is this the correct way to do it?

this.state.arrayvar.push(newelement);
this.setState({ arrayvar:this.state.arrayvar });

I'm concerned that modifying the array in-place with push might cause trouble - is it safe?

The alternative of making a copy of the array, and setStateing that seems wasteful.

Body:
For added new element into the array, push() should be the answer.

For remove element and update state of array, below code works for me. splice(index, 1) can not work.

const [arrayState, setArrayState] = React.useState<any[]>([]);
...

// index is the index for the element you want to remove
const newArrayState = arrayState.filter((value, theIndex) => {return index !== theIndex});
setArrayState(newArrayState);


问:
How can I reduce the repetitive work of this jquery source?
```<code>   $("#sel1").click(function () {
    $("#itemed1").attr("src", "../img/tab_img_01_on.png");
    $("#itemed2").attr("src", "../img/tab_img_02.png");
    $("#itemed3").attr("src", "../img/tab_img_03.png");
    $("#itemed4").attr("src", "../img/tab_img_04.png");
    $(this).find("span").addClass("add");
    $("#sel2").find("span").removeClass("add");
    $("#sel3").find("span").removeClass("add");
    $("#sel4").find("span").removeClass("add");
});
$("#sel2").click(function () {
    $("#itemed2").attr("src", "../img/tab_img_02_on.png");
    $("#itemed1").attr("src", "../img/tab_img_01.png");
    $("#itemed3").attr("src", "../img/tab_img_03.png");
    $("#itemed4").attr("src", "../img/tab_img_04.png");
    $(this).find("span").addClass("add");
    $("#sel1").find("span").removeClass("add");
    $("#sel3").find("span").removeClass("add");
    $("#sel4").find("span").removeClass("add");
});
$("#sel3").click(function () {
    $("#itemed3").attr("src", "../img/tab_img_03_on.png");
    $("#itemed1").attr("src", "../img/tab_img_01.png");
    $("#itemed2").attr("src", "../img/tab_img_02.png");
    $("#itemed4").attr("src", "../img/tab_img_04.png");
    $(this).find("span").addClass("add");
    $("#sel1").find("span").removeClass("add");
    $("#sel2").find("span").removeClass("add");
    $("#sel4").find("span").removeClass("add");
});
$("#sel4").click(function () {
    $("#itemed4").attr("src", "../img/tab_img_04_on.png");
    $("#itemed1").attr("src", "../img/tab_img_01.png");
    $("#itemed2").attr("src", "../img/tab_img_02.png");
    $("#itemed3").attr("src", "../img/tab_img_03.png");
    $(this).find("span").addClass("add");
    $("#sel1").find("span").removeClass("add");
    $("#sel2").find("span").removeClass("add");
    $("#sel3").find("span").removeClass("add");
});
</code>```

Hello This JQuery code is a source that changes the image when you click on the element.
It works fine, but I have a lot of iterations,
so I want to reduce my code. What should I use?

答:
You could use a simple combination of selectors.

See sample here or in CodePen:

$(".selector").click(function () {
    let index = $(this).data('index');
    $(".selector").find("span").removeClass("add");
    $(this).find("span").addClass("add");

    $(".imgs").each( function(){
      $(this).attr("src", `../img/tab_img_0${$(this).data('index')}.png`);
    });

    $(`.imgs[data-index="${index}"]`).attr("src", `../img/tab_img_0${index}_on.png`);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.add {
  font-size: 2em;
}</code>```

<button class="selector" data-index="1">Sel 1 sample</button>
<button class="selector" data-index="2">Sel 2 sample</button>
<button class="selector" data-index="3">Sel 3 sample</button>
<button class="selector" data-index="4">Sel 4 sample</button>

```

Obviously, if you are using n index > 10 you should use the padStart function.

Body:
   $("#sel1").click(function () {
    $("#itemed1").attr("src", "../img/tab_img_01_on.png");
    $("#itemed2").attr("src", "../img/tab_img_02.png");
    $("#itemed3").attr("src", "../img/tab_img_03.png");
    $("#itemed4").attr("src", "../img/tab_img_04.png");
    $(this).find("span").addClass("add");
    $("#sel2").find("span").removeClass("add");
    $("#sel3").find("span").removeClass("add");
    $("#sel4").find("span").removeClass("add");
});
$("#sel2").click(function () {
    $("#itemed2").attr("src", "../img/tab_img_02_on.png");
    $("#itemed1").attr("src", "../img/tab_img_01.png");
    $("#itemed3").attr("src", "../img/tab_img_03.png");
    $("#itemed4").attr("src", "../img/tab_img_04.png");
    $(this).find("span").addClass("add");
    $("#sel1").find("span").removeClass("add");
    $("#sel3").find("span").removeClass("add");
    $("#sel4").find("span").removeClass("add");
});
$("#sel3").click(function () {
    $("#itemed3").attr("src", "../img/tab_img_03_on.png");
    $("#itemed1").attr("src", "../img/tab_img_01.png");
    $("#itemed2").attr("src", "../img/tab_img_02.png");
    $("#itemed4").attr("src", "../img/tab_img_04.png");
    $(this).find("span").addClass("add");
    $("#sel1").find("span").removeClass("add");
    $("#sel2").find("span").removeClass("add");
    $("#sel4").find("span").removeClass("add");
});
$("#sel4").click(function () {
    $("#itemed4").attr("src", "../img/tab_img_04_on.png");
    $("#itemed1").attr("src", "../img/tab_img_01.png");
    $("#itemed2").attr("src", "../img/tab_img_02.png");
    $("#itemed3").attr("src", "../img/tab_img_03.png");
    $(this).find("span").addClass("add");
    $("#sel1").find("span").removeClass("add");
    $("#sel2").find("span").removeClass("add");
    $("#sel3").find("span").removeClass("add");
});

Hello This JQuery code is a source that changes the image when you click on the element.
It works fine, but I have a lot of iterations,
so I want to reduce my code. What should I use?

Body:
You could use a simple combination of selectors.

See sample here or in CodePen:

$(".selector").click(function () {
    let index = $(this).data('index');
    $(".selector").find("span").removeClass("add");
    $(this).find("span").addClass("add");

    $(".imgs").each( function(){
      $(this).attr("src", `../img/tab_img_0${$(this).data('index')}.png`);
    });

    $(`.imgs[data-index="${index}"]`).attr("src", `../img/tab_img_0${index}_on.png`);
});

.add {
  font-size: 2em;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="selector" data-index="1">Sel 1 <span>sample</span></button>
<button class="selector" data-index="2">Sel 2 <span>sample</span></button>
<button class="selector" data-index="3">Sel 3 <span>sample</span></button>
<button class="selector" data-index="4">Sel 4 <span>sample</span></button>

<img data-index="1" class="imgs" />
<img data-index="2" class="imgs" />
<img data-index="3" class="imgs" />
<img data-index="4" class="imgs" />

Obviously, if you are using n index > 10 you should use the padStart function.


问:
Select customer from table A then find customer in table B and insert the customer_id into table B
I am taking old records from excel sheets and moving them into a database.

I have a customers table and an orders table.

The customers table has fields
customer_id ---primary key ---auto increment
First_Name
Last_Name

The orders table has fields:
customer_id (empty will be a foreign key for customers table)
First_Name (populated)
Last_Name  (populated)

I need to select the customer_id, first_name and last_name row by row from the customers table then find each order in the orders table with the same name the insert the customer_id from the customers table to the orders table.

There are about 5000 orders and 3000 unique customers and I am trying to assign the customer_id to each order.  I can do it manually but it would take a week of Sundays.

Thanks

答:
Your existing table design have issues (like what if two or more customers have same name?), still if you want to update the customer_id based on customer name you can try query like following.

```<code>update o
set o.customer_id =c.customer_id
from orders o
inner join customers c on c.First_Name =o.First_Name and c.Last_Name=o.Last_Name
</code>```

Body:
Your existing table design have issues (like what if two or more customers have same name?), still if you want to update the customer_id based on customer name you can try query like following.

update o
set o.customer_id =c.customer_id
from orders o
inner join customers c on c.First_Name =o.First_Name and c.Last_Name=o.Last_Name


问:
ReactJS: Why does pushing values to state in an object removes data?
I have set up a couple of input fields where the value goes into an object input, and I'm trying to store it into a new object with other data, but the value is disappearing.

On my handleSubmit function, I have setNewData(mediaArray) where it just sets the mediaArray into a new state - which it happens to be working correctly, but if I wrap the mediaArray into an object: setNewData({mediaArray}), it erases the data. Why does it do that?

I'm ultimately trying to do this: setNewData({...setSomeOtherInfo, mediaArray}) so I can have this:

```<code>newData = {
  info: '',
  description: '',
  mediaArray: [
    {
      input1: '',
      input2: '',
    },
    {
      input1: '',
      input2: '',
    },
    {
      input1: '',
      input2: '',
    },
  ]
}
</code>```

Component:

```<code>const Screen = props => {

  const [someOtherInfo, setSomeOtherInfo] = useState({
    info: '',
    description: ''
  });
  const [mediaArray, setMediaArray] = useState([]);
  const [newData, setNewData] = useState(null);
  const [input, setInput] = useState({
    input1: '',
    input2: ''
  });

  const handleInput1 = (index, value) => {
    mediaArray[index] = {
      ...mediaArray[index],
      ['input1']: value,
    };
  };

  const handleInput2 = (index, value) => {
    mediaArray[index] = {
      ...mediaArray[index],
      ['input2']: value,
    };
  };

  const handleSubmit = () => {
    setNewData(mediaArray);
  };

  useEffect(() => {

  }, [newData]);

  return (
    <View>
      <TextInput onChangeText={e => handleInput1(index, e)} value={input.input1} />
      <TextInput onChangeText={e => handleInput2(index, e)} value={input.input2} />
    </View>
  );
};

export default Screen;
</code>```

答:
I would suggest that you should try to use set methods for those states, instead of directly mutating the state.

mediaArray[index] = {
      ...mediaArray[index],
      ['input1']: value,
    };
// instead of using this, try
   setMediaArray((state) => {
      state[index].input1 = value
      return state
   })
```

I am not used to with functional component but as per normal scenario, this should work.

Body:
I have set up a couple of input fields where the value goes into an object input, and I'm trying to store it into a new object with other data, but the value is disappearing.

On my handleSubmit function, I have setNewData(mediaArray) where it just sets the mediaArray into a new state - which it happens to be working correctly, but if I wrap the mediaArray into an object: setNewData({mediaArray}), it erases the data. Why does it do that?

I'm ultimately trying to do this: setNewData({...setSomeOtherInfo, mediaArray}) so I can have this:

newData = {
  info: '',
  description: '',
  mediaArray: [
    {
      input1: '',
      input2: '',
    },
    {
      input1: '',
      input2: '',
    },
    {
      input1: '',
      input2: '',
    },
  ]
}

Component:

const Screen = props => {

  const [someOtherInfo, setSomeOtherInfo] = useState({
    info: '',
    description: ''
  });
  const [mediaArray, setMediaArray] = useState([]);
  const [newData, setNewData] = useState(null);
  const [input, setInput] = useState({
    input1: '',
    input2: ''
  });

  const handleInput1 = (index, value) => {
    mediaArray[index] = {
      ...mediaArray[index],
      ['input1']: value,
    };
  };

  const handleInput2 = (index, value) => {
    mediaArray[index] = {
      ...mediaArray[index],
      ['input2']: value,
    };
  };

  const handleSubmit = () => {
    setNewData(mediaArray);
  };

  useEffect(() => {

  }, [newData]);

  return (
    <View>
      <TextInput onChangeText={e => handleInput1(index, e)} value={input.input1} />
      <TextInput onChangeText={e => handleInput2(index, e)} value={input.input2} />
    </View>
  );
};

export default Screen;

Body:
I would suggest that you should try to use set methods for those states, instead of directly mutating the state.

mediaArray[index] = {
      ...mediaArray[index],
      ['input1']: value,
    };
// instead of using this, try
   setMediaArray((state) => {
      state[index].input1 = value
      return state
   })

I am not used to with functional component but as per normal scenario, this should work.


问:
Visual Studio Intellisense not working on XAML only on very specific circumstances
I'm making a new UserControl, and when I opened it the XAML was not working.

I thought that this was odd, as when I was working on my MainWindow it was working just fine. So I checked on my MainWindow. It still works there. Also in C# code.

However, if I press CTRL +        it still comes up fine.

I'm not quite sure why. I went to Tools➾Options➾Text Editor➾XAML➾General, and the Text Completion section is greyed out (e.g. Auto-List Members, etc.). This is also greyed out when I see it on my main window, but Intellisense works there.

Could someone help me? My VS version is VS2012 Express, Update 2. The only extension installed is XNA (using this "hack").

答:
I got the same issue after uninstalling Resharper from VS2019. In the options dialog the "auto list members" and related options for Text Editor->XAML was disabled.

I tried to reset the default editor for XAML to Source Code Text Editor by clicking Open With... on a XAML file, did not work.

I then tried to update and even reinstall VS, nothing worked.

In pure desperation I went back to the same options page as "auto list members" and disabled and then re-enabled any property ("Line Numbers" i my case). This seemed to light a spark and now it's all good again.


问:
Install .NET Core on Google Colab
I am trying to install .NET Core on Google Colab. I follow the instructions given (for Ubuntu 17.10):

```<code>! wget -q https://packages.microsoft.com/config/ubuntu/17.10/packages-microsoft-prod.deb
! dpkg -i packages-microsoft-prod.deb
! apt-get install apt-transport-https
! apt-get update
</code>```

This all works fine until I try to install aspnetcore-runtime-2.1 :

```<code>! apt-get install aspnetcore-runtime-2.1
</code>```

and get this error :

```<code>Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 aspnetcore-runtime-2.1 : Depends: dotnet-runtime-2.1 (>= 2.1.2) but it is not going to be installed
E: Unable to correct problems, you have held broken packages.
</code>```

You can clearly see that there is a dependency missing : dotnet-runtime-2.1. The problem is I cannot manage to install it separately so there is no dependency issue. Can anyone help me with this ?

答:
Google colab is on ubuntu version 18.04.3 at the moment. You can check it using,

! lsb_release -a

So you need to follow Microsoft guide for that version.
Execute these steps one after the other, in order.

```<code>! wget -q https://packages.microsoft.com/config/ubuntu/18.04/packages-microsoft-prod.deb -O packages-microsoft-prod.deb
! dpkg -i packages-microsoft-prod.deb
! add-apt-repository universe
! apt-get update
! apt-get install apt-transport-https
! apt-get update
! apt-get install dotnet-sdk-3.1
</code>```

Here is a working colab notebook -> https://colab.research.google.com/drive/19ZM4sIccSOgNjX3hQW0KUFsVbZCrGXTY

You can check if it got installed properly using,

```<code>! dotnet --list-sdks
</code>```

Title: Install .NET Core on Google Colab

Body:
I am trying to install .NET Core on Google Colab. I follow the instructions given (for Ubuntu 17.10):

! wget -q https://packages.microsoft.com/config/ubuntu/17.10/packages-microsoft-prod.deb
! dpkg -i packages-microsoft-prod.deb
! apt-get install apt-transport-https
! apt-get update

This all works fine until I try to install aspnetcore-runtime-2.1 :

! apt-get install aspnetcore-runtime-2.1

and get this error :

Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 aspnetcore-runtime-2.1 : Depends: dotnet-runtime-2.1 (>= 2.1.2) but it is not going to be installed
E: Unable to correct problems, you have held broken packages.

You can clearly see that there is a dependency missing : dotnet-runtime-2.1. The problem is I cannot manage to install it separately so there is no dependency issue. Can anyone help me with this ?

Body:
Google colab is on ubuntu version 18.04.3 at the moment. You can check it using,

! lsb_release -a

So you need to follow Microsoft guide for that version.
Execute these steps one after the other, in order.

! wget -q https://packages.microsoft.com/config/ubuntu/18.04/packages-microsoft-prod.deb -O packages-microsoft-prod.deb
! dpkg -i packages-microsoft-prod.deb
! add-apt-repository universe
! apt-get update
! apt-get install apt-transport-https
! apt-get update
! apt-get install dotnet-sdk-3.1

Here is a working colab notebook -> https://colab.research.google.com/drive/19ZM4sIccSOgNjX3hQW0KUFsVbZCrGXTY

You can check if it got installed properly using,

! dotnet --list-sdks


问:
how to Change Codeigniter pagination query string
I want to change CodeIgniter pagination query string. When I use query string it will run & the url is good but data remaining same, without query string it will run properly.

My URL look like

```<code>example.com/1
</code>```

But I want it to be like

```<code>example.com?page=1
</code>```

Here is my controller code..

```<code>$this->load->library('pagination');

$config['base_url'] = base_url().'/purchase/index';
$config['total_rows'] = $this->db->count_all('purchase');
$config['per_page'] = 10;
$config['page_query_string'] = TRUE;
$config['query_string_segment'] = 'page';

$this->pagination->initialize($config);

$page =($this->uri->segment(3)) ? $this->uri->segment(3) : 0;

$data['pur_list'] = $this->purchase_model->purchase_list($config['per_page'],$page);
</code>```

答:
this will give you output like </p>

```<code>example.com?page=1&q=banana
</code>```

```<code>$config = $this->config->item('pagination_config');
$config["base_url"] = base_url("search");
$config["total_rows"] = $this->SearchModel->getResultCount($query);
$config["per_page"] = 6;
$config['enable_query_strings'] = TRUE;
$config['page_query_string'] = TRUE;
$config['use_page_numbers'] = TRUE;
$config['reuse_query_string'] = TRUE;
$config['query_string_segment'] = 'page';
$this->pagination->initialize($config);
$current_page = $this->input->get('page',0);
$this->data["links"] = $this->pagination->create_links();
$this->data['results'] = $this->SearchModel->getResults($query, $config["per_page"], $current_page);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to change CodeIgniter pagination query string. When I use query string it will run & the url is good but data remaining same, without query string it will run properly.

My URL look like

example.com/1

But I want it to be like

example.com?page=1

Here is my controller code..

$this->load->library('pagination');

$config['base_url'] = base_url().'/purchase/index';
$config['total_rows'] = $this->db->count_all('purchase');
$config['per_page'] = 10;
$config['page_query_string'] = TRUE;
$config['query_string_segment'] = 'page';

$this->pagination->initialize($config);

$page =($this->uri->segment(3)) ? $this->uri->segment(3) : 0;

$data['pur_list'] = $this->purchase_model->purchase_list($config['per_page'],$page);

Body:
this will give you output like

example.com?page=1&q=banana

$config = $this->config->item('pagination_config');
$config["base_url"] = base_url("search");
$config["total_rows"] = $this->SearchModel->getResultCount($query);
$config["per_page"] = 6;
$config['enable_query_strings'] = TRUE;
$config['page_query_string'] = TRUE;
$config['use_page_numbers'] = TRUE;
$config['reuse_query_string'] = TRUE;
$config['query_string_segment'] = 'page';
$this->pagination->initialize($config);
$current_page = $this->input->get('page',0);
$this->data["links"] = $this->pagination->create_links();
$this->data['results'] = $this->SearchModel->getResults($query, $config["per_page"], $current_page);


问:
In ANDROID, How to get a current position and tracking in map using GPS without giving any location in a program?
I am new to android, can anyone help me for my question....
How to get a current position and tracking in map using GPS without giving any location in a program?????</p>

答:
```<code>public class GPSLocationBased extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.locationbased);

    LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    LocationListener ll = new Mylocationlistener();

    // ---Get the status of GPS---
    boolean isGPS = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);

    // If GPS is not enable then it will be on
    if(!isGPS)
    {
        Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
        intent.putExtra("enabled", true);
         sendBroadcast(intent);
    }

    //<--registers the current activity to be notified periodically by the named provider. Periodically,
    //the supplied LocationListener will be called with the current Location or with status updates.-->
    lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
}

/**
 *Mylocationlistener class will give the current GPS location
 *with the help of Location Listener interface
 */
private class Mylocationlistener implements LocationListener {
    @Override
    public void onLocationChanged(Location location) {
        if (location != null) {
            // ---Get current location latitude, longitude, altitude & speed ---

            Log.d("LOCATION CHANGED", location.getLatitude() + "");
            Log.d("LOCATION CHANGED", location.getLongitude() + "");
            float speed = location.getSpeed();
            double altitude = location.getAltitude();
            Toast.makeText(GPSLocationBased.this,"Latitude = "+
                    location.getLatitude() + "" +"Longitude = "+ location.getLongitude()+"Altitude = "+altitude+"Speed = "+speed,
                    Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }
}
</code>```

}

Through this code u will get ur lat and long.
and u may use it on ur gmap.
this code also start gps functionality problematically. Hope this will help u.. All the best :)

Body:
public class GPSLocationBased extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.locationbased);

    LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    LocationListener ll = new Mylocationlistener();

    // ---Get the status of GPS---
    boolean isGPS = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);

    // If GPS is not enable then it will be on
    if(!isGPS)
    {
        Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
        intent.putExtra("enabled", true);
         sendBroadcast(intent);
    }

    //<--registers the current activity to be notified periodically by the named provider. Periodically,
    //the supplied LocationListener will be called with the current Location or with status updates.-->
    lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
}

/**
 *Mylocationlistener class will give the current GPS location
 *with the help of Location Listener interface
 */
private class Mylocationlistener implements LocationListener {
    @Override
    public void onLocationChanged(Location location) {
        if (location != null) {
            // ---Get current location latitude, longitude, altitude & speed ---

            Log.d("LOCATION CHANGED", location.getLatitude() + "");
            Log.d("LOCATION CHANGED", location.getLongitude() + "");
            float speed = location.getSpeed();
            double altitude = location.getAltitude();
            Toast.makeText(GPSLocationBased.this,"Latitude = "+
                    location.getLatitude() + "" +"Longitude = "+ location.getLongitude()+"Altitude = "+altitude+"Speed = "+speed,
                    Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }
}

}

Through this code u will get ur lat and long.
and u may use it on ur gmap.
this code also start gps functionality problematically. Hope this will help u.. All the best :)


问:
My device id for AdMob Testing changed (Android)
I have set the device id of the phone I use for adMob testing as a const in my app. My testing device is not my day-to-day device.

Today I wanted to test a use case with a reward video and all of the sudden I get no fill or internal errors.

I took a look into the Log Cat and I saw that the device Id changed

By device Id I am referring to the one that comes in this log:

```<code>I/Ads: Use RequestConfiguration.Builder().setTestDeviceIds(Arrays.asList("THIS_ID_HERE") to get test ads on this device.
</code>```

Why does it changed?

Is it because I uninstalled the prod version and installed a dev version of my app?

Does it happens randomly?

Can I prevent this behavior?

答:
As per google given try to use below credential for testing ads.In that case you will not need to add Device Id.

```<code><!--Ad test credentials-->
<string name="admob_app_id">ca-app-pub-3940256099942544~3347511713</string>
<string name="banner_home_footer">ca-app-pub-3940256099942544/6300978111</string>
<string name="interstitial_full_screen">ca-app-pub-3940256099942544/1033173712</string>
<string name="rewarded_video">ca-app-pub-3940256099942544/5224354917</string>

<!--Ad live credentials-->
<string name="admob_app_id">add here your live app id</string>
<string name="banner_home_footer">add here your live footer id</string>
<string name="interstitial_full_screen">add here your live interstitial id</string>
<string name="rewarded_video">add here your live rewarded id</string>
</code>```

Now use below function for shows testing ads.

```<code>//Banner Ads
private void loadBannerAds(AdView mAdView) {
    AdRequest adRequest = new AdRequest.Builder()
            .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
            .build();
    mAdView.loadAd(adRequest);
}

//Interstitial Ads
private void loadInterstitialAds(final InterstitialAd mInterstitialAd) {
    AdRequest adRequest = new AdRequest.Builder()
            .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
            .build();
    // Load ads into Interstitial Ads
    mInterstitialAd.loadAd(adRequest);
    mInterstitialAd.setAdListener(new AdListener() {
        public void onAdLoaded() {
            if (mInterstitialAd.isLoaded()) {
                mInterstitialAd.show();
            }
        }
    });
}

//RewardedVideo Ads
private void loadRewardedVideoAd(RewardedVideoAd mRewardedVideoAd) {
    AdRequest adRequest = new AdRequest.Builder()
            .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
            .build();

    mRewardedVideoAd.loadAd(context.getResources().getString(R.string.rewarded_video), adRequest);

    mRewardedVideoAd.setRewardedVideoAdListener(new RewardedVideoAdListener() {
        @Override
        public void onRewarded(RewardItem rewardItem) {
        }
        @Override
        public void onRewardedVideoAdLeftApplication() {
        }
        @Override
        public void onRewardedVideoAdClosed() {
        }
        @Override
        public void onRewardedVideoAdFailedToLoad(int errorCode) {
        }
        @Override
        public void onRewardedVideoCompleted() {
        }
        @Override
        public void onRewardedVideoAdLoaded() {
            try {
                if (mRewardedVideoAd.isLoaded()) {
                    mRewardedVideoAd.show();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        @Override
        public void onRewardedVideoAdOpened() {
        }
        @Override
        public void onRewardedVideoStarted() {
        }
    });

    // showing the ad to user
    // make sure the ad is loaded completely before showing it
    if (mRewardedVideoAd.isLoaded()) {
        mRewardedVideoAd.show();
    }
}
</code>```

I hope this can help you!

Body:
I have set the device id of the phone I use for adMob testing as a const in my app. My testing device is not my day-to-day device.

Today I wanted to test a use case with a reward video and all of the sudden I get no fill or internal errors.

I took a look into the Log Cat and I saw that the device Id changed

By device Id I am referring to the one that comes in this log:

I/Ads: Use RequestConfiguration.Builder().setTestDeviceIds(Arrays.asList("THIS_ID_HERE") to get test ads on this device.

Why does it changed?

Is it because I uninstalled the prod version and installed a dev version of my app?

Does it happens randomly?

Can I prevent this behavior?

Body:
As per google given try to use below credential for testing ads.In that case you will not need to add Device Id.

<!--Ad test credentials-->
<string name="admob_app_id">ca-app-pub-3940256099942544~3347511713</string>
<string name="banner_home_footer">ca-app-pub-3940256099942544/6300978111</string>
<string name="interstitial_full_screen">ca-app-pub-3940256099942544/1033173712</string>
<string name="rewarded_video">ca-app-pub-3940256099942544/5224354917</string>

<!--Ad live credentials-->
<string name="admob_app_id">add here your live app id</string>
<string name="banner_home_footer">add here your live footer id</string>
<string name="interstitial_full_screen">add here your live interstitial id</string>
<string name="rewarded_video">add here your live rewarded id</string>

Now use below function for shows testing ads.

//Banner Ads
private void loadBannerAds(AdView mAdView) {
    AdRequest adRequest = new AdRequest.Builder()
            .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
            .build();
    mAdView.loadAd(adRequest);
}

//Interstitial Ads
private void loadInterstitialAds(final InterstitialAd mInterstitialAd) {
    AdRequest adRequest = new AdRequest.Builder()
            .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
            .build();
    // Load ads into Interstitial Ads
    mInterstitialAd.loadAd(adRequest);
    mInterstitialAd.setAdListener(new AdListener() {
        public void onAdLoaded() {
            if (mInterstitialAd.isLoaded()) {
                mInterstitialAd.show();
            }
        }
    });
}

//RewardedVideo Ads
private void loadRewardedVideoAd(RewardedVideoAd mRewardedVideoAd) {
    AdRequest adRequest = new AdRequest.Builder()
            .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
            .build();

    mRewardedVideoAd.loadAd(context.getResources().getString(R.string.rewarded_video), adRequest);

    mRewardedVideoAd.setRewardedVideoAdListener(new RewardedVideoAdListener() {
        @Override
        public void onRewarded(RewardItem rewardItem) {
        }
        @Override
        public void onRewardedVideoAdLeftApplication() {
        }
        @Override
        public void onRewardedVideoAdClosed() {
        }
        @Override
        public void onRewardedVideoAdFailedToLoad(int errorCode) {
        }
        @Override
        public void onRewardedVideoCompleted() {
        }
        @Override
        public void onRewardedVideoAdLoaded() {
            try {
                if (mRewardedVideoAd.isLoaded()) {
                    mRewardedVideoAd.show();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        @Override
        public void onRewardedVideoAdOpened() {
        }
        @Override
        public void onRewardedVideoStarted() {
        }
    });

    // showing the ad to user
    // make sure the ad is loaded completely before showing it
    if (mRewardedVideoAd.isLoaded()) {
        mRewardedVideoAd.show();
    }
}

I hope this can help you!


问:
sql query question for most name in table with multiple most names
fbn table:

```<code>create table fbn (
id int,
name varchar(40),
birthday date,
gender varchar(10));

INSERT into fbn values
(1, "James", "2000-04-22", "male"),
(2, "Julia", "2006-02-27", "female"),
(3, "Ethan", "2013-05-23", "male"),
(4, "Lion", "2014-09-11", "male"),
(5, "Ethan", "2006-01-01", "male"),
(6, "Lion", "2006-02-01", "male");
</code>```

what's the name that occur most? note that there are two names (Ethan and Lion) occur most often. I have two solutions as below:

```<code>select tmp2.name
from (select tmp.name,
             dense_rank() over(order by tmp.name_count desc) rank
      from (select name,
                   count(*) name_count
            from fbn
            group by name) tmp
      ) tmp2
where tmp2.rank = 1;
</code>```

and the 2nd solution:

```<code>select name from fbn
group by name
having count(name) = (select count(name) from fbn
                      group by name
                      order by count(name) desc
                      limit 1);
</code>```

both seem to be working, but both looks like too complicated. is there any other solution that's more concise easier to understand? Thanks

答:
How about this:

```<code>SELECT counts,GROUP_CONCAT(NAME) AS names
FROM
(SELECT NAME, COUNT(*) counts  FROM fbn GROUP BY NAME) A
GROUP BY counts
ORDER BY counts DESC
LIMIT 1;
</code>```

Fiddle here : https://www.db-fiddle.com/f/qzmJAx5LFfzZdYyDetUfex/1

Body:
fbn table:

create table fbn (
id int,
name varchar(40),
birthday date,
gender varchar(10));

INSERT into fbn values
(1, "James", "2000-04-22", "male"),
(2, "Julia", "2006-02-27", "female"),
(3, "Ethan", "2013-05-23", "male"),
(4, "Lion", "2014-09-11", "male"),
(5, "Ethan", "2006-01-01", "male"),
(6, "Lion", "2006-02-01", "male");

what's the name that occur most? note that there are two names (Ethan and Lion) occur most often. I have two solutions as below:

select tmp2.name
from (select tmp.name,
             dense_rank() over(order by tmp.name_count desc) rank
      from (select name,
                   count(*) name_count
            from fbn
            group by name) tmp
      ) tmp2
where tmp2.rank = 1;

and the 2nd solution:

select name from fbn
group by name
having count(name) = (select count(name) from fbn
                      group by name
                      order by count(name) desc
                      limit 1);

both seem to be working, but both looks like too complicated. is there any other solution that's more concise easier to understand? Thanks

Body:
How about this:

SELECT counts,GROUP_CONCAT(NAME) AS names
FROM
(SELECT NAME, COUNT(*) counts  FROM fbn GROUP BY NAME) A
GROUP BY counts
ORDER BY counts DESC
LIMIT 1;

Fiddle here : https://www.db-fiddle.com/f/qzmJAx5LFfzZdYyDetUfex/1


问:
Citrus Framework logging - how to enable/use
The Citrus Framework documentation indicates that integration test console output can be logged via the SLF4J logging system. It's not obvious whether this is automatic, or whether it needs to be enabled in some way. My experience indicates that it's not enabled as no log file containing what appears on the test run console has been produced.

My application uses Log4J with an associated log4j2-spring.xml file (in src/main/resources) to define log formats and files. When an integration test is run via Citrus, the application console output (and other information) is properly logged to the files specified in the Log4J config file. There is however, no Citrus console output logged anywhere (except on the console).

How do I enable the logging of the Citrus test console output? I created a separate log4j.xml that I placed in src/test/resources, but this seems to have been ignored.

Do I need to specify a separate logger in the config that's specific for Citrus output?

答:
Citrus uses SLF4J which is a facade to several other logging frameworks out there. So you need to pick your favorite logging framework (in your case Log4J) and add a SLF4J logger binding for that logging framework. This is all described in the SLF4J user manual

I would suggest to add the SLF4J logger binding for Log4J as a test scoped dependency in your project. Also depending on your Log4J configuration setup you may need to add a Log4J logger configuration for com.consol.citrus and set a proper logging level for that in order to see the Citrus output logged by Log4J.


答:
Expendable version of same code.

function pad(v) {
  return (v.length === 2 ? v : '0' + v);
}

$('[id^=sel]').click(function() {
  var total = 4;
  var idNumber = $(this).attr('id').match(/\d+/);

  for ( i = 1; i <= total; i++ ) {
    $('#itemed' + i).attr('src', '../img/tab_img_' + pad(i) + '.png');
    $('#sel' + i).find('span').removeClass('add');
  }

  $('#itemed' + idNumber).attr('src', '../img/tab_img_' + pad(idNumber) + '_on.png');
  $(this).find('span').addClass('add');
});
```

But I think @SnakeDrak approach is correct

Title: How can I reduce the repetitive work of this jquery source?

Body:
Expendable version of same code.

function pad(v) {
  return (v.length === 2 ? v : '0' + v);
}

$('[id^=sel]').click(function() {
  var total = 4;
  var idNumber = $(this).attr('id').match(/\d+/);

  for ( i = 1; i <= total; i++ ) {
    $('#itemed' + i).attr('src', '../img/tab_img_' + pad(i) + '.png');
    $('#sel' + i).find('span').removeClass('add');
  }

  $('#itemed' + idNumber).attr('src', '../img/tab_img_' + pad(idNumber) + '_on.png');
  $(this).find('span').addClass('add');
});

But I think @SnakeDrak approach is correct


问:
Angular 8 @output EventEmitter not letting an Object to be emitted
How would I emit an Object instead of primitive data types?

I have a object const amount = { currenty: 'USD', total: '10.25' };
which I wanted to emmit to the parent component.

```<code>export class MyChildComponent implements OnInit {
     @Output() childEventEmitter: EventEmitter = new EventEmitter();
....
}
</code>```

in the emitter function

this.childEventEmitter.emit(amount); // not working

error: Argument of type { currenty: 'USD', total: '10.25' } not assignable to paraments of type string

答:
Simple way by passing any kind of parameter through the event.</p>

```<code>@Output() childEventEmitter: EventEmitter<any> = new EventEmitter<any>();
</code>```

Body:
How would I emit an Object instead of primitive data types?

I have a object const amount = { currenty: 'USD', total: '10.25' };
which I wanted to emmit to the parent component.

export class MyChildComponent implements OnInit {
     @Output() childEventEmitter: EventEmitter = new EventEmitter();
....
}

in the emitter function

this.childEventEmitter.emit(amount); // not working

error: Argument of type { currenty: 'USD', total: '10.25' } not assignable to paraments of type string

Body:
Simple way by passing any kind of parameter through the event.

@Output() childEventEmitter: EventEmitter<any> = new EventEmitter<any>();


问:
Nesting Defaultdictionaries in Python3
I'm working on a piece of code and this is my first time implementing defaultdict from collections.
Currently, I have a piece of code that works just fine as a defaultdict, but I'd really like to nest my dictionaries.

This is the code I have currently:

```<code>from collections import defaultdict, Counter
from re import findall

class Class:
    def __init__(self, n, file):
        self.counts = defaultdict(lambda: defaultdict(int))
        self.__n = n
        self.__file = file

    def function(self, starting_text, charas):
        self.__starting_text = starting_text
        self.__charas = charas

        with open(self.__file) as file:
            text = file.read().lower().replace('\n', ' ')

        ngrams = [text[i : i + self.__n] for i in range(len(text))]

        out = self.counts
        for item in ngrams:
            data = []
            for word in findall( item+".", text):
                data.append(word[-1])
            self.counts = { item : data.count(item) for item in data }
            out[item] = self.counts
        self.counts = out
</code>```

Some of the things in the code aren't yet implemented because I'm at a bit of a standstill, so please ignore anything that isn't applicable to this particular question!

If I run print(self.counts) at the end, my program runs something that looks like this:

```<code>defaultdict(<function Class.__init__.<locals>.<lambda> at 0x7f8c4a94bea0>, {'t': {'h': 1, ' ': 1, 'e': 1}, 'h': {'i': 1, 'o': 1}, 'i': {'s': 2}, 's': {' ': 2, 'h': 1, 'e': 1}, ' ': {'i': 1, 'a': 1, 's': 2}, 'a': {' ': 1}, 'o': {'r': 1}, 'r': {'t': 1}, 'e': {'n': 2, ' ': 1}, 'n': {'t': 1, 'c': 1}, 'c': {'e': 1}})
</code>```

Which is great! But I'd really like to have those inner dictionaries be defaultdicts as well. In particular, if I run self.counts['t']['h'], I get 1, as expected.
However, a benefit of the defaultdict is having it give you 0 if a key is not available. Currently, if I run self.counts['t']['x'] I get a keyerror, but I'd live to get 0 instead by having each inner list be a defaultdict as well.

I'm assuming this can be done somewhere in the chunk of code beginning with out=self.counts, but I'm a little unsure how I can achieve this.

答:
Your code is not using any of the features of the defaultdict. It would work identically if you used a normal dict instead. It's also very confusing, as you're using several variable names (like item and self.__counts) for different things in different parts of the code.

But you can pretty trivially change it to use the defaultdict instead of doing things the hard way. Here's how I'd fix it:

```<code>def function(self, starting_text, charas):
    self.__starting_text = starting_text
    self.__charas = charas

    with open(self.__file) as file:
        text = file.read().lower().replace('\n', ' ')

    ngrams = set(text[i : i + self.__n] for i in range(len(text)))

    for item in ngrams:
        for word in findall( item+".", text):
            self.counts[item][word[-1]] += 1
</code>```

This isn't exactly the same as your previous code, as it's not idempotent (if you call it repeatedly, you'll keep adding on to the counts, rather than replacing old counts with new ones). You probably can restore most of the old behavior by putting all the characters into a list (like your data) first, then setting the value in self.__counts only at the end. But then I'd probably prefer using a collections.Counter instead of doing it by hand (and I'd probably build the Counter in the loop, rather than having defaultdict do it for me).

On an unrelated note: Your code is using double leading underscores on several of your attributes. That's not generally encouraged for Python code. It enables name mangling, which transforms names like self.__n into self._Class__n (if Class is the name of the class the code using __n is written in, regardless of what type self is). It should not usually be used to mark something as "private", rather it's intended to avoid accidental name collisions when you can't know in advance what other names might be put into the same object namespace. For instance, a proxy or a mixin class might need to allow users to access any kind of attribute name, and the designer of the class can't know what those will be (and the designer of the objects that will be proxied or the classes that will be mixed with may not know of the proxy/mixin class's existence). If you just want to mark your attributes as "private", use a single leading underscore rather than two. Data privacy isn't enforced in Python, and trying to use name mangling for it is only misleading you (outside code that wants to access your attributes will still be able to do so). And name mangling makes debugging harder. The Python philosophy is that its programmers are all "consenting adults" and so they should be trusted to know not to misbehave with other code's internals (or to deal with the consequences if they do).

Title: Nesting Defaultdictionaries in Python3

Body:
I'm working on a piece of code and this is my first time implementing defaultdict from collections.
Currently, I have a piece of code that works just fine as a defaultdict, but I'd really like to nest my dictionaries.

This is the code I have currently:

from collections import defaultdict, Counter
from re import findall

class Class:
    def __init__(self, n, file):
        self.counts = defaultdict(lambda: defaultdict(int))
        self.__n = n
        self.__file = file

    def function(self, starting_text, charas):
        self.__starting_text = starting_text
        self.__charas = charas

        with open(self.__file) as file:
            text = file.read().lower().replace('\n', ' ')

        ngrams = [text[i : i + self.__n] for i in range(len(text))]

        out = self.counts
        for item in ngrams:
            data = []
            for word in findall( item+".", text):
                data.append(word[-1])
            self.counts = { item : data.count(item) for item in data }
            out[item] = self.counts
        self.counts = out

Some of the things in the code aren't yet implemented because I'm at a bit of a standstill, so please ignore anything that isn't applicable to this particular question!

If I run print(self.counts) at the end, my program runs something that looks like this:

defaultdict(<function Class.__init__.<locals>.<lambda> at 0x7f8c4a94bea0>, {'t': {'h': 1, ' ': 1, 'e': 1}, 'h': {'i': 1, 'o': 1}, 'i': {'s': 2}, 's': {' ': 2, 'h': 1, 'e': 1}, ' ': {'i': 1, 'a': 1, 's': 2}, 'a': {' ': 1}, 'o': {'r': 1}, 'r': {'t': 1}, 'e': {'n': 2, ' ': 1}, 'n': {'t': 1, 'c': 1}, 'c': {'e': 1}})

Which is great! But I'd really like to have those inner dictionaries be defaultdicts as well. In particular, if I run self.counts['t']['h'], I get 1, as expected.
However, a benefit of the defaultdict is having it give you 0 if a key is not available. Currently, if I run self.counts['t']['x'] I get a keyerror, but I'd live to get 0 instead by having each inner list be a defaultdict as well.

I'm assuming this can be done somewhere in the chunk of code beginning with out=self.counts, but I'm a little unsure how I can achieve this.

Body:
Your code is not using any of the features of the defaultdict. It would work identically if you used a normal dict instead. It's also very confusing, as you're using several variable names (like item and self.__counts) for different things in different parts of the code.

But you can pretty trivially change it to use the defaultdict instead of doing things the hard way. Here's how I'd fix it:

def function(self, starting_text, charas):
    self.__starting_text = starting_text
    self.__charas = charas

    with open(self.__file) as file:
        text = file.read().lower().replace('\n', ' ')

    ngrams = set(text[i : i + self.__n] for i in range(len(text)))

    for item in ngrams:
        for word in findall( item+".", text):
            self.counts[item][word[-1]] += 1

This isn't exactly the same as your previous code, as it's not idempotent (if you call it repeatedly, you'll keep adding on to the counts, rather than replacing old counts with new ones). You probably can restore most of the old behavior by putting all the characters into a list (like your data) first, then setting the value in self.__counts only at the end. But then I'd probably prefer using a collections.Counter instead of doing it by hand (and I'd probably build the Counter in the loop, rather than having defaultdict do it for me).

On an unrelated note: Your code is using double leading underscores on several of your attributes. That's not generally encouraged for Python code. It enables name mangling, which transforms names like self.__n into self._Class__n (if Class is the name of the class the code using __n is written in, regardless of what type self is). It should not usually be used to mark something as "private", rather it's intended to avoid accidental name collisions when you can't know in advance what other names might be put into the same object namespace. For instance, a proxy or a mixin class might need to allow users to access any kind of attribute name, and the designer of the class can't know what those will be (and the designer of the objects that will be proxied or the classes that will be mixed with may not know of the proxy/mixin class's existence). If you just want to mark your attributes as "private", use a single leading underscore rather than two. Data privacy isn't enforced in Python, and trying to use name mangling for it is only misleading you (outside code that wants to access your attributes will still be able to do so). And name mangling makes debugging harder. The Python philosophy is that its programmers are all "consenting adults" and so they should be trusted to know not to misbehave with other code's internals (or to deal with the consequences if they do).


问:
How to add a component as a sibling to a directive in angular 8?
```<code>   <div>
     <input type="text"/>
     <span class="drop-down-icon"></span>
   </div>
   <ul *ngIf="something">
     <li *ngFor="let item of list"></li>
   </ul>
</code>```

In the above code, div element and its children are added from the directive, but I want the ul element to be added from the component, can it be achieved?

答:
Yes it can be achieve using the ElementRef you can add the DOM element from the component.
But if you want to add *ngFor directive to the ul then ul element will also created on the iteration.

Body:
     <input type="text"/>

In the above code, div element and its children are added from the directive, but I want the ul element to be added from the component, can it be achieved?


问:
Select two different Items if they meet different condition
I have a select problem with mssql which is;

```<code>Invoice 1
ItemUniqueNo    ItemName    InvoceNo
1               A           123
3               C           123

Table A (All Invoices)
ItemUniqueNo   ItemName   InvoceNo
1               A           123
2               B           235
3               C           123

Table B (Item List)
ItemUniqueNo    ItemName    ItemGroup
1               A           XXX
2               B           YYY
3               C           ZZZ
</code>```

I want to select every items (from Table A) If an invoice has both type of product which is; ItemUniqueNo=3 and ItemGroup = XXX, in same invoice. Here is my code:

```<code>SELECT
*
FROM
TABLE_A
WHERE
(ItemUniqueNo IN (SELECT ItemUniqueNo FROM TABLE_B WHERE ItemGroup='XXX') OR ItemUniqueNo = 3)
</code>```

with this code, I've listed all items which has either ItemGroup = XXX and ItemUniqueNo=3 BUT
I want to meet both condition in same invoice, like:

```<code>Invoice 1
ItemUniqueNo    ItemName    InvoceNo
1               A           123  --->  This meets 'XXX' ItemGroup condition
3               C           123  --->  This meets '3' ItemUniqueNo condition
</code>```

This invoice meet both 2 condition, so i want to list this two item with InvoceNo.
AND all other items which meet this condition.

答: Just change your OR to an AND in your where clause

Body:
I have a select problem with mssql which is;

Invoice 1
ItemUniqueNo    ItemName    InvoceNo
1               A           123
3               C           123

Table A (All Invoices)
ItemUniqueNo   ItemName   InvoceNo
1               A           123
2               B           235
3               C           123

Table B (Item List)
ItemUniqueNo    ItemName    ItemGroup
1               A           XXX
2               B           YYY
3               C           ZZZ

I want to select every items (from Table A) If an invoice has both type of product which is; ItemUniqueNo=3 and ItemGroup = XXX, in same invoice. Here is my code:

SELECT
*
FROM
TABLE_A
WHERE
(ItemUniqueNo IN (SELECT ItemUniqueNo FROM TABLE_B WHERE ItemGroup='XXX') OR ItemUniqueNo = 3)

with this code, I've listed all items which has either ItemGroup = XXX and ItemUniqueNo=3 BUT
I want to meet both condition in same invoice, like:

Invoice 1
ItemUniqueNo    ItemName    InvoceNo
1               A           123  --->  This meets 'XXX' ItemGroup condition
3               C           123  --->  This meets '3' ItemUniqueNo condition

This invoice meet both 2 condition, so i want to list this two item with InvoceNo.
AND all other items which meet this condition.


问:
How do i load google fonts on the sever side node js
I am using node js and canvas to create an API that writes text on a certain image. I successfully created a route such as -> /:sometext/:fontsize/:color/:position-x/:position-y and sends a static image with the text of the given font-size, color, and position on the canvas.

What I am unable to achieve is that I want to send the font family in the route and have that rendered on the screen. Plus, isn't there any other way that I can load at least google fonts without having to download the .ttf file.

What I have tried:

GetGoogleFonts npm package (which was a bad idea, since it was stuck at the installation)

WebFontLoader (Gives "Window is not defined" error)

Steps to Reproduce

Currently, I am using a ttf file to load the font

```<code>
router.get('/thumbnail/:name/:fontsize/:color/:posx/:posy', function (req, res, next) {
  let name = req.params.name;
  let fontsize = req.params.fontsize
  let positionx = req.params.posx
  let positiony = req.params.posy
  let color = req.params.color

  let myimage = 'static/image1.jpg'

  const canvas = createCanvas(2000, 1000)
  const ctx = canvas.getContext('2d')
  var str = "hi "+name
  registerFont('AvenirNext.ttf', { family: 'Avenir Next' })
  loadImage(myimage).then((image) => {
  ctx.drawImage(image, 0 , 0, 2000, 1000);
  ctx.font = fontsize + "px Avenir Next"
  ctx.fillStyle = color
  ctx.fillText(str, positionx, positiony);

  const out = fs.createWriteStream(__dirname + '/test.jpeg')
  const stream = canvas.createJPEGStream()
  stream.pipe(res)
  out.on('finish', () =>  console.log('The JPEG file was created.'))

})
});

</code>```

答:
If you don't want to host the ttf files on your own server you could try to use the Google Font Github repo.

// missing imports
const http = require('http');
const fs = require('fs');
```

<pre class="lang-js prettyprint-override"><code>const fontFamily = req.params.fontfamily; // example: ArchivoNarrow

// download font from github
const file = fs.createWriteStream(fontFamily + '.ttf');
const request = http.get('https://github.com/google/fonts/blob/master/ofl/' + fontFamily.toLowerCase() + '/' + fontFamily + '-Regular.ttf?raw=true', function(response) {
  response.pipe(file);
});

registerFont(fontFamily + '.ttf', { family: fontFamily });
</code>```

// delete font after the image is created
try {
  fs.unlinkSync(fontFamily + '.ttf');
} catch(err) {
  console.error(err);
}
```

Font I used for this example: ArchivoNarrow

Body:
I am using node js and canvas to create an API that writes text on a certain image. I successfully created a route such as -> /:sometext/:fontsize/:color/:position-x/:position-y and sends a static image with the text of the given font-size, color, and position on the canvas.

What I am unable to achieve is that I want to send the font family in the route and have that rendered on the screen. Plus, isn't there any other way that I can load at least google fonts without having to download the .ttf file.

What I have tried:

GetGoogleFonts npm package (which was a bad idea, since it was stuck at the installation)

WebFontLoader (Gives "Window is not defined" error)

Steps to Reproduce

Currently, I am using a ttf file to load the font

router.get('/thumbnail/:name/:fontsize/:color/:posx/:posy', function (req, res, next) {
  let name = req.params.name;
  let fontsize = req.params.fontsize
  let positionx = req.params.posx
  let positiony = req.params.posy
  let color = req.params.color

  let myimage = 'static/image1.jpg'

  const canvas = createCanvas(2000, 1000)
  const ctx = canvas.getContext('2d')
  var str = "hi "+name
  registerFont('AvenirNext.ttf', { family: 'Avenir Next' })
  loadImage(myimage).then((image) => {
  ctx.drawImage(image, 0 , 0, 2000, 1000);
  ctx.font = fontsize + "px Avenir Next"
  ctx.fillStyle = color
  ctx.fillText(str, positionx, positiony);

  const out = fs.createWriteStream(__dirname + '/test.jpeg')
  const stream = canvas.createJPEGStream()
  stream.pipe(res)
  out.on('finish', () =>  console.log('The JPEG file was created.'))

})
});

Body:
If you don't want to host the ttf files on your own server you could try to use the Google Font Github repo.

// missing imports
const http = require('http');
const fs = require('fs');

const fontFamily = req.params.fontfamily; // example: ArchivoNarrow

// download font from github
const file = fs.createWriteStream(fontFamily + '.ttf');
const request = http.get('https://github.com/google/fonts/blob/master/ofl/' + fontFamily.toLowerCase() + '/' + fontFamily + '-Regular.ttf?raw=true', function(response) {
  response.pipe(file);
});

registerFont(fontFamily + '.ttf', { family: fontFamily });

// delete font after the image is created
try {
  fs.unlinkSync(fontFamily + '.ttf');
} catch(err) {
  console.error(err);
}

Font I used for this example: ArchivoNarrow


问:
How to convert int to string on Arduino?
How do I convert an int, n, to a string so that when I send it over the serial, it is sent as a string?

This is what I have so far:

```<code>int ledPin=13;
int testerPin=8;
int n=1;

char buf[10];

void setup()
{
    pinMode(ledPin, OUTPUT);
    pinMode(testerPin, OUTPUT);
    Serial.begin(115200);
}

void loop()
{
    digitalWrite(ledPin, HIGH);
    sprintf(buf, "Hello!%d", n);
    Serial.println(buf);
    delay(500);
    digitalWrite(ledPin, LOW);
    delay(500);

    n++;
}
</code>```

答:
This simply work for me:</p>

```<code>int bpm = 60;
char text[256];
sprintf(text, "Pulso: %d     ", bpm);
//now use text as string
</code>```

Body:
How do I convert an int, n, to a string so that when I send it over the serial, it is sent as a string?

This is what I have so far:

int ledPin=13;
int testerPin=8;
int n=1;

char buf[10];

void setup()
{
    pinMode(ledPin, OUTPUT);
    pinMode(testerPin, OUTPUT);
    Serial.begin(115200);
}

void loop()
{
    digitalWrite(ledPin, HIGH);
    sprintf(buf, "Hello!%d", n);
    Serial.println(buf);
    delay(500);
    digitalWrite(ledPin, LOW);
    delay(500);

    n++;
}

Body:
This simply work for me:

int bpm = 60;
char text[256];
sprintf(text, "Pulso: %d     ", bpm);
//now use text as string


问:
How to get name of variable
I have simple question.
How to get name of variable time from this example:

```<code>let x = {
  color: string = red;
}

let y = getVarName(x.color);
console.log(y);
</code>```

Result: color

How i can get this result above? getVarName is example function which i want to make.

答:
You can use below for getting output as color.

```<code>let color : string = 'red';
let xp : any = '';
let z = {
   colors : color,
}

let p = getVarName(z.colors);
console.log('colorname: ',p);
function getVarName(xp){
   return xp;
}
console.log('color name: ',z.colors);
let keys = Object.keys(z).filter(k=>z[k]==='red');

console.log('key: ',keys[0])
</code>```

You can check this working example refer below link:
https://stackblitz.com/edit/typescript-73dpve?embed=1&file=index.ts

Title: How to get name of variable

Body:
I have simple question.
How to get name of variable time from this example:

let x = {
  color: string = red;
}

let y = getVarName(x.color);
console.log(y);

Result: color

How i can get this result above? getVarName is example function which i want to make.

Body:
You can use below for getting output as color.

let color : string = 'red';
let xp : any = '';
let z = {
   colors : color,
}

let p = getVarName(z.colors);
console.log('colorname: ',p);
function getVarName(xp){
   return xp;
}
console.log('color name: ',z.colors);
let keys = Object.keys(z).filter(k=>z[k]==='red');

console.log('key: ',keys[0])

You can check this working example refer below link:
https://stackblitz.com/edit/typescript-73dpve?embed=1&file=index.ts


问:
what is the impact of modifying openAM Authentication Settings (user Profile)
we use OpenAM version 13.0.0

what is the impact of modifying User Profile from required to Dynamic or Dynamic with an alias?

realms->authentication->settings

is this will affects SSO SAML or normal login for the admin user.

答:
Based on the NameID format being used it will affect SAML SSO.
It does not affect authentication for the super user 'amadmin'.
The purpose for this setting is security. If the actual source for authentication has a different account/identity base as OpenAM, e.g. a RADIUS server. It may include accounts for network operators that are not allowed to use 'Access Management', nevertheless you may use it as authentication method for OpenAM. To guarantee that only 'known' identities are allowed to use 'Access Management', you set 'User Profile' to 'required'. Then OpenAM will perform a 'profile lookup' in the configured user data stores after the actual authentication (via RADIUS) happened.
Unfortunately OpenAM has always set this as default, even when 'datastore' authentication is configured .... this does not make sense as the source for authentication is the same as for identities.
Unfortunately the concept has not been widely known, hence 'User profile' setting is also leveraged by other part of the code, although it's totally unrelated.</p>