问:
How to add 'OR' condition to call middleware on Laravel Routes?
I want to add 'OR' condition with middleware on laravel routes for Role and Permission. Can anyone please help me here. Below is the code which I am trying currently through some internet research but it is not working.</p>

```<code>Route::get('get-all-users', 'API\Admin\AdminController@get_all_users')->middleware(['role:admin' OR 'permission:view.all.users']);
</code>```

答:
In this scenario,  you will need to change the DB structure a bit. Tables would look like:

Actions

Roles

Role_action_mapping => This will have foreign keys of both the above tables as a many to many relationship.

Now, every action should have a role assigned to it. So, the permission view.all.users will have an entry in the table with admin(or any desired role) assigned to it by it's side in Role_action_mapping.

So all you will have to do is have a single middleware say permission:view.all.users on the route and just check if the current role of the user has an entry with view.all.users in the Role_action_mapping table.

Body:
I want to add 'OR' condition with middleware on laravel routes for Role and Permission. Can anyone please help me here. Below is the code which I am trying currently through some internet research but it is not working.

Route::get('get-all-users', 'API\Admin\AdminController@get_all_users')->middleware(['role:admin' OR 'permission:view.all.users']);


来源: stackexchange

ContentLicense: CC BY-SA 4.0

Title: Labeling by date in two data frames

Body:
df1
name date
A    14-04-05
A    14-05-08
A    14-08-09
A    15-01-05
B    18-07-05
B    18-08-09
B    18-10-02
C    19-01-03
C    19-02-04
C    19-03-30
D    16-04-01
D    16-08-04

df2
name startdate
A    14-07-07
B    18-09-09
C    19-03-15
D    16-06-28

Record all dates in one dataset, The second dataset records the start date.

I want to label the records of df1, compared to the start date of df2, record '0' if it is earlier than the start date and '1' if it is the day after the start date.

result what I want

df1
name date     Label startdate
A    14-04-05 0     14-07-07
A    14-05-08 0     14-07-07
A    14-08-09 1     14-07-07
A    15-01-05 1     14-07-07
B    18-07-05 0     18-09-09
B    18-08-09 0     18-09-09
B    18-10-02 1     18-09-09
C    19-01-03 0     19-03-15
C    19-02-04 0     19-03-15
C    19-03-30 1     19-03-15
D    16-04-01 0     16-06-28
D    16-08-04 1     16-06-28

I tried to handle it using datetime, but it didn't work..

Simple example dataset sample

df1 = pd.DataFrame(np.array([['A', '2015-12-21'],['A', '2015-12-22'], ['A', '2015-12-25'], ['B', '2018-01-28'],['B', '2018-02-28'],['B', '2018-03-28']]),
                   columns=['name', 'date'])

df2 = pd.DataFrame(np.array([['A', '2015-12-23'], ['B', '2018-03-01']]),
                   columns=['name', 'startdate'])

Thank you for reading

Body:
You can map it:

print (df1.assign(new=(df1["date"]>df1["name"].map(df2.set_index("name")["startdate"])).astype(int),
                  start=df1["name"].map(df2.set_index("name")["startdate"])))

   name      date  new     start
0     A  14-04-05    0  14-07-07
1     A  14-05-08    0  14-07-07
2     A  14-08-09    1  14-07-07
3     A  15-01-05    1  14-07-07
4     B  18-07-05    0  18-09-09
5     B  18-08-09    0  18-09-09
6     B  18-10-02    1  18-09-09
7     C  19-01-03    0  19-03-15
8     C  19-02-04    0  19-03-15
9     C  19-03-30    1  19-03-15
10    D  16-04-01    0  16-06-28
11    D  16-08-04    1  16-06-28


问:
Get bash where bash script executed from
I want to be able to execute a bash script located in my home directory with the command ~/script_name.sh from any directory and then in the script, get the directory that it was ran from.

eg. I'm in the directory /foo/bar/baz, and execute /foo/script.sh, and it prints out /foo/bar/baz

pwd and $0/$BASH_SOURCE give me the directory my shell starts in and the path to the script in my home directory respectively.

答: Instead of invoking the external command pwd, consider using $PWD instead. If you want to protect against some rogue code having explicitly changed PWD, do a cd . (which is an internal command) first, which restores PWD to the correct value.


问:
How can I keep number and increment in child component with Vue JS?
Practicing to make a todo application with Vue JS

Input items save in the localStrage.

UPDATED

When you have some added list and reload a page, ID number start from 1(defalut).

Ideal behaviour:

when reload a page, ID number continues number increment.

if some items removed, then, add new item, ID number should be the biggest ID number in array(if 8) +1 (should be 9).

My code: Link

Problem is around here.

Child2.vue

```<code>  created() {
    let keyObject = JSON.parse(localStorage.getItem(this.keyName));

    if (keyObject) {
      this.$emit("update:todos", keyObject);
    } else {
      return;
    }

    if (this.todos.length > 0) {
      console.log(this.todos.id);
      const setId = this.todos.reduce(function(a,b){ return a > b.id ? a : b.id} ,0)
      this.todos.id = setId + 1
      console.log(this.todos.id);

      this.$emit('update:todos', keyObject)
      // this.$emit('update:todos', this.todos.id)
    }
  },
</code>```

Do you know how?

答:
From my understanding of your problem, you want to update the value of the props from a child component.

To do that you might want to emit the change from a child component back to the parent.

Below is one way of doing that:

In your child component:

```<code>this.todosArray = this.todosArray.concat(keyObject); //concat with an existing array
this.$emit("updateTodos", this.todosArray); //emit new array back to parent
</code>```

In your parent component, where u register your child component:

```<code><Child2 :todos="todos" :keyName="keyName" @updateTodos="updateTodos"/>
</code>```

and then add a method to update the original array with the value that will come from the child component.

```<code>updateTodos(value) {
 this.todos = value
}
</code>```

I hope it helps. Good luck!

Body:
Practicing to make a todo application with Vue JS

Input items save in the localStrage.

UPDATED

When you have some added list and reload a page, ID number start from 1(defalut).

Ideal behaviour:

when reload a page, ID number continues number increment.

if some items removed, then, add new item, ID number should be the biggest ID number in array(if 8) +1 (should be 9).

My code: Link

Problem is around here.

Child2.vue

  created() {
    let keyObject = JSON.parse(localStorage.getItem(this.keyName));

    if (keyObject) {
      this.$emit("update:todos", keyObject);
    } else {
      return;
    }

    if (this.todos.length > 0) {
      console.log(this.todos.id);
      const setId = this.todos.reduce(function(a,b){ return a > b.id ? a : b.id} ,0)
      this.todos.id = setId + 1
      console.log(this.todos.id);

      this.$emit('update:todos', keyObject)
      // this.$emit('update:todos', this.todos.id)
    }
  },

Do you know how?

Body:
From my understanding of your problem, you want to update the value of the props from a child component.

To do that you might want to emit the change from a child component back to the parent.

Below is one way of doing that:

In your child component:

this.todosArray = this.todosArray.concat(keyObject); //concat with an existing array
this.$emit("updateTodos", this.todosArray); //emit new array back to parent

In your parent component, where u register your child component:

<Child2 :todos="todos" :keyName="keyName" @updateTodos="updateTodos"/>

and then add a method to update the original array with the value that will come from the child component.

updateTodos(value) {
 this.todos = value
}

I hope it helps. Good luck!


问:
Setting up multiple test folders in a SBT project
We'd like to set up our SBT project so that we have multiple test folders as opposed to one. So we'd like to see:

root

src

test

scala

unit

functional

How would we configure our SBT project file paths to do this?

答:
SBT 0.9.x:

```<code>(sourceDirectories in Test) := Seq(new File("src/test/scala/unit"),
                                   new File("src/test/scala/functional"))
</code>```

SBT 0.7.x:

```<code>override def testSourceRoots = ("src" / "test") +++
       "scala" +++ ("unit" / "functional")
</code>```

ContentLicense: CC BY-SA 3.0

Body:
SBT 0.9.x:

(sourceDirectories in Test) := Seq(new File("src/test/scala/unit"),
                                   new File("src/test/scala/functional"))

SBT 0.7.x:

override def testSourceRoots = ("src" / "test") +++
       "scala" +++ ("unit" / "functional")


问:
Do I need to specify a data type boolean in typescript when the value is already set in false?
public expanded: boolean = false;

Can the above piece of code be simplified to something like public expanded = false;?

Just wondering if the transpiler will benefit from it?

答: Yes, the typescript will infer the type automatically.</p>


问:
A javascript reactjs question about props
Here is the simple App.js code:

```<code>import React from 'react'
import Member from './Member'

function App () {
  const members = [
    { name: 'Andy', age: 22 },
    { name: 'Bruce', age: 33 },
    { name: 'Mary', age: 11 }
  ]
  for (const member of members) {
    return <Member {...member} />
  }
}

export default App
</code>```

Here is the Member.js:

```<code>import React from 'react'

function Member ({ name, age }) {
  return (
  <div>
    {name}
    <hr />
    {age}
  </div>)
}

export default Member
</code>```

The problem is only the first object {name:'Andy', age: 22} shows in the browser. How can I change the code to show all three of them?
I am new to Javascript and React. I just can't figure it out. Can anyone help? Thanks a lot.

答:
One way is not to spread the  props at first

Pass the array as it is as

Then in the Member component; use the .map() function to iterate over the Member props like member.map(user => {user.name}, {user.age} )

Hope that helps

Body:
Here is the simple App.js code:

import React from 'react'
import Member from './Member'

function App () {
  const members = [
    { name: 'Andy', age: 22 },
    { name: 'Bruce', age: 33 },
    { name: 'Mary', age: 11 }
  ]
  for (const member of members) {
    return <Member {...member} />
  }
}

export default App

Here is the Member.js:

import React from 'react'

function Member ({ name, age }) {
  return (

    {name}

    {age}

)
}

export default Member

The problem is only the first object {name:'Andy', age: 22} shows in the browser. How can I change the code to show all three of them?
I am new to Javascript and React. I just can't figure it out. Can anyone help? Thanks a lot.


问:
Unable to use GET_PAGE_NAME keyword with multiple GO_TO Page
I am creating a Suite File where a TestCase contains multiple PageObject and to get_page_name where I am landed.
Getting below error
Error if 2 pageobject

Suite File

Suite File

答: two methods are defined with the same name "get page name" in the files "HomePage" and "LoginPage"</p>


问:
Query string query from javascript client
I am using elasticsearch 5.5 and my query is

```<code>client.search({
  index: 'sample',
  type: 'data',
  body: {
    "query": {
      "query_string": {
        "query": "state:req.params.state AND city:req.params.city AND postalcode:req.params.pc"
      }
    }
  }
}
})
</code>```

In this code req.params.state, req.params.city and req.params.pc are user given values which are considered as value(string) itself and returns nothing because double quotes are used.

So when I tried to remove double quotes the AND operater used is not validated as operator and throws an error.

答:
Well, you need to build the query differently, in a dynamic way, like this.</p>

```<code>const input = {
  'state': 'state',
  'city': 'city',
  'pc': 'postcode'
};
const query = [];
Object.keys(input).forEach(p => {
   if (req.params[p]) {
      query.push([input[p], req.params[p]].join(":"));
   }
});

client.search({
  index: 'sample',
  type: 'data',
  body:{
    "query":{
      "query_string": {
        "query": query.length ? query.join(" AND ") : "*"
      }
    }
  }
})
</code>```

Body:
I am using elasticsearch 5.5 and my query is

client.search({
  index: 'sample',
  type: 'data',
  body: {
    "query": {
      "query_string": {
        "query": "state:req.params.state AND city:req.params.city AND postalcode:req.params.pc"
      }
    }
  }
}
})

In this code req.params.state, req.params.city and req.params.pc are user given values which are considered as value(string) itself and returns nothing because double quotes are used.

So when I tried to remove double quotes the AND operater used is not validated as operator and throws an error.

Body:
Well, you need to build the query differently, in a dynamic way, like this.

const input = {
  'state': 'state',
  'city': 'city',
  'pc': 'postcode'
};
const query = [];
Object.keys(input).forEach(p => {
   if (req.params[p]) {
      query.push([input[p], req.params[p]].join(":"));
   }
});

client.search({
  index: 'sample',
  type: 'data',
  body:{
    "query":{
      "query_string": {
        "query": query.length ? query.join(" AND ") : "*"
      }
    }
  }
})


问:
Best approach for adding subviews in tableview cell at runtime and expand tableview cell

I have a table view (picture attached) where I have a cell and its status(multiple).

When a user clicks the cell it expands show the status.

My question is what is the best approach to achieve this functionality, I don't feel like the one I have right is a good approach.

Right now when a user click I set a variable in didSelectRowAt and reload the cell. When I reload the cell I check the variable and add/remove subview.

I'm adding subview in a stackview like this:-

```<code>    for _ in 1...4 {
        let view = ActivityFeedStatusView()
        let constraint = NSLayoutConstraint(item: view, attribute: .height, relatedBy: .equal,
                                            toItem: nil, attribute: .height, multiplier: 1.0, constant: 70.0)
        NSLayoutConstraint.activate([constraint])
        stackview.addArrangedSubview(view)
    }
</code>```

As you can see it'll get added all the time cellForRowAt will be called plus It is also giving me constraint warning.

I'm open to any kind of feedback and suggestions, thank you for reading.

Note: This code is just a test code to generate and show view

答:
Your solution seems fine to me:
My complete solution is:
1.keep track of previous selected cell index and current selected cell index by delegate method didSelectCellAtIndex.
2.reload cells at previous cell index and current cell index.
3.in cell init codes.if it is at previous then remove all status subviews.Otherwise,add status subviews on this cell.
4.manually calculate the height and reload or use auto layout for self height constraint.</p>

Body:
I have a table view (picture attached) where I have a cell and its status(multiple).

When a user clicks the cell it expands show the status.

My question is what is the best approach to achieve this functionality, I don't feel like the one I have right is a good approach.

Right now when a user click I set a variable in didSelectRowAt and reload the cell. When I reload the cell I check the variable and add/remove subview.

I'm adding subview in a stackview like this:-

    for _ in 1...4 {
        let view = ActivityFeedStatusView()
        let constraint = NSLayoutConstraint(item: view, attribute: .height, relatedBy: .equal,
                                            toItem: nil, attribute: .height, multiplier: 1.0, constant: 70.0)
        NSLayoutConstraint.activate([constraint])
        stackview.addArrangedSubview(view)
    }

As you can see it'll get added all the time cellForRowAt will be called plus It is also giving me constraint warning.

I'm open to any kind of feedback and suggestions, thank you for reading.

Note: This code is just a test code to generate and show view


问:
How to manage node_modules in Continous deployment via jenkins?
Trying to develop node.js application since it is under development requires lot of deployments to be done to production environment.During every releases do we have to move entire node_modules to production ?

Note : production environment is restricted from internet access so cannot use NPM install there.

答:
You should check out npmrc file, which, among other things, decides source of all your node modules.

Your production server should have such file in its project root, and it must store the location of your npm packages that must be installed.

The registry value inside npmrc file is where you can put your packages. You can read more about it here.


问:
I want to Create a Crystal Report of Paid Sales Invoices
When a Sales invoice is paid it is matched against the receipt.
A Sales invoice can also be matched against a credit note but there is no distinguishing flag.
I want the final report to only show the Paid invoices.
I am currently Grouping by Customer, then Matching Letter, then document, so at this level you can see if the match is with a receipt or with credit notes.
I output the Group footer of the document giving me a list of documents, which for a customer payment will start with the Receipt, followed by one or more invoices totaling the value of the receipt:

GF4 Customer A  Match BC    REC101009798                    GBP240.00
GF4 Customer A  Match BC    INV101059389        ‘new field’ GBP120.00
GF4 Customer A  Match BC    INV101059390        ‘new field’ GBP120.00

If the matching is as a result of a customer payment, the Receipt will always be on the first line in the group output.

How do I create a ’new field’ on the Invoice lines that will say “Paid” , it doesn’t matter if the new field also appears on the Receipt line?

I have tried to use a formula on the group footer referencing the document type but of course when the document type changes, so does the result of the formula.
Having a success on the first line I have been concentrating on trying to copy the result on to the successive lines so thought a fresh pair of eyes might help.

Many thanks

答:
Thank you Pals, I have solved this with a colleague.
We revised the formula on the Group Footer. First we created a formula that assigned a 1 to a Receipt and 0 to all other docments: IF {GACCDUDATE.TYP_0} = "REC01" THEN 1 ELSE 0. Next we created a SUM formula: IF Sum({@rowIsPaid}, {GACCENTRYD.MTC_0}) > 0 THEN "Paid"
and put this on the Group footer.</p>


问:
How to implement sensor batching on Tizen
I need to get the data from accelerometer on Tizen Wearable (ideally 3.0 or below) in a batched manner for maximum battery efficiency.

The relevant apidoc is here.

My current code looks like this:

```<code>static void start_accelerometer() {
    sensor_type_e type = SENSOR_ACCELEROMETER;
    int max_batch_latency = 30000; // 300 is max queue, 100 ms is default period

    if (sensor_get_default_sensor(type, &sensor) == SENSOR_ERROR_NONE)
    {
        if (sensor_create_listener(sensor, &listener) == SENSOR_ERROR_NONE
            && sensor_listener_set_max_batch_latency(listener, max_batch_latency) == SENSOR_ERROR_NONE
            && sensor_listener_set_event_cb(listener, 100, accelerometer_sensor_event_callback, NULL) == SENSOR_ERROR_NONE
            && sensor_listener_set_option(listener, SENSOR_OPTION_ALWAYS_ON) == SENSOR_ERROR_NONE
            )
        {
            if (sensor_listener_start(listener) == SENSOR_ERROR_NONE)
            {
                dlog_print(DLOG_INFO, TAG, "Sensor started");
            }
        }
    }
}
</code>```

I have tried numerous variations of the above (like settings sensor_listener_set_option to SENSOR_OPTION_DEFAULT to have it pause on display off, starting the sensor without setting event callback and reading data manually) - but in all cases I never get the batched values from the sensor (either in the callback or through sensor_listener_read_data()). I'm always getting only the most recent data.

Do you know how to get batched data from accelerometer on Tizen wearables?

P.S. I'm using Galaxy Watch Active 1 for development.

答:
As far as I know, the physical sensors work in a batch manner only when the AP goes into a suspend state, it only occurs while the display is off.
So, after the display turns off, wait for 10 to 30 minutes before checking.
Also, please set enough intervals(about 1000ms) to avoid too much flush.

Lastly, using sensor_listener_read_data(), you can get only the most recent data.

Body:
I need to get the data from accelerometer on Tizen Wearable (ideally 3.0 or below) in a batched manner for maximum battery efficiency.

The relevant apidoc is here.

My current code looks like this:

static void start_accelerometer() {
    sensor_type_e type = SENSOR_ACCELEROMETER;
    int max_batch_latency = 30000; // 300 is max queue, 100 ms is default period

    if (sensor_get_default_sensor(type, &sensor) == SENSOR_ERROR_NONE)
    {
        if (sensor_create_listener(sensor, &listener) == SENSOR_ERROR_NONE
            && sensor_listener_set_max_batch_latency(listener, max_batch_latency) == SENSOR_ERROR_NONE
            && sensor_listener_set_event_cb(listener, 100, accelerometer_sensor_event_callback, NULL) == SENSOR_ERROR_NONE
            && sensor_listener_set_option(listener, SENSOR_OPTION_ALWAYS_ON) == SENSOR_ERROR_NONE
            )
        {
            if (sensor_listener_start(listener) == SENSOR_ERROR_NONE)
            {
                dlog_print(DLOG_INFO, TAG, "Sensor started");
            }
        }
    }
}

I have tried numerous variations of the above (like settings sensor_listener_set_option to SENSOR_OPTION_DEFAULT to have it pause on display off, starting the sensor without setting event callback and reading data manually) - but in all cases I never get the batched values from the sensor (either in the callback or through sensor_listener_read_data()). I'm always getting only the most recent data.

Do you know how to get batched data from accelerometer on Tizen wearables?

P.S. I'm using Galaxy Watch Active 1 for development.


问:
Read file with separation in C++
I have a script which reads text file into a vector.

```<code>#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <vector>
using namespace std;

struct Items
{
    string Name;
    int Number1;
    double Number2;
};

int main()
{
    ifstream file("file4.txt");
    vector<Items> player_data;
    Items player_info;
    while (file >> player_info.Name >> player_info.Number1 >> player_info.Number2) {
        player_data.push_back(player_info);
    }

    for (auto &i : player_data) {
        std::cout << i.Name << ", " << i.Number1 << ", " << i.Number2 << endl;
    }
}
</code>```

The file4.txt contains as follows:

```<code>Wogger Wabbit
2
6.2
Bilbo Baggins
111
81.3
Mary Poppins
29
154.8
</code>```

How can I display the data properly? How could I give the separation which is a line break ('\n')?

答:
From your description, I am assuming you want to print the outputs line by line. So use '\n' instead of comma:

std::cout << i.Name << "\n" << i.Number1 << "\n" << i.Number2 << endl;

Title: Read file with separation in C++

Body:
I have a script which reads text file into a vector.

#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <vector>
using namespace std;

struct Items
{
    string Name;
    int Number1;
    double Number2;
};

int main()
{
    ifstream file("file4.txt");
    vector<Items> player_data;
    Items player_info;
    while (file >> player_info.Name >> player_info.Number1 >> player_info.Number2) {
        player_data.push_back(player_info);
    }

    for (auto &i : player_data) {
        std::cout << i.Name << ", " << i.Number1 << ", " << i.Number2 << endl;
    }
}

The file4.txt contains as follows:

Wogger Wabbit
2
6.2
Bilbo Baggins
111
81.3
Mary Poppins
29
154.8

How can I display the data properly? How could I give the separation which is a line break ('\n')?


问:
How to copy a range of selected data to after the lastRow of data in the same Sheet using Google Apps Script?
I selected manually a range of data and want to press a button to copy those data to after the last row of data in the same sheet using Google Apps Script but not working at all. How to fix it? The codes are: </p>

```<code>var listToCopy = SpreadsheetApp.getActiveSheet().getActiveRange();
  var height = listToCopy.getHeight();
  var destRow = listToCopy.getLastRow()+1;
  listToCopy.copyTo(spreadsheet.getRange(destRow, 0, height));
</code>```

答:
I believe your goal as follows.

You want to copy the selected range to the last row of the same sheet using Google Apps Script.

For this, how about this answer?

Modification points:

In the case of var destRow = listToCopy.getLastRow()+1;, the last row of the range of listToCopy is retrieved.

In your case, the last row of the sheet is required to be retrieved.

The source range can be copied to the destination range as the start range like getRange(destRow, 1).

The 1st number of range is 1.

spreadsheet is not declared.

When above points are reflected to your script, it becomes as follows.

Modified script:

In order to use this script, please select the range and run the function of myFunction. By this, the selected range is copied to the last row of the same sheet.

```<code>function myFunction() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var listToCopy = sheet.getActiveRange();
  var destRow = sheet.getLastRow() + 1;
  listToCopy.copyTo(sheet.getRange(destRow, 1));
}
</code>```

References:

getLastRow() of Class Sheet

copyTo(destination)

Body:
I selected manually a range of data and want to press a button to copy those data to after the last row of data in the same sheet using Google Apps Script but not working at all. How to fix it? The codes are:

var listToCopy = SpreadsheetApp.getActiveSheet().getActiveRange();
  var height = listToCopy.getHeight();
  var destRow = listToCopy.getLastRow()+1;
  listToCopy.copyTo(spreadsheet.getRange(destRow, 0, height));

Body:
I believe your goal as follows.

You want to copy the selected range to the last row of the same sheet using Google Apps Script.

For this, how about this answer?

Modification points:

In the case of var destRow = listToCopy.getLastRow()+1;, the last row of the range of listToCopy is retrieved.

In your case, the last row of the sheet is required to be retrieved.

The source range can be copied to the destination range as the start range like getRange(destRow, 1).

The 1st number of range is 1.

spreadsheet is not declared.

When above points are reflected to your script, it becomes as follows.

Modified script:

In order to use this script, please select the range and run the function of myFunction. By this, the selected range is copied to the last row of the same sheet.

function myFunction() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var listToCopy = sheet.getActiveRange();
  var destRow = sheet.getLastRow() + 1;
  listToCopy.copyTo(sheet.getRange(destRow, 1));
}

References:

getLastRow() of Class Sheet

copyTo(destination)


问:
Count multiple Columns in Oracle SQL
I am looking to count the occurrence of IDs in 3 different columns using SQL. The raw table would look like:

```<code>id | A  | B  | C
------------------
1  | A1 | B1 | C1
2  | A1 | B2 | C1
3  | A1 | B1 | C2
4  | A2 | B1 | C2
5  | A1 | B2 | C2
</code>```

The desired Table should look like:

```<code>id | A  | count(A) | B  | count(B) | C  | count(C)
--------------------------------------------------
1  | A1 | 4        | B1 | 3        | C1 | 2
2  | A1 | 4        | B2 | 2        | C1 | 2
3  | A1 | 4        | B1 | 3        | C2 | 3
4  | A2 | 1        | B1 | 3        | C2 | 3
5  | A1 | 4        | B2 | 2        | C2 | 3
</code>```

I tried the below query for a single column but didn't quite get the desired results:

```<code>SELECT A, COUNT(A) from table_name GROUP BY A;
</code>```

But am unable to do the same for 3 columns.

答:
Use COUNT as analytic function:

```<code>SELECT
    id,
    A,
    COUNT(*) OVER (PARTITION BY A) cnt_A,
    B,
    COUNT(*) OVER (PARTITION BY B) cnt_B,
    C,
    COUNT(*) OVER (PARTITION BY C) cnt_C
FROM yourTable
ORDER BY id;
</code>```

Demo

You don't want GROUP BY here, at least not by itself, because that aggregates the original records all of which you want to include in the output.

Title: Count multiple Columns in Oracle SQL

Body:
I am looking to count the occurrence of IDs in 3 different columns using SQL. The raw table would look like:

id | A  | B  | C
------------------
1  | A1 | B1 | C1
2  | A1 | B2 | C1
3  | A1 | B1 | C2
4  | A2 | B1 | C2
5  | A1 | B2 | C2

The desired Table should look like:

id | A  | count(A) | B  | count(B) | C  | count(C)
--------------------------------------------------
1  | A1 | 4        | B1 | 3        | C1 | 2
2  | A1 | 4        | B2 | 2        | C1 | 2
3  | A1 | 4        | B1 | 3        | C2 | 3
4  | A2 | 1        | B1 | 3        | C2 | 3
5  | A1 | 4        | B2 | 2        | C2 | 3

I tried the below query for a single column but didn't quite get the desired results:

SELECT A, COUNT(A) from table_name GROUP BY A;

But am unable to do the same for 3 columns.

Body:
Use COUNT as analytic function:

SELECT
    id,
    A,
    COUNT(*) OVER (PARTITION BY A) cnt_A,
    B,
    COUNT(*) OVER (PARTITION BY B) cnt_B,
    C,
    COUNT(*) OVER (PARTITION BY C) cnt_C
FROM yourTable
ORDER BY id;

Demo

You don't want GROUP BY here, at least not by itself, because that aggregates the original records all of which you want to include in the output.


问:
Reverse ssh tunnel for p2p downloads
I am looking to implement a solution where I use a remote bittorrent client on the cloud server and then download the files to local system over http. This is expected to improve my bandwidth and overcome blacklisting my ip(suppose if I am behind proxy). My solution would be exactly like seedr.cc . One another improvement I want to provide is that the files/directories to be downloaded in parts locally(client application) simultaneously. This can also be done very easily if my solution is a client server application. Now, the real question, suppose if I want to not download the files/directories on the server at all, but on clients directly without mounting remote disk(client's disk). Here, remember the server is used for just the network, no storage is used at all. Do you know of any thing that can help?</p>

答:
Let me first describe your topology to be clear.

You build a server and some clients, the clients can download files using p2p. And you want a client can download file both from sever and other clients to accelerate the speed.

Firstly, the bt download can improve your speed but the limitation comes from your ISP. If you only buy a 100Mb bandwidth, you can not get a higher speed than it.

Secondly, if this topology can help you, then you can build such a systems.

NAT traversal is needed, it's the basic a p2p communication. You may need natpmp, upnp or ICE. Since you have a server, maybe ICE is better.

LSD and DHT will help you find other clients.

peer wire communiction protocol is needed to connect to other peers and download files.

There is a open source project named libtorrent may help you. It builds the whole system, you can use it or build your own by learning it.

As for downloading both form server and clients, there need to have a peer manager design, that is relatively hard, and I cannot make it short, you need to do many examples and optimization by yourself.

Title: Reverse ssh tunnel for p2p downloads


问:
How paranoid should I be about my Azure application binary files being stolen?
I need to migrate a huge application to Windows Azure. The application depends on a third-party library that requires an activation key stored in a special binary file on the role instance filesystem.

Obviously that key has to be either included into the role package or stored somewhere where role can fetch it. The activation key will not be bound to the machine (since I have no idea where exactly a role will be run in the cloud) so anyone can use it to make a copy of that library work.

Since Azure roles run somewhere not under our control I feel somewhat paranoid about the key being stolen and made widely available.

How do I evaluate how likely it is to steal a binary file that is included into Azure role? How do I mitigate such risks?

答:
As far security is concerned, unless your team is extremely capable in this area, the default always upgraded Azure OS is probably much more secure than any self-configured host. At least, this is how we (aka my company, Lokad) assess the situation two years after migrating in full to Windows Azure compared to our previous self-hosted situation.

Then, if you have credentials, such as licence keys, then the most logical place to put them is the Role configuration file - not the Role binaries. You can naturally regenerate the special file within the VM as needed, but this way, you don't internally spread your credentials all over the place as you archive your binary versions.


问:
get latitude and longitude of my location when internet is disable in flutter
How can I get current location updates when the internet is disabled on mobile in flutter? I have used the geolocator package to get latitude and longitude of the current location. </p>

答:
Geolocator does not need internet enabled on mobile.

You can track position changes listening this stream Geolocator().getPositionStream()

https://pub.dev/documentation/geolocator/latest/geolocator/Geolocator/getPositionStream.html


问:
Add default value option in select tag
I use a select tag in my application:

<Select
    showSearch={false}
    defaultValue={["Lucy"]}
    mode="multiple"
    style={{ width: 200 }}
    placeholder="Select a person"
    optionFilterProp="children"
    onChange={onChange}
    onFocus={onFocus}
    onBlur={onBlur}
    onSearch={onSearch}
    filterOption={(input, option) =>
      option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
    }
  >
    <Option value="jack">Jack</Option>
    <Option value="lucy">Lucy</Option>
    <Option value="tom">Tom</Option>
  </Select>,
  document.getElementById("container")```

I want to set a default selected value for this Select, to get something like this:

 So, when i will open first time this dropdown, i want to have a default value selected in the way like in the image. I tried defaultValue but it does not work as i described., So, how to achive what i described above?

demo: https://codesandbox.io/s/select-with-search-field-ant-design-demo-4f9op?file=/index.js:410-955

答:
You are providing ['Lucy'] (uppercased) as default value but the values provided in the options are 'lucy', 'jack', and 'tom' all lowercased. That is why the Select treats the default value as another value.

Solution either provide the default value same as used in options defaultValue={["lucy"]} or use uppercased values in Option if you want the defaultValue to be uppercased as well.

<Select
    showSearch={false}
    defaultValue={["lucy"]}
    mode="multiple"
    style={{ width: 200 }}
    placeholder="Select a person"
    optionFilterProp="children"
    onChange={onChange}
    onFocus={onFocus}
    onBlur={onBlur}
    onSearch={onSearch}
    filterOption={(input, option) =>
      option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
    }
  >
    <Option value="jack">Jack</Option>
    <Option value="lucy">Lucy</Option>
    <Option value="tom">Tom</Option>
  </Select>,
  document.getElementById("container")
```

Codesandbox demo, codesandbox

Title: Add default value option in select tag

Body:
I use a select tag in my application:

<Select
    showSearch={false}
    defaultValue={["Lucy"]}
    mode="multiple"
    style={{ width: 200 }}
    placeholder="Select a person"
    optionFilterProp="children"
    onChange={onChange}
    onFocus={onFocus}
    onBlur={onBlur}
    onSearch={onSearch}
    filterOption={(input, option) =>
      option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
    }
  >
    <Option value="jack">Jack</Option>
    <Option value="lucy">Lucy</Option>
    <Option value="tom">Tom</Option>
  </Select>,
  document.getElementById("container")

I want to set a default selected value for this Select, to get something like this:

 So, when i will open first time this dropdown, i want to have a default value selected in the way like in the image. I tried defaultValue but it does not work as i described., So, how to achive what i described above?

demo: https://codesandbox.io/s/select-with-search-field-ant-design-demo-4f9op?file=/index.js:410-955

Body:
You are providing ['Lucy'] (uppercased) as default value but the values provided in the options are 'lucy', 'jack', and 'tom' all lowercased. That is why the Select treats the default value as another value.

Solution either provide the default value same as used in options defaultValue={["lucy"]} or use uppercased values in Option if you want the defaultValue to be uppercased as well.

<Select
    showSearch={false}
    defaultValue={["lucy"]}
    mode="multiple"
    style={{ width: 200 }}
    placeholder="Select a person"
    optionFilterProp="children"
    onChange={onChange}
    onFocus={onFocus}
    onBlur={onBlur}
    onSearch={onSearch}
    filterOption={(input, option) =>
      option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
    }
  >
    <Option value="jack">Jack</Option>
    <Option value="lucy">Lucy</Option>
    <Option value="tom">Tom</Option>
  </Select>,
  document.getElementById("container")

Codesandbox demo, codesandbox


问:
BigQuery coud not parse into datetime from a csv file
While loading data into bigquery, I provided my own schema to avoid confusions with data types. Even now BQ is unable to load values from a datetime format. Although they are quite straight forward as: '1/9/2014 5:26' Here is the full error message:

Could not parse '1/9/2014 5:26'

I thought it might be because of some bad values but have checked the column through and there had been no bad vaules. And it is giving the error on the very first one so it is unable to parse that value without doubt. Notably the values are able to be parsed as string type but not just as the date or datetime types.

答:
Load it as a string, use PARSE_DATE, and write it out as new table:</p>

```<code>CREATE OR REPLACE TABLE  dataset.new_table AS
SELECT
   *,
   PARSE_DATE("%m/%d/%y %h:%M", str_col) AS date
FROM
   dataset.loaded_table
</code>```

Body:
Load it as a string, use PARSE_DATE, and write it out as new table:

CREATE OR REPLACE TABLE  dataset.new_table AS
SELECT
   *,
   PARSE_DATE("%m/%d/%y %h:%M", str_col) AS date
FROM
   dataset.loaded_table


问:
How to optimize a docker image?

I am building a webapp with several docker images via docker-compose.

One of the Docker images is webserver_web.

The size of the image (~1.2 GB) looks pretty big to me and, I wonder what tricks I can apply to reduce the size.

I suspect that I'm not using the Dockerfile efficiently.

Observations regarding the layers size:

The webserver_web image is using FROM python:3.7.6 for the first layer.

The size of the python 3.7.6 image is 919MB

There are 34 layers (column "IMAGE") in the history

The first 18 layers have a total size of ~918MB (which fits the size of the python 3.7.6 image)

The 19th image corresponds to the second command in the Dockerfile ("MAINTAINER User4 ")

the first 18 images are coming from the first command in the Dockerfile ("FROM python:3.7.6")

the shear size of the image (~80%) comes from the python image

The contribution of the base image to the overall image size: ~80% (918 / 1136.64)

The size of the image webserver_web: 1136.64 MB (1.11*1024)

58.2MB is coming from the need to install sudo, vim, and nano into the container:

RUN apt-get update && apt-get install -y vim nano sudo

Here are the image sizes, the Dockerfile, and the layers of the docker image.

Any ideas what can be done to reduce the size of the webserver_web Docker image?

Is size of more than 1GB acceptable for a docker image?

Thanks,

Avner

The image sizes:

```<code>docker images
REPOSITORY                   TAG                 IMAGE ID            CREATED             SIZE
...
webserver_web                latest              ec306049da3e        15 minutes ago      1.11GB
python                       3.7.6               879165535a54        3 months ago        919MB
</code>```

The Dockerfile:

```<code>cat Dockerfile
FROM python:3.7.6
MAINTAINER User4 <user4@gmail.com>

# Create the group and user to be used in this container
RUN groupadd flaskgroup && useradd -m -g flaskgroup -s /bin/bash flask

RUN apt-get update && apt-get install -y vim nano sudo

# http://gbraad.nl/blog/non-root-user-inside-a-docker-container.html
# Add user flask to sudoers
RUN echo "flask ALL=(root) NOPASSWD:ALL" > /etc/sudoers.d/flask && \
    chmod 0440 /etc/sudoers.d/flask

# Create the working directory (and set it as the working directory)
RUN mkdir -p /home/flask/app/web
WORKDIR /home/flask/app/web

# Install the package dependencies (this step is separated
# from copying all the source code to avoid having to
# re-install all python packages defined in requirements.txt
# whenever any source code change is made)
COPY requirements.txt /home/flask/app/web
RUN pip install --no-cache-dir -r requirements.txt

# Copy the source code into the container
COPY . /home/flask/app/web

RUN chown -R flask:flaskgroup /home/flask

USER flask
</code>```

Layers of the docker image (with size for each layer):

```<code>avner@avner-ThinkPad-P51:~$ docker history webserver_web
IMAGE               CREATED              CREATED BY                                      SIZE                COMMENT
0688e195012d        About a minute ago   /bin/sh -c #(nop)  USER flask                   0B
3052d2e91fd0        About a minute ago   /bin/sh -c chown -R flask:flaskgroup /home/f…   35.3MB
81a5cf0a37b9        About a minute ago   /bin/sh -c #(nop) COPY dir:668861ff8c7f55004…   35.3MB
24341ee304ae        About a minute ago   /bin/sh -c pip install --no-cache-dir -r req…   64.2MB
925e12e74fe8        About a minute ago   /bin/sh -c #(nop) COPY file:4e7a69dabf52b355…   1.07kB
0419bbb589d3        About a minute ago   /bin/sh -c #(nop) WORKDIR /home/flask/app/web   0B
b87691531f4a        About a minute ago   /bin/sh -c mkdir -p /home/flask/app/web         0B
251001545b6f        About a minute ago   /bin/sh -c echo "flask ALL=(root) NOPASSWD:A…   30B
980fc4c0dd9c        About a minute ago   /bin/sh -c apt-get update && apt-get install…   58.2MB
9015bd3d1e3b        2 minutes ago        /bin/sh -c groupadd flaskgroup && useradd -m…   334kB
7ad23eec9ab4        2 minutes ago        /bin/sh -c #(nop)  MAINTAINER User4 <user4@g…   0B
879165535a54        3 months ago         /bin/sh -c #(nop)  CMD ["python3"]              0B
<missing>           3 months ago         /bin/sh -c set -ex;   wget -O get-pip.py "$P…   6.34MB
<missing>           3 months ago         /bin/sh -c #(nop)  ENV PYTHON_GET_PIP_SHA256…   0B
<missing>           3 months ago         /bin/sh -c #(nop)  ENV PYTHON_GET_PIP_URL=ht…   0B
<missing>           4 months ago         /bin/sh -c #(nop)  ENV PYTHON_PIP_VERSION=20…   0B
<missing>           4 months ago         /bin/sh -c cd /usr/local/bin  && ln -s idle3…   32B
<missing>           4 months ago         /bin/sh -c set -ex   && wget -O python.tar.x…   91MB
<missing>           4 months ago         /bin/sh -c #(nop)  ENV PYTHON_VERSION=3.7.6     0B
<missing>           4 months ago         /bin/sh -c #(nop)  ENV GPG_KEY=0D96DF4D4110E…   0B
<missing>           4 months ago         /bin/sh -c apt-get update && apt-get install…   17.9MB
<missing>           4 months ago         /bin/sh -c #(nop)  ENV LANG=C.UTF-8             0B
<missing>           4 months ago         /bin/sh -c #(nop)  ENV PATH=/usr/local/bin:/…   0B
<missing>           4 months ago         /bin/sh -c set -ex;  apt-get update;  apt-ge…   510MB
<missing>           4 months ago         /bin/sh -c apt-get update && apt-get install…   145MB
<missing>           4 months ago         /bin/sh -c set -ex;  if ! command -v gpg > /…   17.5MB
<missing>           4 months ago         /bin/sh -c apt-get update && apt-get install…   16.5MB
<missing>           4 months ago         /bin/sh -c #(nop)  CMD ["bash"]                 0B
<missing>           4 months ago         /bin/sh -c #(nop) ADD file:a5ec219cbfc4e0c31…   114MB
</code>```

答:
Most of the time python docker images are big. If you want to slim down your images you can use multistage builds. But it will slow your build time. Also you can reduce the layer in the image (eg. Don't use multiple RUN statements, instead use once and do all your execution in one statement). But it will make nearly all the caching mechanism of docker useless. And it will increase build time significantly.

TL;DR;

Python images are big. Bigger is faster. Smaller is slower. 1GB is not so large for a python image.

I highly recommend this links for python docker images:

https://pythonspeed.com/articles/base-image-python-docker-images/

https://pythonspeed.com/articles/base-image-python-docker-images/

https://towardsdatascience.com/slimming-down-your-docker-images-275f0ca9337e

I was referring build time in "Bigger is faster. Smaller is slower.". I recommend this article that is about docker image sizes. Actually it is not a big overhead for network to have big images (images with many layers) as it looks. It will be an overhead only the first time uploaded it. After that all little changes will be small due to layer caching in registry/server. If you use multistage, pruning/purging or squeezing your image will be smaller. But when you change it even a little bit, it will upload nearly all layers from beginning (Because there is few number of layers in image). So if you change your images often the bigger images can reduce your bandwidth usage. But if you do not change your images often, make it small as possible (Remove unused tools in the end, stage your sections, use minimal number of statment in last stage).

Title: How to optimize a docker image?

Body:
I am building a webapp with several docker images via docker-compose.

One of the Docker images is webserver_web.

The size of the image (~1.2 GB) looks pretty big to me and, I wonder what tricks I can apply to reduce the size.

I suspect that I'm not using the Dockerfile efficiently.

Observations regarding the layers size:

The webserver_web image is using FROM python:3.7.6 for the first layer.

The size of the python 3.7.6 image is 919MB

There are 34 layers (column "IMAGE") in the history

The first 18 layers have a total size of ~918MB (which fits the size of the python 3.7.6 image)

The 19th image corresponds to the second command in the Dockerfile ("MAINTAINER User4 ")

the first 18 images are coming from the first command in the Dockerfile ("FROM python:3.7.6")

the shear size of the image (~80%) comes from the python image

The contribution of the base image to the overall image size: ~80% (918 / 1136.64)

The size of the image webserver_web: 1136.64 MB (1.11*1024)

58.2MB is coming from the need to install sudo, vim, and nano into the container:

RUN apt-get update && apt-get install -y vim nano sudo

Here are the image sizes, the Dockerfile, and the layers of the docker image.

Any ideas what can be done to reduce the size of the webserver_web Docker image?

Is size of more than 1GB acceptable for a docker image?

Thanks,

Avner

The image sizes:

docker images
REPOSITORY                   TAG                 IMAGE ID            CREATED             SIZE
...
webserver_web                latest              ec306049da3e        15 minutes ago      1.11GB
python                       3.7.6               879165535a54        3 months ago        919MB

The Dockerfile:

cat Dockerfile
FROM python:3.7.6
MAINTAINER User4 <user4@gmail.com>

# Create the group and user to be used in this container
RUN groupadd flaskgroup && useradd -m -g flaskgroup -s /bin/bash flask

RUN apt-get update && apt-get install -y vim nano sudo

# http://gbraad.nl/blog/non-root-user-inside-a-docker-container.html
# Add user flask to sudoers
RUN echo "flask ALL=(root) NOPASSWD:ALL" > /etc/sudoers.d/flask && \
    chmod 0440 /etc/sudoers.d/flask

# Create the working directory (and set it as the working directory)
RUN mkdir -p /home/flask/app/web
WORKDIR /home/flask/app/web

# Install the package dependencies (this step is separated
# from copying all the source code to avoid having to
# re-install all python packages defined in requirements.txt
# whenever any source code change is made)
COPY requirements.txt /home/flask/app/web
RUN pip install --no-cache-dir -r requirements.txt

# Copy the source code into the container
COPY . /home/flask/app/web

RUN chown -R flask:flaskgroup /home/flask

USER flask

Layers of the docker image (with size for each layer):

avner@avner-ThinkPad-P51:~$ docker history webserver_web
IMAGE               CREATED              CREATED BY                                      SIZE                COMMENT
0688e195012d        About a minute ago   /bin/sh -c #(nop)  USER flask                   0B
3052d2e91fd0        About a minute ago   /bin/sh -c chown -R flask:flaskgroup /home/f…   35.3MB
81a5cf0a37b9        About a minute ago   /bin/sh -c #(nop) COPY dir:668861ff8c7f55004…   35.3MB
24341ee304ae        About a minute ago   /bin/sh -c pip install --no-cache-dir -r req…   64.2MB
925e12e74fe8        About a minute ago   /bin/sh -c #(nop) COPY file:4e7a69dabf52b355…   1.07kB
0419bbb589d3        About a minute ago   /bin/sh -c #(nop) WORKDIR /home/flask/app/web   0B
b87691531f4a        About a minute ago   /bin/sh -c mkdir -p /home/flask/app/web         0B
251001545b6f        About a minute ago   /bin/sh -c echo "flask ALL=(root) NOPASSWD:A…   30B
980fc4c0dd9c        About a minute ago   /bin/sh -c apt-get update && apt-get install…   58.2MB
9015bd3d1e3b        2 minutes ago        /bin/sh -c groupadd flaskgroup && useradd -m…   334kB
7ad23eec9ab4        2 minutes ago        /bin/sh -c #(nop)  MAINTAINER User4 <user4@g…   0B
879165535a54        3 months ago         /bin/sh -c #(nop)  CMD ["python3"]              0B
<missing>           3 months ago         /bin/sh -c set -ex;   wget -O get-pip.py "$P…   6.34MB
<missing>           3 months ago         /bin/sh -c #(nop)  ENV PYTHON_GET_PIP_SHA256…   0B
<missing>           3 months ago         /bin/sh -c #(nop)  ENV PYTHON_GET_PIP_URL=ht…   0B
<missing>           4 months ago         /bin/sh -c #(nop)  ENV PYTHON_PIP_VERSION=20…   0B
<missing>           4 months ago         /bin/sh -c cd /usr/local/bin  && ln -s idle3…   32B
<missing>           4 months ago         /bin/sh -c set -ex   && wget -O python.tar.x…   91MB
<missing>           4 months ago         /bin/sh -c #(nop)  ENV PYTHON_VERSION=3.7.6     0B
<missing>           4 months ago         /bin/sh -c #(nop)  ENV GPG_KEY=0D96DF4D4110E…   0B
<missing>           4 months ago         /bin/sh -c apt-get update && apt-get install…   17.9MB
<missing>           4 months ago         /bin/sh -c #(nop)  ENV LANG=C.UTF-8             0B
<missing>           4 months ago         /bin/sh -c #(nop)  ENV PATH=/usr/local/bin:/…   0B
<missing>           4 months ago         /bin/sh -c set -ex;  apt-get update;  apt-ge…   510MB
<missing>           4 months ago         /bin/sh -c apt-get update && apt-get install…   145MB
<missing>           4 months ago         /bin/sh -c set -ex;  if ! command -v gpg > /…   17.5MB
<missing>           4 months ago         /bin/sh -c apt-get update && apt-get install…   16.5MB
<missing>           4 months ago         /bin/sh -c #(nop)  CMD ["bash"]                 0B
<missing>           4 months ago         /bin/sh -c #(nop) ADD file:a5ec219cbfc4e0c31…   114MB


问:
DatePicker on Mac not saving date until return key is pressed
I'm adapting my iPad app to Mac with Mac Catalyst and am having a problem with the datePicker (it has a datePickerMode of time). On iPad the datePicker is a wheel and whenever the user scrolls on the date picker the dateChanged action is fired. But on Mac the date picker is not a scroller and is instead a type of text input. I can type and change all the time values on Mac, but the dateChanged action won't be fired until I press the return key.

I would like to get the dateChange action fired whenever a user is entering in a time. How can I do this? I tried adding different targets to the datePicker but nothing work.

I actually prefer to have the date scroller on the Mac so if anyone knows how to do this instead I would greatly appreciate it (I looked all over the internet for this and found nothing)!

Here's my code:

```<code>class DateVC: UIViewController {
     @IBOutlet weak var datePicker: UIDatePicker!

     override func viewDidLoad() {
          super.viewDidLoad()

          //Just show the time
          datePicker.datePickerMode = .time
    }

     //Action connected to datePicker. This is not called until I press enter on Mac
     @IBAction func datePickerChanged(_ sender: Any) {
        //do actions
     }

}
</code>```

答:
Because your function linked with @IBAction which is to be called upon action, like 'button press'

you should follow different approach.

```<code>let datePicker = UIDatePicker()
    datePicker.datePickerMode = .date
    dateTextField.inputView = datePicker

datePicker.addTarget(self, action: #selector(datePickerChanged(picker:)), for: .valueChanged)
</code>```

and here is your function:

```<code>@objc func datePickerChanged(picker: UIDatePicker) {
    //do your action here
}
</code>```

Body:
I'm adapting my iPad app to Mac with Mac Catalyst and am having a problem with the datePicker (it has a datePickerMode of time). On iPad the datePicker is a wheel and whenever the user scrolls on the date picker the dateChanged action is fired. But on Mac the date picker is not a scroller and is instead a type of text input. I can type and change all the time values on Mac, but the dateChanged action won't be fired until I press the return key.

I would like to get the dateChange action fired whenever a user is entering in a time. How can I do this? I tried adding different targets to the datePicker but nothing work.

I actually prefer to have the date scroller on the Mac so if anyone knows how to do this instead I would greatly appreciate it (I looked all over the internet for this and found nothing)!

Here's my code:

class DateVC: UIViewController {
     @IBOutlet weak var datePicker: UIDatePicker!

     override func viewDidLoad() {
          super.viewDidLoad()

          //Just show the time
          datePicker.datePickerMode = .time
    }

     //Action connected to datePicker. This is not called until I press enter on Mac
     @IBAction func datePickerChanged(_ sender: Any) {
        //do actions
     }

}

Body:
Because your function linked with @IBAction which is to be called upon action, like 'button press'

you should follow different approach.

let datePicker = UIDatePicker()
    datePicker.datePickerMode = .date
    dateTextField.inputView = datePicker

datePicker.addTarget(self, action: #selector(datePickerChanged(picker:)), for: .valueChanged)

and here is your function:

@objc func datePickerChanged(picker: UIDatePicker) {
    //do your action here
}


问:
Calling ASP.net Web Service from C# Application
I have a question. How can i invoke a web service and get the result from a C# desktop application. I am making a desktop app and I want it to be able to connect to my online ASP.net web services. How is this possible?</p>

答:
In Solution Explorer, right-click your project node and select Add Service Reference.

Enter the URL where your service WSDL is located.  This is usually the URL of the service itself.

This generates a strongly-typed proxy class in a new Services References folder in your project.

Write code in your desktop app to instantiate the proxy class and invoke methods on it.  The rest works like magic. :)

AB Kolan was also correct, but Add Web Reference uses the old-style web services framework whereas Add Service References uses the new WCF stack.  Important note: It is not required that the service itself use WCF for you to use WCF on the client side.  WCF on the client is typically the best choice for any service, provided you can take a dependency on .NET 3.0 and above.

OwnerDisplayName: QAH

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Andrew Arnott


问:
JSONObject etc instantiation crashing
I am trying to learn how to use JSON and writing a simple program however whenever I instantiate a JSON Object it crashes.
What am I missing if I receive this error when trying to instantiate a JSONObject or JSONArray. I have added http://sourceforge.net/projects/json-lib/files/ this JSON library to the build path. Is there anything I am missing?

The error message is as follows:

```<code>Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/lang/exception/NestableRuntimeException
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClassCond(Unknown Source)
    at java.lang.ClassLoader.defineClass(Unknown Source)
    at java.security.SecureClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.access$000(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at jsonexp.JSONexp.<init>(JSONexp.java:36)
    at jsonexp.JSONexp.main(JSONexp.java:55)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.lang.exception.NestableRuntimeException
</code>```

I have learned that this sort of error occurs when the library being used depends on another library.

I do not know how to deal with this problem and would very much appreciate some help.

Thanks.

答:
Yes, the jar you are including has it's own runtime dependencies that are not satisfied.

java.lang.ClassNotFoundException: org.apache.commons.lang.exception.NestableRuntimeException

When seeing these type errors, I usually google around until I find the library responsible. This particular case it is the Apache Commons Lang library. Including this jar in your class path should solve the problem

Title: JSONObject etc instantiation crashing

Body:
I am trying to learn how to use JSON and writing a simple program however whenever I instantiate a JSON Object it crashes.
What am I missing if I receive this error when trying to instantiate a JSONObject or JSONArray. I have added http://sourceforge.net/projects/json-lib/files/ this JSON library to the build path. Is there anything I am missing?

The error message is as follows:

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/lang/exception/NestableRuntimeException
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClassCond(Unknown Source)
    at java.lang.ClassLoader.defineClass(Unknown Source)
    at java.security.SecureClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.access$000(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at jsonexp.JSONexp.<init>(JSONexp.java:36)
    at jsonexp.JSONexp.main(JSONexp.java:55)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.lang.exception.NestableRuntimeException

I have learned that this sort of error occurs when the library being used depends on another library.

I do not know how to deal with this problem and would very much appreciate some help.

Thanks.


问:
Authenticate with Azure AD using .Net Core 3.00 from behind Corporate Proxy
I have a .Net core app. I trying to use AzureAd Authentication. It's working fine on LocalHost but when I deployed the app on my company server I faced an issue of Proxy Credentials.
I used the below code but Not working:

```<code>services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
                .AddAzureAD(options => Configuration.Bind("AzureAd", options))
                .AddOpenIdConnect(options => options.BackchannelHttpHandler = new HttpClientHandler
                {
                    UseProxy = true,
                    Proxy = new WebProxy
                    {
                        Credentials = new NetworkCredential
                        {
                            UserName = "my_UserName",
                            Password = "my_Password "
                        },
                        Address = new Uri("my_Domain:my_Port")
                    }
                });
</code>```

appsettings:

```<code>"AzureAd": {
   "Instance": "https://login.microsoftonline.com/",
   "Domain": "My_Domain",
   "TenantId": "*************",
   "ClientId": "******",
   "CallbackPath": "/signin-oidc"
 }
</code>```

答:
After deep searching, I found the the solution:</p>
```<code>services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
        .AddAzureAD(options => Configuration.Bind("AzureAd", options))
        .AddCookie(options =>
             {
               options.SlidingExpiration = true;
               options.ExpireTimeSpan = TimeSpan.FromMinutes(60);
              });

services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options =>
            {
                options.BackchannelHttpHandler = new HttpClientHandler
                {
                    UseProxy = true,
                    Proxy = new WebProxy()
                    {
                        Credentials = new NetworkCredential
                        {
                            UserName = "My_UserName",
                            Password = "My_Password"
                        },
                        Address = new Uri("My_Domain:My_Port")
                    }
                };
            });

            services.AddHttpClient();

</code>```

Body:
I have a .Net core app. I trying to use AzureAd Authentication. It's working fine on LocalHost but when I deployed the app on my company server I faced an issue of Proxy Credentials.
I used the below code but Not working:

services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
                .AddAzureAD(options => Configuration.Bind("AzureAd", options))
                .AddOpenIdConnect(options => options.BackchannelHttpHandler = new HttpClientHandler
                {
                    UseProxy = true,
                    Proxy = new WebProxy
                    {
                        Credentials = new NetworkCredential
                        {
                            UserName = "my_UserName",
                            Password = "my_Password "
                        },
                        Address = new Uri("my_Domain:my_Port")
                    }
                });

appsettings:

"AzureAd": {
   "Instance": "https://login.microsoftonline.com/",
   "Domain": "My_Domain",
   "TenantId": "*************",
   "ClientId": "******",
   "CallbackPath": "/signin-oidc"
 }

Body:
After deep searching, I found the the solution:

services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
        .AddAzureAD(options => Configuration.Bind("AzureAd", options))
        .AddCookie(options =>
             {
               options.SlidingExpiration = true;
               options.ExpireTimeSpan = TimeSpan.FromMinutes(60);
              });

services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options =>
            {
                options.BackchannelHttpHandler = new HttpClientHandler
                {
                    UseProxy = true,
                    Proxy = new WebProxy()
                    {
                        Credentials = new NetworkCredential
                        {
                            UserName = "My_UserName",
                            Password = "My_Password"
                        },
                        Address = new Uri("My_Domain:My_Port")
                    }
                };
            });

            services.AddHttpClient();


问:
How to install specific helm client version so it is compatible with the server (Tiller)
My helm client and server are different versions. I need to update my client so it is same version as the server.

```<code>$ helm version
Client: &version.Version{SemVer:"v2.15.2", GitCommit:"8dce272473e5f2a7bf58ce79bb5c3691db54c96b", GitTreeState:"clean"}
Server: &version.Version{SemVer:"v2.16.3", GitCommit:"1ee0254c86d4ed6887327dabed7aa7da29d7eb0d", GitTreeState:"clean"}
</code>```

I tried to update via the installer script here: https://raw.githubusercontent.com/helm/helm/master/scripts/get

but when I do that, it will give me this message:

```<code>Downloading helm
Helm v2.16.3 is already v2.16.3
</code>```

How to install specific helm client version so it is compatible with the server (Tiller)? In this case version 2.16.3.

答:
If you want to have the specific Helm version, you can follow Helm: From the binary releases. You can see and download all Helm client versions from here.

Btw. as a side note, I strongly suggest moving to Helm 3. There is no Tiller there, so you don't have to "sync" the versions between client and server.

Body:
My helm client and server are different versions. I need to update my client so it is same version as the server.

$ helm version
Client: &version.Version{SemVer:"v2.15.2", GitCommit:"8dce272473e5f2a7bf58ce79bb5c3691db54c96b", GitTreeState:"clean"}
Server: &version.Version{SemVer:"v2.16.3", GitCommit:"1ee0254c86d4ed6887327dabed7aa7da29d7eb0d", GitTreeState:"clean"}

I tried to update via the installer script here: https://raw.githubusercontent.com/helm/helm/master/scripts/get

but when I do that, it will give me this message:

Downloading helm
Helm v2.16.3 is already v2.16.3

How to install specific helm client version so it is compatible with the server (Tiller)? In this case version 2.16.3.


问:
SassError: argument `$color` of `darken($color, $amount)` must be a color
I am attempting to add a custom color map in Bulma, with the following SCSS code:

// Set your colors
$primary: #5B43CC;
$primary-invert: findColorInvert($primary);
$twitter: #4099FF;
$twitter-invert: findColorInvert($twitter);
$facebook: #4267B2;
$facebook-invert: findColorInvert($facebook);

$custom-colors: (
  "foo": (black, grey),
);

// Import Bulma's core
@import "~bulma/sass/utilities/_all";

// Links
$link: $primary;
$link-invert: $primary-invert;
$link-focus-border: $primary;

// Import Bulma and Buefy styles
// this has been moved to App.vue because it must be at the end
@import "~bulma";
@import "~buefy/src/scss/buefy";
```

<p>But I get the following error:</p>

<pre class="lang-js prettyprint-override"><code> ERROR  Failed to compile with 6 errors                                                                                1:26:26 AM

 error  in ./src/App.vue?vue&type=style&index=0&lang=scss&

Module build failed (from ./node_modules/sass-loader/dist/cjs.js):
SassError: argument `$color` of `darken($color, $amount)` must be a color
        on line 150 of node_modules/bulma/sass/elements/button.sass, in function `darken`
        from line 150 of node_modules/bulma/sass/elements/button.sass
        from line 4 of node_modules/bulma/sass/elements/_all.sass
        from line 5 of node_modules/bulma/bulma.sass
        from line 40 of src/assets/scss/main.scss
        from line 2 of /c/Users/Raj/Projects/testsite/src/App.vue
>>           background-color: darken($color-invert, 5%); }

   ----------------------------^

 @ ./node_modules/vue-style-loader??ref--8-oneOf-1-0!./node_modules/css-loader/dist/cjs.js??ref--8-oneOf-1-1!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/src??ref--8-oneOf-1-2!./node_modules/sass-loader/dist/cjs.js??ref--8-oneOf-1-3!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/App.vue?vue&type=style&index=0&lang=scss& 4:14-416 14:3-18:5 15:22-424
 @ ./src/App.vue?vue&type=style&index=0&lang=scss&
 @ ./src/App.vue
 @ ./src/main.js
 @ multi (webpack)-dev-server/client?http://localhost:8080/sockjs-node (webpack)/hot/dev-server.js ./src/main.js
</code>```

However, if I comment out // $primary-invert: findColorInvert($primary); then the error goes away. Also, if the snippet under // set your colors is moved after @import "~bulma/sass/utilities/_all", then the error also goes away.

What am I doing wrong here?

Note, this is a follow-up to this previous post

答:
So as I mentioned in the comments, when it comes to Sass compilation it's all about ordering (of imports and/or variable declarations). Now, since those color inversions are using a Bulma utility called findColorInvert, which resides within utilities/functions.sass, we can't probably import the utilities with the original order here.

We could split them and insert our customs in between the functions and derived-variables:

```<code>@import "~bulma/sass/utilities/initial-variables";
@import "~bulma/sass/utilities/functions";

// Set your colors
$primary: #5B43CC;
$primary-invert: findColorInvert($primary);
$twitter: #4099FF;
$twitter-invert: findColorInvert($twitter);
$facebook: #4267B2;
$facebook-invert: findColorInvert($facebook);

// Links
$link: $primary;
$link-invert: $primary-invert;
$link-focus-border: $primary;

$custom-colors: (
  "foo": (black, grey),
);

@import "~bulma/sass/utilities/derived-variables";
@import "~bulma/sass/utilities/animations";
@import "~bulma/sass/utilities/mixins";
@import "~bulma/sass/utilities/controls";
</code>```

Body:
I am attempting to add a custom color map in Bulma, with the following SCSS code:

// Set your colors
$primary: #5B43CC;
$primary-invert: findColorInvert($primary);
$twitter: #4099FF;
$twitter-invert: findColorInvert($twitter);
$facebook: #4267B2;
$facebook-invert: findColorInvert($facebook);

$custom-colors: (
  "foo": (black, grey),
);

// Import Bulma's core
@import "~bulma/sass/utilities/_all";

// Links
$link: $primary;
$link-invert: $primary-invert;
$link-focus-border: $primary;

// Import Bulma and Buefy styles
// this has been moved to App.vue because it must be at the end
@import "~bulma";
@import "~buefy/src/scss/buefy";

But I get the following error:

 ERROR  Failed to compile with 6 errors                                                                                1:26:26 AM

 error  in ./src/App.vue?vue&type=style&index=0&lang=scss&

Module build failed (from ./node_modules/sass-loader/dist/cjs.js):
SassError: argument `$color` of `darken($color, $amount)` must be a color
        on line 150 of node_modules/bulma/sass/elements/button.sass, in function `darken`
        from line 150 of node_modules/bulma/sass/elements/button.sass
        from line 4 of node_modules/bulma/sass/elements/_all.sass
        from line 5 of node_modules/bulma/bulma.sass
        from line 40 of src/assets/scss/main.scss
        from line 2 of /c/Users/Raj/Projects/testsite/src/App.vue
>>           background-color: darken($color-invert, 5%); }

   ----------------------------^

 @ ./node_modules/vue-style-loader??ref--8-oneOf-1-0!./node_modules/css-loader/dist/cjs.js??ref--8-oneOf-1-1!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/src??ref--8-oneOf-1-2!./node_modules/sass-loader/dist/cjs.js??ref--8-oneOf-1-3!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/App.vue?vue&type=style&index=0&lang=scss& 4:14-416 14:3-18:5 15:22-424
 @ ./src/App.vue?vue&type=style&index=0&lang=scss&
 @ ./src/App.vue
 @ ./src/main.js
 @ multi (webpack)-dev-server/client?http://localhost:8080/sockjs-node (webpack)/hot/dev-server.js ./src/main.js

However, if I comment out // $primary-invert: findColorInvert($primary); then the error goes away. Also, if the snippet under // set your colors is moved after @import "~bulma/sass/utilities/_all", then the error also goes away.

What am I doing wrong here?

Note, this is a follow-up to this previous post

Body:
So as I mentioned in the comments, when it comes to Sass compilation it's all about ordering (of imports and/or variable declarations). Now, since those color inversions are using a Bulma utility called findColorInvert, which resides within utilities/functions.sass, we can't probably import the utilities with the original order here.

We could split them and insert our customs in between the functions and derived-variables:

@import "~bulma/sass/utilities/initial-variables";
@import "~bulma/sass/utilities/functions";

// Set your colors
$primary: #5B43CC;
$primary-invert: findColorInvert($primary);
$twitter: #4099FF;
$twitter-invert: findColorInvert($twitter);
$facebook: #4267B2;
$facebook-invert: findColorInvert($facebook);

// Links
$link: $primary;
$link-invert: $primary-invert;
$link-focus-border: $primary;

$custom-colors: (
  "foo": (black, grey),
);

@import "~bulma/sass/utilities/derived-variables";
@import "~bulma/sass/utilities/animations";
@import "~bulma/sass/utilities/mixins";
@import "~bulma/sass/utilities/controls";


问:
Is it possible to create an animated gif from a youtube or vimeo location using php?
Just a thought on whether this would be possible really, I thought it would be really cool if I could create animated gifs for embedded videos on the fly. Has anyone seen this done before?</p>

答:
I would look in to calling imagemagick on the command line via php. </p>

<p>That will do all the heavy lifting for you. </p>

Body:
I would look in to calling imagemagick on the command line via php.

That will do all the heavy lifting for you.


问:
Indefinitely retain release and build
I have the following setting under 'Release Retention'

I would like to know two things:

If I retain a release and it's build indefinitely from the Release pipeline, does it mean that I can retain it longer than the default of 365 days shown below?

I would also like to know what is the Azure DevOps action if I have the 26th release and build that I want to retain indefinitely?

In short, I am little confused on the "Retain Indefinitely" vs the 365 days and 25 builds setting.

Thanks

答:
If I retain a release and it's build indefinitely from the Release pipeline, does it mean that I can retain it longer than the default of 365 days shown below?

Yes. You are right. If you use the Retain indefinitely option,  the release will keep forever(irrespective of the number of days specified).

I would also like to know what is the Azure DevOps action if I have the 26th release and build that I want to retain indefinitely?

You just need to find the 26th release and set the Retain indefinitely option. Then the release will retain indefinitely and the related build will also be retained.

"Retain Indefinitely" vs the 365 days and 25 builds setting

The Retain Indefinitely option is used to keep the target release forever. It will not be affected by the retention policy.

For Days to retain a release   365 and Minimum releases to keep  25, the Days to retain a release and Minimum releases to keep are equals two fields. and the 365 and 25 are the maximum value of these two fields.

These two fields are used for the retention policy in Release -> Stage -> Retention.

Each stage has a different rentention policy. And the max value is 365 and 25. You could set them for every stages.

Here is a doc about release, you could refer to it.

Title: Indefinitely retain release and build


问:
How to convert Linq query for joining 3 tables to Linq method and use Include
I have seen a few posts that are similar but I haven't been able to figure out how to solve my problem. I have three tables in an ASP.NET Core project. There is a one-to-many relationship on my Prescriptions and Prescribers tables and one-to-many relationship on my Prescribers and Marketers tables. I want to query the Prescriptions table and fetch the foreign key PrescriberId, then query Prescribers table and fetch the foreign key MarketerId and return the MarketerId. So far I have this linq

```<code>'var presciber = from p in _context.Prescriptions
                 join f in _context.Prescribers on p.PrescriberId equals f.Id
                 join m in _context.Marketers on f.MarketerId equals m.Id
                 where p.FolderStatusId == 3
                 select new { m.Id };
</code>```

I want to be able to use .Include so I can include other data from Marketers table, so instead of displaying MarketerId, I can display Marketer Name and not get null in the view. So I want to convert this query into a method, I have tried this

```<code>var prescriber = _context.Prescriptions
    .Join(_context.Prescribers,
    p => p.PrescriberId,
    f => f.Id,
    (p, f) => new { Prescriptions = p, Prescribers = f })
    .Join(_Context.Marketers,
    f => f.Prescribers.MarketerId,
    m => m.Id,
    (f, m) => new { Prescribers = f, Marketers = m })
    .Where(d => d.FolderStatusId == 3);//This line gets the error
</code>```

On the Where clause I get the error

```<code><anonmyous type: <anonymous type:Prescription Prescriptions, Prescriber Prescribers> Prescribers, Marketer Marketers> does not contain a definition for FolderStatusId
</code>```

Here are my classes

```<code>public class Prescriptions {
  public int Id {get;set;}
  public int FolderStatusId {get;set;}
  public int PrescriberId { get; set; }
  public string Medication { get; set; }
  public virtual Prescriber Prescriber { get; set; }
}
</code>```

Here is the Prescribers class

```<code>public class Prescriber {
    public int Id { get; set; }
    public int MarketerId { get; set; }
    public string Name { get; set; }
    public virtual Marketer Marketer {get;set;}
    public virtual ICollection<Prescription> Prescriptions { get; set; }
}
</code>```

Here is the Marketer class

```<code>public class Marketer {
    public int Id { get;set; }
    public string Name { get; set; }
    public virtual ICollection<Prescriber> Prescribers { get; set; }
}
</code>```

My question is how can I correct this Linq method and also where do I add the .Include?

答:
My advice would be to use identifiers that would mean anything to the reader. That would have helped you to see the cause of the problem:

```<code>var result = _context.Prescriptions
.Join(_context.Prescribers,
prescription => prescription.PrescriberId,
prescriber => prescriber.Id,
(prescription, prescriber) => new
{
    Prescription = prescription,
    Prescriber = prescriber,
})
// End of first join

.Join(_Context.Marketers,
firstJoinResult => firstJoinResult.Prescriber.MarketerId,
marketer => marketer.Id,

(firstJoinResult, marketer) => new
{
    Prescription = prescription,
    Prescriber = prescriber,
    Marketer = marketer,
})
// end of second join

.Where(secondJoinResult => secondJoinResult.FolderStatusId == 3);
//This line gets the error
</code>```

Your second join result, does not have a property FolderStatusId. In your original code, you used identifier d to refer to the second join result. Only Prescriptions have a FolderStatusId. So your Where should be like:

```<code>.Where(secondJoinResult => secondJoinResult.Prescription.FolderStatusId == 3);
</code>```

There's room for improvement

Use Where before the joins

If you use the Where before you start joining, a lot of Prescriptions don't have to be joined at all:

```<code>var result = _context.Prescriptions
    .Where(prescription => prescription.FolderStatusId == 3);
    .Join(_context.Prescribers,
        prescription => prescription.PrescriberId,
        prescriber => prescriber.Id,
        ... // etc
</code>```

Select only the properties that you plan to use

So a Marketer has zero or more Prescribers, and every Prescriber has zero or more Prescriptions, like you said: one-to-many relationships.

Every Prescription of Marketer [14] has a foreign key MarketerId with a value 14. If Marketer [14] has 1000 Prescriptions, then you would transfer 1000 times the combination of Marketer [14] with one of the Prescriptions with MarketerId [14].

Apart from the fact that you would transfer 1000 times the same Marketer data, you would also transfer the same value of Prescription.MarketerId, of which you already know the value: it has value [14]. What a waste of processing power!

Solution: select only the properties that you plan to use:

```<code>    var result = _context.Prescriptions
    .Where(prescription => prescription.FolderStatusId == 3);
    .Join(_context.Prescribers,
        prescription => prescription.PrescriberId,
        prescriber => prescriber.Id,
        ... // etc
        (firstJoinResult, marketer) => new
        {
            Marketer = new
            {
                // Select only the Marketer properties that you plan to use
                Id = marketer.Id,
                Name = markter.Name,
                ...
            }

            Subscriber = new
            {
                // Again: only the properties that you plan to use:
                Id = firstJoinResult.Subscriber.Id,
                Name = markter.Name,

                // No need for this, you  know the value:
                // MarketerId = firstJoinResult.Subscriber.MarketerId,
            },

            Prescription = new { ... },
       });
</code>```

In Entity framework always use Select to query data and select only the properties that you plan to use. Only use Include if you plan to change the included data.

The reason is, that entity framework can only update items that are fetched completely.

Consider a GroupJoin

I already mentioned in the previous chapter: the same values of Marketer [14] will be transferred many times.

Whenever you want Items with their subitems, like Schools with their Students, Customers with their Orders, and Marketers with their Prescribers, consider a GroupJoin instead of a Join.

```<code>var result = _context.Marketers
    .GroupJoin(_context.Prescribers,
        marketer => marketer.Id,
        prescriber => prescriber.MarketerId,

        // parameter ResultSelector:
        // get all Marketers with their prescribers to make one new
        (marketer, prescribersOfThisMarketer) => new
        {
            Id = marketer.Id,
            Name = marketer.Name,
            ...

            Prescribers = prescribersOfThisPrescription.GroupJoin(
                _context.Prescriptions.Where(prescription => prescription.FolderStatusId == 3),
                prescriber => prescriber.Id,
                prescription => prescription.PrescriberId,

                // from every prescriber with all its prescriptions, make one new
                (prescriber, prescriptionsOfThisPrescriber) => new
                {
                    Id = prescriber.Id,
                    Name = prescriber.Name,
                    ...

                    Prescriptions = prescriptionsOfThisPrescriber.Select(presription => new
                    {
                         Id = prescription.Id,
                         ...
                    })
                    .ToList(),
                })
                .ToList(),
        });
</code>```

So Instead of

```<code>Marketer  Subscriber
   A          10
   A          11
   B          20
   A          28
   C          12
   B          13
</code>```

You get:

Marketer A with his Subscribers 10, 11, 28

Marketer B with his Subscriber 20, 13

Marketer C with his Subscriber 12

Marketer D without any Subscribers

This usually looks more like you would want your result.

Note: GroupJoin will also return items that have no subitems!, like Marketers without any Subscribers. Usually you want this, but if you don't want them, use a Where to filter them out:

```<code>.Where(marketer => marketer.Subscribers.Any());
</code>```

The most revolutional: use the ICollection!

Some people told me that EF-core does not support this. I know that full entity framework certainly does: use the ICollections instead of a group-join.

Requirement Give me (some properties of) all Marketers, each with (some properties of all) his Prescribers, each with his Prescriptions.

```<code>var marketers = dbContext.Marketers.Select(marketer => new
{
    Id = marketer.Id,
    Name = marketer.Name,
    ...

    Prescribers = marketer.Prescribers.Select(prescriber => new
    {
        Id = prescriber.Id,
        Name = prescriber.Name,
        ...

        Prescriptions = prescriber.Prescriptions
            .Where(prescription => prescription.FolderStatusId == 3)
            .Select(prescription => new
            {
                 Id = prescription.Id,
                 ...
            })
            .ToList(),
    })
    .ToList(),
});
</code>```

This feels way more naturally than a (Group-)Join. Entity framework knows the relations between the tables and translate it into the correct (Group-)Join.

Body:
I have seen a few posts that are similar but I haven't been able to figure out how to solve my problem. I have three tables in an ASP.NET Core project. There is a one-to-many relationship on my Prescriptions and Prescribers tables and one-to-many relationship on my Prescribers and Marketers tables. I want to query the Prescriptions table and fetch the foreign key PrescriberId, then query Prescribers table and fetch the foreign key MarketerId and return the MarketerId. So far I have this linq

'var presciber = from p in _context.Prescriptions
                 join f in _context.Prescribers on p.PrescriberId equals f.Id
                 join m in _context.Marketers on f.MarketerId equals m.Id
                 where p.FolderStatusId == 3
                 select new { m.Id };

I want to be able to use .Include so I can include other data from Marketers table, so instead of displaying MarketerId, I can display Marketer Name and not get null in the view. So I want to convert this query into a method, I have tried this

var prescriber = _context.Prescriptions
    .Join(_context.Prescribers,
    p => p.PrescriberId,
    f => f.Id,
    (p, f) => new { Prescriptions = p, Prescribers = f })
    .Join(_Context.Marketers,
    f => f.Prescribers.MarketerId,
    m => m.Id,
    (f, m) => new { Prescribers = f, Marketers = m })
    .Where(d => d.FolderStatusId == 3);//This line gets the error

On the Where clause I get the error

<anonmyous type: <anonymous type:Prescription Prescriptions, Prescriber Prescribers> Prescribers, Marketer Marketers> does not contain a definition for FolderStatusId

Here are my classes

public class Prescriptions {
  public int Id {get;set;}
  public int FolderStatusId {get;set;}
  public int PrescriberId { get; set; }
  public string Medication { get; set; }
  public virtual Prescriber Prescriber { get; set; }
}

Here is the Prescribers class

public class Prescriber {
    public int Id { get; set; }
    public int MarketerId { get; set; }
    public string Name { get; set; }
    public virtual Marketer Marketer {get;set;}
    public virtual ICollection<Prescription> Prescriptions { get; set; }
}

Here is the Marketer class

public class Marketer {
    public int Id { get;set; }
    public string Name { get; set; }
    public virtual ICollection<Prescriber> Prescribers { get; set; }
}

My question is how can I correct this Linq method and also where do I add the .Include?

Body:
My advice would be to use identifiers that would mean anything to the reader. That would have helped you to see the cause of the problem:

var result = _context.Prescriptions
.Join(_context.Prescribers,
prescription => prescription.PrescriberId,
prescriber => prescriber.Id,
(prescription, prescriber) => new
{
    Prescription = prescription,
    Prescriber = prescriber,
})
// End of first join

.Join(_Context.Marketers,
firstJoinResult => firstJoinResult.Prescriber.MarketerId,
marketer => marketer.Id,

(firstJoinResult, marketer) => new
{
    Prescription = prescription,
    Prescriber = prescriber,
    Marketer = marketer,
})
// end of second join

.Where(secondJoinResult => secondJoinResult.FolderStatusId == 3);
//This line gets the error

Your second join result, does not have a property FolderStatusId. In your original code, you used identifier d to refer to the second join result. Only Prescriptions have a FolderStatusId. So your Where should be like:

.Where(secondJoinResult => secondJoinResult.Prescription.FolderStatusId == 3);

There's room for improvement

Use Where before the joins

If you use the Where before you start joining, a lot of Prescriptions don't have to be joined at all:

var result = _context.Prescriptions
    .Where(prescription => prescription.FolderStatusId == 3);
    .Join(_context.Prescribers,
        prescription => prescription.PrescriberId,
        prescriber => prescriber.Id,
        ... // etc

Select only the properties that you plan to use

So a Marketer has zero or more Prescribers, and every Prescriber has zero or more Prescriptions, like you said: one-to-many relationships.

Every Prescription of Marketer [14] has a foreign key MarketerId with a value 14. If Marketer [14] has 1000 Prescriptions, then you would transfer 1000 times the combination of Marketer [14] with one of the Prescriptions with MarketerId [14].

Apart from the fact that you would transfer 1000 times the same Marketer data, you would also transfer the same value of Prescription.MarketerId, of which you already know the value: it has value [14]. What a waste of processing power!

Solution: select only the properties that you plan to use:

    var result = _context.Prescriptions
    .Where(prescription => prescription.FolderStatusId == 3);
    .Join(_context.Prescribers,
        prescription => prescription.PrescriberId,
        prescriber => prescriber.Id,
        ... // etc
        (firstJoinResult, marketer) => new
        {
            Marketer = new
            {
                // Select only the Marketer properties that you plan to use
                Id = marketer.Id,
                Name = markter.Name,
                ...
            }

            Subscriber = new
            {
                // Again: only the properties that you plan to use:
                Id = firstJoinResult.Subscriber.Id,
                Name = markter.Name,

                // No need for this, you  know the value:
                // MarketerId = firstJoinResult.Subscriber.MarketerId,
            },

            Prescription = new { ... },
       });

In Entity framework always use Select to query data and select only the properties that you plan to use. Only use Include if you plan to change the included data.

The reason is, that entity framework can only update items that are fetched completely.

Consider a GroupJoin

I already mentioned in the previous chapter: the same values of Marketer [14] will be transferred many times.

Whenever you want Items with their subitems, like Schools with their Students, Customers with their Orders, and Marketers with their Prescribers, consider a GroupJoin instead of a Join.

var result = _context.Marketers
    .GroupJoin(_context.Prescribers,
        marketer => marketer.Id,
        prescriber => prescriber.MarketerId,

        // parameter ResultSelector:
        // get all Marketers with their prescribers to make one new
        (marketer, prescribersOfThisMarketer) => new
        {
            Id = marketer.Id,
            Name = marketer.Name,
            ...

            Prescribers = prescribersOfThisPrescription.GroupJoin(
                _context.Prescriptions.Where(prescription => prescription.FolderStatusId == 3),
                prescriber => prescriber.Id,
                prescription => prescription.PrescriberId,

                // from every prescriber with all its prescriptions, make one new
                (prescriber, prescriptionsOfThisPrescriber) => new
                {
                    Id = prescriber.Id,
                    Name = prescriber.Name,
                    ...

                    Prescriptions = prescriptionsOfThisPrescriber.Select(presription => new
                    {
                         Id = prescription.Id,
                         ...
                    })
                    .ToList(),
                })
                .ToList(),
        });

So Instead of

Marketer  Subscriber
   A          10
   A          11
   B          20
   A          28
   C          12
   B          13

You get:

Marketer A with his Subscribers 10, 11, 28

Marketer B with his Subscriber 20, 13

Marketer C with his Subscriber 12

Marketer D without any Subscribers

This usually looks more like you would want your result.

Note: GroupJoin will also return items that have no subitems!, like Marketers without any Subscribers. Usually you want this, but if you don't want them, use a Where to filter them out:

.Where(marketer => marketer.Subscribers.Any());

The most revolutional: use the ICollection!

Some people told me that EF-core does not support this. I know that full entity framework certainly does: use the ICollections instead of a group-join.

Requirement Give me (some properties of) all Marketers, each with (some properties of all) his Prescribers, each with his Prescriptions.

var marketers = dbContext.Marketers.Select(marketer => new
{
    Id = marketer.Id,
    Name = marketer.Name,
    ...

    Prescribers = marketer.Prescribers.Select(prescriber => new
    {
        Id = prescriber.Id,
        Name = prescriber.Name,
        ...

        Prescriptions = prescriber.Prescriptions
            .Where(prescription => prescription.FolderStatusId == 3)
            .Select(prescription => new
            {
                 Id = prescription.Id,
                 ...
            })
            .ToList(),
    })
    .ToList(),
});

This feels way more naturally than a (Group-)Join. Entity framework knows the relations between the tables and translate it into the correct (Group-)Join.


问:
PM2 Log Rotate Weekly Configuration
I'm so confused with the pm2-logrotate configuration, i need some help. I've search for documentation and googled with zero result. I just want to rotate the log every week.

I've tried using pm2 set pm2-logrotate:rotateInverval 0 0 * * 0 but the log file generated daily.

I just don't understand that cron stuff and i need some explaination, can somebody explain it to me?

thank you in advance.

答:
Without being wrapped in quotation marks, it's likely that only the first 0 is being read in your interval. So instead of interpreting the interval as 0 0 * * 0, it is interpreted just as 0.

The following should do the trick:

```<code>pm2 set pm2-logrotate:rotateInverval "0 0 * * 0"
</code>```

As for understanding the cron syntax, try pasting the values in here for an explanation: https://crontab.guru/#0_0___0

Title: PM2 Log Rotate Weekly Configuration

Body:
Without being wrapped in quotation marks, it's likely that only the first 0 is being read in your interval. So instead of interpreting the interval as 0 0 * * 0, it is interpreted just as 0.

The following should do the trick:

pm2 set pm2-logrotate:rotateInverval "0 0 * * 0"

As for understanding the cron syntax, try pasting the values in here for an explanation: https://crontab.guru/#0_0___0


问:
JQUERY: How to change the input value by clicking a button with a generic JQuery
I'm not an expert in JQuery but I'm trying to get a value from a button - when the user click a button and the input field will change the value.

But, I can have many buttons.. (In same cases, more than 100) for this reason I want to know if it's possible to get the value from the clicked button with a "generic" JQuery - to avoid a big JQuery with a $('#answer').val() for each button..

https://jsfiddle.net/Ldy01wb2/1/

HTML:

```<code><input type="button" id ='one' value="A">
<input type="button" id ='two' value="B">
<br><br>
Hidden: <input type="text" id="answer" value="">
</code>```

JQUERY: (what I want)

```<code>$(':button').click(function(){
    $('#answer').val = $(':button').val ;
});
</code>```

JQUERY: (works.. but if I have 100, I need 100 functions.. and I'm trying to get a generic solution for all buttons)

```<code>$('#one').click(function(){
    $('#answer').val("A") ;
});

$('#two').click(function(){
    $('#answer').val("B") ;
});
</code>```

答:
```<code>$("button, input[type='button']").click(function(){
    $('#answer').val(this.val()) ;
});
</code>```

Please check here for more information https://api.jquery.com/button-selector/

Body:
I'm not an expert in JQuery but I'm trying to get a value from a button - when the user click a button and the input field will change the value.

But, I can have many buttons.. (In same cases, more than 100) for this reason I want to know if it's possible to get the value from the clicked button with a "generic" JQuery - to avoid a big JQuery with a $('#answer').val() for each button..

https://jsfiddle.net/Ldy01wb2/1/

HTML:

<input type="button" id ='one' value="A">
<input type="button" id ='two' value="B">

Hidden: <input type="text" id="answer" value="">

JQUERY: (what I want)

$(':button').click(function(){
    $('#answer').val = $(':button').val ;
});

JQUERY: (works.. but if I have 100, I need 100 functions.. and I'm trying to get a generic solution for all buttons)

$('#one').click(function(){
    $('#answer').val("A") ;
});

$('#two').click(function(){
    $('#answer').val("B") ;
});

Body:
$("button, input[type='button']").click(function(){
    $('#answer').val(this.val()) ;
});

Please check here for more information https://api.jquery.com/button-selector/


问:
How can I switch between tabs in a TabLayout programatically from within a fragment
How can I switch between tabs in a TabLayout programatically from within a fragment which is currently displayed in the selected tab?
I have a button in my fragment which I want to switch to the other tab\fragment, and I can not use - tabs.getTabAt(2).select(); because it does not work from inside the fragment.

答:
I actually solved it now and it was quite easy.
To switch tabs from within the fragment an access to the tabLayout is required and using tabs = getActivity().findViewById(R.id.tabLayout); worked just fine for that and then just call tabs.getTabAt(1).select(); like snachmsm suggested in the previous answer.