问:
Can I change this c code using C pointer struct function?
```<code>#define ID_LEN 7
#define NAME_LEN 10

typedef struct {
    char id[ID_LEN];
    char name[NAME_LEN];
    int math;
    int eng;
} STUDENT;

void FirstList(STUDENT *list,int i) {
    printf("Enter data for student No.%d\n",++i);
    printf("ID : ");
    scanf("%s",list->id);
    printf("Name : ");
    scanf("%s",list->name);
    printf("Math score: ");
    scanf("%d",&list->math);
    printf("English score: ");
    scanf("%d",&list->eng);
}

int main() {
    STUDENT ** list=NULL;
    printf("How many student? ");
    int num=0;
    scanf("%d",&num);
    list=(STUDENT**)malloc(num*sizeof(STUDENT*));
    for(int i=0; i<num; i++) {
        list[i]= malloc(sizeof(STUDENT));
        FirstList(list[i],i);
    }
}
</code>```

**It is part of my C code **

I wanna change of my code without changing the other part.
I wanna change Like this

```<code>typedef struct {
    char id[ID_LEN];
    char name[NAME_LEN];
    int math;
    int eng;
} STUDENT;

void FirstList(STUDENT *list[] ,int num) {
    for(int j=0; j++, j<num) {
        list[j]=malloc(sizeof(STUDENT));
        printf("Enter data for student No.%d\n",++i);
        printf("ID : ");
        scanf("%s",list[j]->id);
        printf("Name : ");
        scanf("%s",list[j]->name);
        printf("Math score: ");
        scanf("%d",&list[j]->math);
        printf("English score: ");
        scanf("%d",&list[j]->eng);
    }
}

int main() {
    STUDENT ** list=NULL;
    printf("How many student? ");
    int num=0;
    scanf("%d",&num);
    list=(STUDENT**)malloc(num*sizeof(STUDENT*));
    FirstList(list[i],num);
}
</code>```

I wanna change like this. But I'm not sure it is possible, and I tried to find about this. But I couldn't....Please fix my code....
Please help me.... Thank you for reading my question.

答:
```<code>#define ID_LEN 7
#define NAME_LEN 10

typedef struct
{
    char id[ID_LEN];
    char name[NAME_LEN];
    int math;
    int eng;
} STUDENT;

void FirstList(STUDENT *list[], int num)
{
    int j;
    for (j = 0; j < num; j++)
    {
        list[j] = malloc(sizeof(STUDENT));
        printf("Enter data for student No.%d\n", j);
        printf("ID : ");
        scanf("%s", list[j]->id);
        printf("Name : ");
        scanf("%s", list[j]->name);
        printf("Math score: ");
        scanf("%d", &list[j]->math);
        printf("English score: ");
        scanf("%d", &list[j]->eng);
    }
}

void PrintList(STUDENT * list[], int Num)
{
    int j;
    printf("ID   Name     Math Eng  \r\n");
    for (j = 0; j < Num; j++)
    {
        printf("%4d %8s %4d %4d\r\n", list[j]->id, list[j]->name,
               list[j]->math, list[j]->eng);
    }
}

int main()
{
    STUDENT ** list = NULL;
    printf("How many student? ");
    int num = 0;
    scanf("%d", &num);
    list = (STUDENT**)malloc(num * sizeof(STUDENT));
    FirstList(list, num);
    PrintList(list, num);
    return 0;
}
</code>```

Good Luck!

Body:
#define ID_LEN 7
#define NAME_LEN 10

typedef struct {
    char id[ID_LEN];
    char name[NAME_LEN];
    int math;
    int eng;
} STUDENT;

void FirstList(STUDENT *list,int i) {
    printf("Enter data for student No.%d\n",++i);
    printf("ID : ");
    scanf("%s",list->id);
    printf("Name : ");
    scanf("%s",list->name);
    printf("Math score: ");
    scanf("%d",&list->math);
    printf("English score: ");
    scanf("%d",&list->eng);
}

int main() {
    STUDENT ** list=NULL;
    printf("How many student? ");
    int num=0;
    scanf("%d",&num);
    list=(STUDENT**)malloc(num*sizeof(STUDENT*));
    for(int i=0; i<num; i++) {
        list[i]= malloc(sizeof(STUDENT));
        FirstList(list[i],i);
    }
}

**It is part of my C code **

I wanna change of my code without changing the other part.
I wanna change Like this

typedef struct {
    char id[ID_LEN];
    char name[NAME_LEN];
    int math;
    int eng;
} STUDENT;

void FirstList(STUDENT *list[] ,int num) {
    for(int j=0; j++, j<num) {
        list[j]=malloc(sizeof(STUDENT));
        printf("Enter data for student No.%d\n",++i);
        printf("ID : ");
        scanf("%s",list[j]->id);
        printf("Name : ");
        scanf("%s",list[j]->name);
        printf("Math score: ");
        scanf("%d",&list[j]->math);
        printf("English score: ");
        scanf("%d",&list[j]->eng);
    }
}

int main() {
    STUDENT ** list=NULL;
    printf("How many student? ");
    int num=0;
    scanf("%d",&num);
    list=(STUDENT**)malloc(num*sizeof(STUDENT*));
    FirstList(list[i],num);
}

I wanna change like this. But I'm not sure it is possible, and I tried to find about this. But I couldn't....Please fix my code....
Please help me.... Thank you for reading my question.

Body:
#define ID_LEN 7
#define NAME_LEN 10

typedef struct
{
    char id[ID_LEN];
    char name[NAME_LEN];
    int math;
    int eng;
} STUDENT;

void FirstList(STUDENT *list[], int num)
{
    int j;
    for (j = 0; j < num; j++)
    {
        list[j] = malloc(sizeof(STUDENT));
        printf("Enter data for student No.%d\n", j);
        printf("ID : ");
        scanf("%s", list[j]->id);
        printf("Name : ");
        scanf("%s", list[j]->name);
        printf("Math score: ");
        scanf("%d", &list[j]->math);
        printf("English score: ");
        scanf("%d", &list[j]->eng);
    }
}

void PrintList(STUDENT * list[], int Num)
{
    int j;
    printf("ID   Name     Math Eng  \r\n");
    for (j = 0; j < Num; j++)
    {
        printf("%4d %8s %4d %4d\r\n", list[j]->id, list[j]->name,
               list[j]->math, list[j]->eng);
    }
}

int main()
{
    STUDENT ** list = NULL;
    printf("How many student? ");
    int num = 0;
    scanf("%d", &num);
    list = (STUDENT**)malloc(num * sizeof(STUDENT));
    FirstList(list, num);
    PrintList(list, num);
    return 0;
}

Good Luck!


来源: stackexchange

问:
Simple example of threading in C++
Can someone post a simple example of starting two (Object Oriented) threads in C++.

I'm looking for actual C++ thread objects that I can extend run methods on (or something similar) as opposed to calling a C-style thread library.

I left out any OS specific requests in the hopes that whoever replied would reply with cross platform libraries to use. I'm just making that explicit now.

答:
```<code>#include <thread>
#include <iostream>
#include <vector>
using namespace std;

void doSomething(int id) {
    cout << id << "\n";
}

/**
 * Spawns n threads
 */
void spawnThreads(int n)
{
    std::vector<thread> threads(n);
    // spawn n threads:
    for (int i = 0; i < n; i++) {
        threads[i] = thread(doSomething, i + 1);
    }

    for (auto& th : threads) {
        th.join();
    }
}

int main()
{
    spawnThreads(10);
}
</code>```

OwnerDisplayName: Zak

ContentLicense: CC BY-SA 4.0

Title: Simple example of threading in C++

LastEditorDisplayName: Zak


问:
Webscraping using Selenium - Element not found
I'm trying to scrape this website:

https://www.novanthealth.org/home/patients--visitors/locations/clinics.aspx?behavioral-health=yes

I want to get the clinic names and addresses, and this is the python code I'm using

```<code>from selenium import webdriver
import pd
import time

#driver = webdriver.Chrome()
specialty   = ["behavioral-health","dermatology","colon","ear-nose-and-    throat","endocrine","express","family-practice","foot-and-ankle",
           "gastroenterology","heart-%26-vascular","hepatobiliary-and-pancreas","infectious-disease","inpatient","internal-medicine",
           "neurology","nutrition","ob%2Fgyn","occupational-medicine","oncology","orthopedics","osteoporosis","pain-management",
           "pediatrics","plastic-surgery","pulmonary","rehabilitation","rheumatology","sleep","spine","sports-medicine","surgical","urgent-care",
           "urology","weight-loss","wound-care","pharmacy"]
name = []
address = []

for q in specialty:
    driver = webdriver.Chrome()
    driver.get("https://www.novanthealth.org/home/patients--   visitors/locations/clinics.aspx?"+q+"=yes")
    x = driver.find_element_by_class_name("loc-link-right")
    num_page = str(x.text).split(" ")
    x.click()

    for i in num_page:
        btn = driver.find_element_by_xpath('//*[@id="searchResults"]/div[2]/div[2]/button['+i+']')
        btn.click()
        time.sleep(8) #instaed of this use waituntil #
        temp = driver.find_element_by_class_name("gray-background").text
        temp0 = temp.replace("Get directions Website View providers\n","")

        x_temp = temp0.split("\n\n\n")

        for j in range(0,len(x_temp)-1):
            temp1 = x_temp[j].split("Phone:")
            name.append(temp1[0].split("\n")[1])
            temp3 = temp1[1].split("Office hours:")
            temp4 = temp3[0].split("\n")
            temp5 = temp4[1:len(temp4)]
            address.append(" ".join(temp5))
   driver.close()
</code>```

This code works fine If I use it for only one specialty at a time, but when I pass the specialties in a loop as above, the code fails in the second iteration with the error:

```<code>Traceback (most recent call last):
 File "<stdin>", line 10, in <module>
File "C:\Anaconda2\lib\site- packages\selenium\webdriver\remote\webelement.py", line 77, in click self._execute(Command.CLICK_ELEMENT)
File C:\Anaconda2\lib\sitepackages\selenium\webdriver\remote\webelement.py", line 493, in _execute return self._parent.execute(command, params)
File "C:\Anaconda2\lib\site-packages\selenium\webdriver\remote\webdriver.py",     line 249, in execute self.error_handler.check_response(response)
 File "C:\Anaconda2\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 193, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.ElementNotVisibleException: Message: element not visible
(Session info: chrome=46.0.2490.80)
(Driver info: chromedriver=2.19.346078    (6f1f0cde889532d48ce8242342d0b84f94b114a1),platform=Windows NT 6.1 SP1 x86_64
</code>```

I don't have much experience using python, any help will be appreciated

答:
Usually I would do in Selenium Basic, an excel plugin. You can use the same logic in Python. This is tried in VBA and works fine for me.</p>

```<code>Private assert As New assert
Private driver As New Selenium.ChromeDriver

Sub sel_novanHealth()
Set ObjWB = ThisWorkbook
Set ObjExl_Sheet1 = ObjWB.Worksheets("Sheet1")
Dim Name As Variant

   'Open the website
    driver.get "https://www.novanthealth.org/home/patients--visitors/locations.aspx"

    driver.Window.Maximize

    driver.Wait (1000)

    'Find out the total number of pages to be scraped
    lnth = driver.FindElementsByXPath("//button[@class='paginate_button']").Count
   'Running the Loop for the Pages
    For y = 2 To lnth
            'Running the Loop for the Elements
            For x = 1 To 10
                Name = driver.FindElementsByXPath("//div[@class='span12 loc-heading']")(x).Text
                ' Element 2
                 'Element 3
            Next x
                driver.FindElementsByXPath("//button[@class='paginate_button']")(y).Click
    Next y

        driver.Wait (1000)

End Sub
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to scrape this website:

https://www.novanthealth.org/home/patients--visitors/locations/clinics.aspx?behavioral-health=yes

I want to get the clinic names and addresses, and this is the python code I'm using

from selenium import webdriver
import pd
import time

#driver = webdriver.Chrome()
specialty   = ["behavioral-health","dermatology","colon","ear-nose-and-    throat","endocrine","express","family-practice","foot-and-ankle",
           "gastroenterology","heart-%26-vascular","hepatobiliary-and-pancreas","infectious-disease","inpatient","internal-medicine",
           "neurology","nutrition","ob%2Fgyn","occupational-medicine","oncology","orthopedics","osteoporosis","pain-management",
           "pediatrics","plastic-surgery","pulmonary","rehabilitation","rheumatology","sleep","spine","sports-medicine","surgical","urgent-care",
           "urology","weight-loss","wound-care","pharmacy"]
name = []
address = []

for q in specialty:
    driver = webdriver.Chrome()
    driver.get("https://www.novanthealth.org/home/patients--   visitors/locations/clinics.aspx?"+q+"=yes")
    x = driver.find_element_by_class_name("loc-link-right")
    num_page = str(x.text).split(" ")
    x.click()

    for i in num_page:
        btn = driver.find_element_by_xpath('//*[@id="searchResults"]/div[2]/div[2]/button['+i+']')
        btn.click()
        time.sleep(8) #instaed of this use waituntil #
        temp = driver.find_element_by_class_name("gray-background").text
        temp0 = temp.replace("Get directions Website View providers\n","")

        x_temp = temp0.split("\n\n\n")

        for j in range(0,len(x_temp)-1):
            temp1 = x_temp[j].split("Phone:")
            name.append(temp1[0].split("\n")[1])
            temp3 = temp1[1].split("Office hours:")
            temp4 = temp3[0].split("\n")
            temp5 = temp4[1:len(temp4)]
            address.append(" ".join(temp5))
   driver.close()

This code works fine If I use it for only one specialty at a time, but when I pass the specialties in a loop as above, the code fails in the second iteration with the error:

Traceback (most recent call last):
 File "<stdin>", line 10, in <module>
File "C:\Anaconda2\lib\site- packages\selenium\webdriver\remote\webelement.py", line 77, in click self._execute(Command.CLICK_ELEMENT)
File C:\Anaconda2\lib\sitepackages\selenium\webdriver\remote\webelement.py", line 493, in _execute return self._parent.execute(command, params)
File "C:\Anaconda2\lib\site-packages\selenium\webdriver\remote\webdriver.py",     line 249, in execute self.error_handler.check_response(response)
 File "C:\Anaconda2\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 193, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.ElementNotVisibleException: Message: element not visible
(Session info: chrome=46.0.2490.80)
(Driver info: chromedriver=2.19.346078    (6f1f0cde889532d48ce8242342d0b84f94b114a1),platform=Windows NT 6.1 SP1 x86_64

I don't have much experience using python, any help will be appreciated

Body:
Usually I would do in Selenium Basic, an excel plugin. You can use the same logic in Python. This is tried in VBA and works fine for me.

Private assert As New assert
Private driver As New Selenium.ChromeDriver

Sub sel_novanHealth()
Set ObjWB = ThisWorkbook
Set ObjExl_Sheet1 = ObjWB.Worksheets("Sheet1")
Dim Name As Variant

   'Open the website
    driver.get "https://www.novanthealth.org/home/patients--visitors/locations.aspx"

    driver.Window.Maximize

    driver.Wait (1000)

    'Find out the total number of pages to be scraped
    lnth = driver.FindElementsByXPath("//button[@class='paginate_button']").Count
   'Running the Loop for the Pages
    For y = 2 To lnth
            'Running the Loop for the Elements
            For x = 1 To 10
                Name = driver.FindElementsByXPath("//div[@class='span12 loc-heading']")(x).Text
                ' Element 2
                 'Element 3
            Next x
                driver.FindElementsByXPath("//button[@class='paginate_button']")(y).Click
    Next y

        driver.Wait (1000)

End Sub


问:
error on line 2 at column 1: Extra content at the end of the document in PHP public function
I Have function:

```<code>    protected function getFeedCategory($lng) {
    $params = $this->dispatcher->getParam('format', null, '/id/1');
    $pArr = explode("/", $params);
    $limit = 10;
    //varDump($pArr);
    //varDump($this->dispatcher->getParams());
    try {

        $categoryId = (isset($pArr[2])) ? (int)$pArr[2] : 1;
        $cache_key = 'Frontend_Feed_getFeedCategory_' . $categoryId . '_limit_' . $limit . '_' . $lng;
        //$this->_cache->delete($cache_key);
        if (($items = $this->_cache->get($cache_key)) == null || $this->cache_renew_data->can_refrash) {
            $items = $this->db->fetchAll("SELECT n.date_show, n.title_{$lng} AS title,n.id,n.is_ru,n.is_md,n.is_new,n.thumb_md,n.thumb_ru,
                                          n.thumb_en
                                          FROM news AS n
                                          LEFT JOIN news_categories AS nc ON nc.news_id=n.id
                                          WHERE n.is_{$lng} = 1 AND n.date_show < '" . date(MYSQL_DATE_FORMAT) . "'
                                          AND nc.categories_id = {$categoryId}
                                          ORDER BY n.date_show DESC LIMIT 0," . $limit);
            //varDump($items);
            if (count($items)) {
                $this->_cache->save($cache_key, $items);
            }
        }

    } catch (\Exception $e) {
        return $this->getAll($lng, 20);
    }

    return $items;
}
</code>```

And this return error on line 2 at column 1: Extra content at the end of the document, how I Can Fix it?

case 'feed-category' :
                    $items = $this->getFeedCategory($lng);
                    break;

This code get content with url!

答:
```<code>public function getFeedCategory($lng) {
    $params = $this->dispatcher->getParam('format', null, '/id/1');
    $pArr = explode("/", $params);
    $limit = 10;

    try {
        $categoryId = (isset($pArr[2])) ? (int)$pArr[2] : 1;
        $cache_key = 'Frontend_Feed_getFeedCategory_' . $categoryId . '_limit_' . $limit . '_' . $lng;

        if (($items = $this->_cache->get($cache_key)) == null || $this->cache_renew_data->can_refrash) {
            $items = $this->db->fetchAll("SELECT n.date_show, n.title_{$lng} AS title,n.id,n.is_ru,n.is_md,n.is_new,n.thumb_md,n.thumb_ru,
                                          n.thumb_en
                                          FROM news AS n
                                          LEFT JOIN news_categories AS nc ON nc.news_id=n.id
                                          WHERE n.is_{$lng} = 1 AND n.date_show < '" . date(MYSQL_DATE_FORMAT) . "'
                                          AND nc.categories_id = {$categoryId}
                                          ORDER BY n.date_show DESC LIMIT 0," . $limit);

            if (count($items)) {
                $this->_cache->save($cache_key, $items);
                return $items;
            }
        }
    } catch (\Exception $e) {
        return $this->getAll($lng, 20);
    }
}
</code>```

Body:
I Have function:

    protected function getFeedCategory($lng) {
    $params = $this->dispatcher->getParam('format', null, '/id/1');
    $pArr = explode("/", $params);
    $limit = 10;
    //varDump($pArr);
    //varDump($this->dispatcher->getParams());
    try {

        $categoryId = (isset($pArr[2])) ? (int)$pArr[2] : 1;
        $cache_key = 'Frontend_Feed_getFeedCategory_' . $categoryId . '_limit_' . $limit . '_' . $lng;
        //$this->_cache->delete($cache_key);
        if (($items = $this->_cache->get($cache_key)) == null || $this->cache_renew_data->can_refrash) {
            $items = $this->db->fetchAll("SELECT n.date_show, n.title_{$lng} AS title,n.id,n.is_ru,n.is_md,n.is_new,n.thumb_md,n.thumb_ru,
                                          n.thumb_en
                                          FROM news AS n
                                          LEFT JOIN news_categories AS nc ON nc.news_id=n.id
                                          WHERE n.is_{$lng} = 1 AND n.date_show < '" . date(MYSQL_DATE_FORMAT) . "'
                                          AND nc.categories_id = {$categoryId}
                                          ORDER BY n.date_show DESC LIMIT 0," . $limit);
            //varDump($items);
            if (count($items)) {
                $this->_cache->save($cache_key, $items);
            }
        }

    } catch (\Exception $e) {
        return $this->getAll($lng, 20);
    }

    return $items;
}

And this return error on line 2 at column 1: Extra content at the end of the document, how I Can Fix it?

case 'feed-category' :
                    $items = $this->getFeedCategory($lng);
                    break;

This code get content with url!


问:
There is a file which is having 10 columns delimeted with space.I want to insert comma for first six columns only
I have a file like below. But for first file columns i want to put comma while printing and rest of the columns should print with space. Is there anyway i can achieve through sed or awk command?

```<code>$ cat testing
1 2 3 4 5 6 7 8 9 10
</code>```

答:
```<code>perl -pe 'eval "s/ /,/;"x5' < testing
</code>```

Body:
I have a file like below. But for first file columns i want to put comma while printing and rest of the columns should print with space. Is there anyway i can achieve through sed or awk command?

$ cat testing
1 2 3 4 5 6 7 8 9 10

Body: perl -pe 'eval "s/ /,/;"x5' < testing


问:
Protected data members and data functions
when i declare a protected data member in a class that means its not accesible to the outer world but the derived class. My question is

will it be accesible to a class that is derived from the derived class?

答:
Yes, protected data members are accessible all the way down the inheritance hierarchy.

Protected data is usually better avoided. An alternative is to write protected methods that access the private data. This keeps the data encapsulated within a single class. It also makes it easy to set a breakpoint for changes to the data.

ContentLicense: CC BY-SA 2.5


问:
Handle falsy arguments
Is there any clean way to assign default values to a function, if any of its arguments are falsy.

I know that you can do something like

```<code>function addSomething(element, someArr = []) {
  someArr.push(element);
}
</code>```

But this doesnt handle if the second argument is null and you would then get a "cannot read property 'push' of null".

I hoped the below would have worked

```<code>function addSomething(element, someArr || []) {
  someArr.push(element);
}
</code>```

....

So im i left doing the check inside the method?

```<code>function addSomething(element, someArr) {
  someArr = someArr || [];
  someArr.push(element);
  // OR
  someArr && someArr.push(element);
}
</code>```

Or is there a pattern that I have missed

答:
Your code is the best you can hope.
null is different from an array, so if you explicitly pass it into your function it should:

Fail loudly because there is a bug in the program. You wanted an array and got a null.

Handle it gracefully because you want to allow null as well.

I think you want the second case. With TypeScript annotations this function might look like:

```<code>function addSomething(element, someArr: any[]|null)
</code>```

And you'd be forced to explicitly acknowledge this fact.

Title: Handle falsy arguments

Body:
Is there any clean way to assign default values to a function, if any of its arguments are falsy.

I know that you can do something like

function addSomething(element, someArr = []) {
  someArr.push(element);
}

But this doesnt handle if the second argument is null and you would then get a "cannot read property 'push' of null".

I hoped the below would have worked

function addSomething(element, someArr || []) {
  someArr.push(element);
}

....

So im i left doing the check inside the method?

function addSomething(element, someArr) {
  someArr = someArr || [];
  someArr.push(element);
  // OR
  someArr && someArr.push(element);
}

Or is there a pattern that I have missed

Body:
Your code is the best you can hope.
null is different from an array, so if you explicitly pass it into your function it should:

Fail loudly because there is a bug in the program. You wanted an array and got a null.

Handle it gracefully because you want to allow null as well.

I think you want the second case. With TypeScript annotations this function might look like:

function addSomething(element, someArr: any[]|null)

And you'd be forced to explicitly acknowledge this fact.


问:
Running Gatling without interactive options
When I run Gatling (the performance test tool), it always gives me an interactive dialog to run one Scala simulation file at a time. Is there a way to tell Gatling to run all the files in a particular order? I'm sure there must be one, but just don't seem to find a way to specify it. </p>

答:
Running

```<code>user@host $ ./bin/gatling.sh -h
</code>```

returns

```<code>GATLING_HOME is set to /path/to/gatling
Usage: compiler [options]

  -h, --help
  -sf, --simulations-folder <value>

  -bf, --binaries-folder <value>

  -ccp, --compilerClasspath <value>

Usage: gatling [options]

  -h, --help               Show help (this message) and exit
  -nr, --no-reports        Runs simulation but does not generate reports
  -m, --mute               Runs in mute mode: doesn't ask for run description or simulation ID, uses defaults
  -ro, --reports-only <directoryName>
                           Generates the reports for the simulation in <directoryName>
  -df, --data-folder <directoryPath>
                           Uses <directoryPath> as the absolute path of the directory where feeders are stored
  -rf, --results-folder <directoryPath>
                           Uses <directoryPath> as the absolute path of the directory where results are stored
  -bdf, --bodies-folder <directoryPath>
                           Uses <directoryPath> as the absolute path of the directory where bodies are stored
  -sf, --simulations-folder <directoryPath>
                           Uses <directoryPath> to discover simulations that could be run
  -bf, --binaries-folder <directoryPath>
                           Uses <directoryPath> as the absolute path of the directory where Gatling should produce compiled binaries
  -s, --simulation <className>
                           Runs <className> simulation
  -on, --output-name <name>
                           Use <name> for the base name of the output directory
  -rd, --run-description <description>
                           A short <description> of the run to include in the report
</code>```

and running

```<code>./bin/gatling.sh -s RecordedSimulation
</code>```

runs the test in nointeractive mode

Body:
Running

user@host $ ./bin/gatling.sh -h

returns

GATLING_HOME is set to /path/to/gatling
Usage: compiler [options]

  -h, --help
  -sf, --simulations-folder <value>

  -bf, --binaries-folder <value>

  -ccp, --compilerClasspath <value>

Usage: gatling [options]

  -h, --help               Show help (this message) and exit
  -nr, --no-reports        Runs simulation but does not generate reports
  -m, --mute               Runs in mute mode: doesn't ask for run description or simulation ID, uses defaults
  -ro, --reports-only <directoryName>
                           Generates the reports for the simulation in <directoryName>
  -df, --data-folder <directoryPath>
                           Uses <directoryPath> as the absolute path of the directory where feeders are stored
  -rf, --results-folder <directoryPath>
                           Uses <directoryPath> as the absolute path of the directory where results are stored
  -bdf, --bodies-folder <directoryPath>
                           Uses <directoryPath> as the absolute path of the directory where bodies are stored
  -sf, --simulations-folder <directoryPath>
                           Uses <directoryPath> to discover simulations that could be run
  -bf, --binaries-folder <directoryPath>
                           Uses <directoryPath> as the absolute path of the directory where Gatling should produce compiled binaries
  -s, --simulation <className>
                           Runs <className> simulation
  -on, --output-name <name>
                           Use <name> for the base name of the output directory
  -rd, --run-description <description>
                           A short <description> of the run to include in the report

and running

./bin/gatling.sh -s RecordedSimulation

runs the test in nointeractive mode


问:
Can sum() be used like a hash
I want to check whether the sum of two list is same or not.

```<code>lst1 = [1, 2, 3, 4]
lst2 = [0, 3, 3, 4]
if sum(lst1) == sum(lst2):
    return true
</code>```

Here the sum returns true. If I hash the list I get different values but hashing is computationally expensive. I only want to check whether the elements in the two lists are same (only with the exception of 1 element). I am using Binary search technique of dividing the list and then checking the hash. if hashes are different I am checking if its more than once.
But as I said hashing is computationally expensive. Also the order does matter here. Thank you

答:
First, is is not the logically correct syntax for your application; use == instead. Refer this post to know more about the difference: Is there a difference between `==` and `is` in Python?

```<code>def checksum(lst1, lst2):
    return sum(lst1) == sum(lst2):

list1 = [1, 2, 3, 4]
list2 = [0, 3, 3, 4]
checksum(list1,list2)
</code>```

This is the correct code to compare a checksum (and is obviously true in this example).

If you are looking for something different, like finding whether the items of the list are the same element-wise, then the straight-forward answer would be

```<code>return lst1 == lst2
</code>```

Title: Can sum() be used like a hash

Body:
I want to check whether the sum of two list is same or not.

lst1 = [1, 2, 3, 4]
lst2 = [0, 3, 3, 4]
if sum(lst1) == sum(lst2):
    return true

Here the sum returns true. If I hash the list I get different values but hashing is computationally expensive. I only want to check whether the elements in the two lists are same (only with the exception of 1 element). I am using Binary search technique of dividing the list and then checking the hash. if hashes are different I am checking if its more than once.
But as I said hashing is computationally expensive. Also the order does matter here. Thank you

Body:
First, is is not the logically correct syntax for your application; use == instead. Refer this post to know more about the difference: Is there a difference between `==` and `is` in Python?

def checksum(lst1, lst2):
    return sum(lst1) == sum(lst2):

list1 = [1, 2, 3, 4]
list2 = [0, 3, 3, 4]
checksum(list1,list2)

This is the correct code to compare a checksum (and is obviously true in this example).

If you are looking for something different, like finding whether the items of the list are the same element-wise, then the straight-forward answer would be

return lst1 == lst2


问:
How could I check if string is only match into an other string
I'm actually a beginner into web developpment.

I have a problem with my actual condition.

Exemple :

```<code>$rooms = 10;
</code>```

In my code, I check if $rooms is equal to 1,0 or 10 so :

```<code>if(strpos($rooms, '1')){echo 1;}
if(strpos($rooms, '0')){echo 0};
if(strpos($rooms, '10')){echo 10;}
</code>```

My result :

```<code>1
0
10
</code>```

My condition match for 1, 0 and 10, where I only need to match the number 10

How can I only pass into my third condition ?

Thx

答:
You can use in_array() (strict/non-strict mode as third parameter) like,</p>

```<code>$arr = array(1,0,10);
var_dump(in_array(0,$arr));
var_dump(in_array(22,$arr));
var_dump(in_array(10,$arr));
var_dump(in_array(1,$arr));
</code>```

Body:
I'm actually a beginner into web developpment.

I have a problem with my actual condition.

Exemple :

$rooms = 10;

In my code, I check if $rooms is equal to 1,0 or 10 so :

if(strpos($rooms, '1')){echo 1;}
if(strpos($rooms, '0')){echo 0};
if(strpos($rooms, '10')){echo 10;}

My result :

1
0
10

My condition match for 1, 0 and 10, where I only need to match the number 10

How can I only pass into my third condition ?

Thx

Body:
You can use in_array() (strict/non-strict mode as third parameter) like,

$arr = array(1,0,10);
var_dump(in_array(0,$arr));
var_dump(in_array(22,$arr));
var_dump(in_array(10,$arr));
var_dump(in_array(1,$arr));


答: Yes. (You could have simply tried that out, by the way.)</p>

Title: Protected data members and data functions

Body:
when i declare a protected data member in a class that means its not accesible to the outer world but the derived class. My question is

will it be accesible to a class that is derived from the derived class?


问:
Angular 2+ Animation- Changing color on body element
I am a beginner programmer, and I recently started to learn Angular 4. I am trying to make a personal site and want to add some animations.

On the top of the page, I have a jumbotron with a logo. I want it so that so that when I click on this logo, the background color of the body changes, but it seems that the function trigger the  element.

Here is my code on TypeScript: (Code doesn't produce an error. It just doesn't do what I intended to do.)

```<code>@Component({
    selector: 'main-jumbotron',
    templateUrl: './jumbotron.component.html',
    styleUrls: ['./jumbotron.component.css'],
    animations: [
      trigger("changeBodyColor", [
        state('off', style({
            backgroundColor: '#CCFFCC'
        })),
        state('on', style({
            backgroundColor: '#3A3A38'
        })),
        transition('off => on', [animate('2s')]),
        transition('on => off', [animate('2s')])
      ])
    ]
})
export class JumbotronComponent implements OnInit {
     // other private instance data, constructor here, ngOnInit etc.

    colorState: string = 'off';
        toggleColor() {
            console.log('triggered ' + this.colorState);
            this.colorState = (this.colorState === 'off') ? 'on' : 'off';
    }
}
</code>```

When I put [@changeBodyColor]="colorState" in the div element of the jumbotron, animation works, but just changing the jumbotron background color, obviously. When I put this on the body element from index.html, the function is triggered (logged on console), but the color does not change.

I feel like this is a problem with the DOM hierarchy. If anyone has some idea of what the issue might be, please let me know!

答:
If you want to change the whole body, then write the animations: in the component which defines your body.
it wont change your jumbotron or footer so what you can do is make div with properties covering the whole screen, and then apply your trigger there [@changeBodyColor].</p>

Body:
I am a beginner programmer, and I recently started to learn Angular 4. I am trying to make a personal site and want to add some animations.

On the top of the page, I have a jumbotron with a logo. I want it so that so that when I click on this logo, the background color of the body changes, but it seems that the function trigger the  element.

Here is my code on TypeScript: (Code doesn't produce an error. It just doesn't do what I intended to do.)

@Component({
    selector: 'main-jumbotron',
    templateUrl: './jumbotron.component.html',
    styleUrls: ['./jumbotron.component.css'],
    animations: [
      trigger("changeBodyColor", [
        state('off', style({
            backgroundColor: '#CCFFCC'
        })),
        state('on', style({
            backgroundColor: '#3A3A38'
        })),
        transition('off => on', [animate('2s')]),
        transition('on => off', [animate('2s')])
      ])
    ]
})
export class JumbotronComponent implements OnInit {
     // other private instance data, constructor here, ngOnInit etc.

    colorState: string = 'off';
        toggleColor() {
            console.log('triggered ' + this.colorState);
            this.colorState = (this.colorState === 'off') ? 'on' : 'off';
    }
}

When I put [@changeBodyColor]="colorState" in the div element of the jumbotron, animation works, but just changing the jumbotron background color, obviously. When I put this on the body element from index.html, the function is triggered (logged on console), but the color does not change.

I feel like this is a problem with the DOM hierarchy. If anyone has some idea of what the issue might be, please let me know!


问:
How to activate/install SSL Certificate on Custom PHP Page
I am new to SSL, but i have search the internet to enable the SSL in Joomla-based website which is successful.

But there is subdomains in which i created custom PHP pages and want install the SSL Certificate on the pages i have created.

Please is there any guide to go about it.

Thank you

答:
You don't install an SSL Certificate on a specific page.

You install it on the web server, which is probably either apache2 or nginx.
Try installing it there or contact your webhost/admin.


问:
Is it possible to only deploy the changed files to an AWS Elastic Beanstalk application instead of uploading my whole source code?
I have set up an Elastic Beanstalk Application in AWS.

Until now I have deployed newer versions of my source code (ZIP-file) via the web interface of AWS.

Now my website is online and users are able to upload profile pictures. The problem is when I deploy a new version of my website all my source code will be replaced by the new one and all the user images are gone...

So is there any option to commit only the changed files instead of uploading the whole page?

答: No, you'll have to use a storage solution, such as AWS S3 to store the image files. This way the files will not disappear whenever your application is (re)deployed, and they will be available from all EC2 instances, so your application can scale up and down freely.</p>


问:
Given Project GUID, how can I find the name/path of the project?
I have a list of Project GUIDs from a sln file.

I need to find the project corresponding to each GUID programatically.

How can I do this?

答:
I may be very late to answer this question, but in the hopes of helping any other person who wonders over this question. There are several assemblies that you would like to use for parsing solution and project files in C#, they are:

```<code>Microsoft.Build.Evaluation
</code>```

and

```<code>Microsoft.Build.Construction
</code>```

With in the later assembly there is a class called SolutionFile. Documentation. Within the documentation SolutionFile contains the property ProjectsByGuid, on which you can do a linq query on if you already have the GUID. The code to do this would look a little like this:

```<code>var guid = "{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}"
var pathToSolutionFile = "C:\users\user\source\repos\solution\solution.sln"
var sln = SolutionFile.Parse(pathToSolutionFile);
var projectName = sln.ProjectsByGuid.Where(x => x.key==guid)
                     .FirstOrDefault().Value?.projectname;
</code>```

I hope this helps you, or anyone else.

Body:
I may be very late to answer this question, but in the hopes of helping any other person who wonders over this question. There are several assemblies that you would like to use for parsing solution and project files in C#, they are:

Microsoft.Build.Evaluation

and

Microsoft.Build.Construction

With in the later assembly there is a class called SolutionFile. Documentation. Within the documentation SolutionFile contains the property ProjectsByGuid, on which you can do a linq query on if you already have the GUID. The code to do this would look a little like this:

var guid = "{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}"
var pathToSolutionFile = "C:\users\user\source\repos\solution\solution.sln"
var sln = SolutionFile.Parse(pathToSolutionFile);
var projectName = sln.ProjectsByGuid.Where(x => x.key==guid)
                     .FirstOrDefault().Value?.projectname;

I hope this helps you, or anyone else.


答:
Even your last approach isn't 100% safe:

function addSomething(element, someArr) {
  someArr && someArr.push(element);
}
addSomething('test', 'foobar');```
</div>
</div>
</p>

<p>You have to check if the parameter is an array: </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function addSomething(element, someArr) {
  Array.isArray(someArr) && someArr.push(element);
}
addSomething('test', 'foobar'); // fails silently</code>```

Title: Handle falsy arguments

Body:
Even your last approach isn't 100% safe:

function addSomething(element, someArr) {
  someArr && someArr.push(element);
}
addSomething('test', 'foobar');

You have to check if the parameter is an array:

function addSomething(element, someArr) {
  Array.isArray(someArr) && someArr.push(element);
}
addSomething('test', 'foobar'); // fails silently


问:
Redux: importing selectors into actions?
There seems to be agreement that if an action creator needs state information (and we want to be independent of state shape), the component calling the action should submit the required state slices to the action. See e.g. Dan Abramov's comment here

But why are we not instead importing selectors into actions?

```<code>import { mySelector } from '../reducers';

const myAction = () => (dispatch, getState) => {
  const requiredState = mySelector(getState());
  etc...
};
</code>```

It looks like this would save at least some state slices a roundtrip through components and de-couple things.

What's the disadvantage of doing this? (Except perhaps that actions cannot export ActionTypes.)

答:
AFAIK the idea in the comment you mentioned is to "decouple" your action from state.

Decoupling the actions from the application state taking in the data you need from where the actions are called make the actions not bounded to state.

Usually decoupling is always a good thing, some advantages:

Easier to maintain code and change implementations

Easier unit test.

Less dependencies for your actions.

Body:
There seems to be agreement that if an action creator needs state information (and we want to be independent of state shape), the component calling the action should submit the required state slices to the action. See e.g. Dan Abramov's comment here

But why are we not instead importing selectors into actions?

import { mySelector } from '../reducers';

const myAction = () => (dispatch, getState) => {
  const requiredState = mySelector(getState());
  etc...
};

It looks like this would save at least some state slices a roundtrip through components and de-couple things.

What's the disadvantage of doing this? (Except perhaps that actions cannot export ActionTypes.)


问:
LINQ Ring: Any() vs Contains() for Huge Collections
Given a huge collection of objects, is there a performance difference between the the following?

Collection.Contains:

```<code>myCollection.Contains(myElement)
</code>```

Enumerable.Any:

```<code>myCollection.Any(currentElement => currentElement == myElement)
</code>```

答:
It depends on the collection. If you have an ordered collection, then Contains might do a smart search (binary, hash, b-tree, etc.), while with `Any() you are basically stuck with enumerating until you find it (assuming LINQ-to-Objects).

Also note that in your example, Any() is using the == operator which will check for referential equality, while Contains will use IEquatable<T> or the Equals() method, which might be overridden.

Body:
Given a huge collection of objects, is there a performance difference between the the following?

Collection.Contains:

myCollection.Contains(myElement)

Enumerable.Any:

myCollection.Any(currentElement => currentElement == myElement)


问:
jquery .css script doesn't work
Morning,
I'm trying to display a div onmouseover. I created a function but i don't know what is wrong. Could you help me please.

The HTML code:

```<code><!DOCTYPE html>
<html lang="it">
<head>
    <meta charset="utf-8">
    <title> PHOTOGALLERY</title>
    <link rel="stylesheet" href="style.css" type="text/css"/>
    <link rel="stylesheet" href="css/smoothness/jquery-ui-
         1.9.2.custom.css"/>
    <script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
    <script src="http://malsup.github.com/jquery.cycle2.js"></script>
    <script type="text/javascript" src="js/jquery-ui-1.9.2.custom.js">
    </script>
    <script>
        function show_img_container() {
            $("#image_container").css("display", "block");
        }
    </script>
</head>
<body>
    <div id="div_container">
        <div id="div_image" class="cycle-slideshow">
            <img src="images/2.jpg" style="height:100%; width:100%">
            <img src="images/3.jpg" style="height:100%; width:100%">
            <img src="images/4.jpg" style="height:100%; width:100%">
            <img src="images/5.jpg" style="height:100%; width:100%">
        </div>
        <div id="image_container" onmouseover="show_img_container()"></div>
    </div>
</body>
</html>
</code>```

In the css file i have a image_container id where the attribute display is set to 'none';

答:
I'll answer based on what OP has provided. wrap the #image_container with a div that contains the function, then it should work.

And since it's quite weird that something appeared when hovered but didn't disappear after hovering out, I added another function for onmouseout

function show_img_container() {
  $("#image_container").css("display", "block");
}
function hide_img_container() {
  $("#image_container").css("display", "none");
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#image_container {
  display: none;
}</code>```

  HOVER ME!!

IM HIDDEN!!!

```

Title: jquery .css script doesn't work

Body:
Morning,
I'm trying to display a div onmouseover. I created a function but i don't know what is wrong. Could you help me please.

The HTML code:

<!DOCTYPE html>

    <meta charset="utf-8">
    <title> PHOTOGALLERY</title>
    <link rel="stylesheet" href="style.css" type="text/css"/>
    <link rel="stylesheet" href="css/smoothness/jquery-ui-
         1.9.2.custom.css"/>

In the css file i have a image_container id where the attribute display is set to 'none';

Body:
I'll answer based on what OP has provided. wrap the #image_container with a div that contains the function, then it should work.

And since it's quite weird that something appeared when hovered but didn't disappear after hovering out, I added another function for onmouseout

function show_img_container() {
  $("#image_container").css("display", "block");
}
function hide_img_container() {
  $("#image_container").css("display", "none");
}

#image_container {
  display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div onmouseover="show_img_container()" onmouseout="hide_img_container()">
  HOVER ME!!
  <div id="image_container">IM HIDDEN!!!</div>
</div>


问:
Using gulp-imgmin is it bad to compress or minify an image more than one time?
I am trying to decide if I should just compress/minify all my images and have them just overwrite each other, or if I should store the minified/compressed versions of each image in a separate folder?

Would it be bad to keep compressing an image that has already been compressed?

答: I would make the gulp.dest = 'src/lib/images/min/' (added min/) therefore keeping the original.  I also do not see a problem with repeatedly running it because there may be an update to the library that improves compression.</p>


问:
How to use Interval in countDownTimer in Android
In my application i should use CountDownTimer and for this I want use this library : CountdownView.

I want when lasted 5s show me Toast.

For example : I want show 17s countTimer, when this timer receive to 5s show me toast "just 5s".

I use this code, but show me ever 5s .

```<code>long time1 = 17 * 1000;
mCvCountdownViewTest1.start(time1);
mCvCountdownViewTest1.setOnCountdownIntervalListener(5000, new CountdownView.OnCountdownIntervalListener() {
    @Override
    public void onInterval(CountdownView cv, long remainTime) {
        Toast.makeText(MainActivity.this, "Just 5s ", Toast.LENGTH_SHORT).show();
    }
});
</code>```

I want just lasted 5s not ever 5s.

how can i it?

答:
I think you should check how many seconds remains.
I rewrote your code:</p>

```<code>long time1 = 17L * 1000;
mCvCountdownViewTest1.start(time1);
mCvCountdownViewTest1.setOnCountdownIntervalListener(1000, new CountdownView.OnCountdownIntervalListener() {
    @Override
    public void onInterval(CountdownView cv, long remainTime) {
        long remainTimeInSeconds = remainTime / 1000;
        if (remainTimeInSeconds  == 5) {
            Toast.makeText(MainActivity.this, "Just 5s ", Toast.LENGTH_SHORT).show();
        }
    }
});
</code>```

Body:
In my application i should use CountDownTimer and for this I want use this library : CountdownView.

I want when lasted 5s show me Toast.

For example : I want show 17s countTimer, when this timer receive to 5s show me toast "just 5s".

I use this code, but show me ever 5s .

long time1 = 17 * 1000;
mCvCountdownViewTest1.start(time1);
mCvCountdownViewTest1.setOnCountdownIntervalListener(5000, new CountdownView.OnCountdownIntervalListener() {
    @Override
    public void onInterval(CountdownView cv, long remainTime) {
        Toast.makeText(MainActivity.this, "Just 5s ", Toast.LENGTH_SHORT).show();
    }
});

I want just lasted 5s not ever 5s.

how can i it?

Body:
I think you should check how many seconds remains.
I rewrote your code:

long time1 = 17L * 1000;
mCvCountdownViewTest1.start(time1);
mCvCountdownViewTest1.setOnCountdownIntervalListener(1000, new CountdownView.OnCountdownIntervalListener() {
    @Override
    public void onInterval(CountdownView cv, long remainTime) {
        long remainTimeInSeconds = remainTime / 1000;
        if (remainTimeInSeconds  == 5) {
            Toast.makeText(MainActivity.this, "Just 5s ", Toast.LENGTH_SHORT).show();
        }
    }
});


问:
Cutting a live stream into separate mp4 files
I am doing a research for cutting a live stream in piece and save it as mp4 files. I am using this source for the proof of concept:

https://learn.microsoft.com/en-us/azure/media-services/media-services-dotnet-creating-live-encoder-enabled-channel#download-sample

And this is the example code I use:

```<code>using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.MediaServices.Client;
using Newtonsoft.Json.Linq;

namespace AMSLiveTest
{
    class Program
    {
        private const string StreamingEndpointName = "streamingendpoint001";
        private const string ChannelName = "channel001";
        private const string AssetlName = "asset001";
        private const string ProgramlName = "program001";

        // Read values from the App.config file.
        private static readonly string _mediaServicesAccountName =
        ConfigurationManager.AppSettings["MediaServicesAccountName"];
        private static readonly string _mediaServicesAccountKey =
        ConfigurationManager.AppSettings["MediaServicesAccountKey"];

        // Field for service context.
        private static CloudMediaContext _context = null;
        private static MediaServicesCredentials _cachedCredentials = null;

        static void Main(string[] args)
        {
            // Create and cache the Media Services credentials in a static class variable.
            _cachedCredentials = new MediaServicesCredentials(
            _mediaServicesAccountName,
            _mediaServicesAccountKey);
            // Used the cached credentials to create CloudMediaContext.
            _context = new CloudMediaContext(_cachedCredentials);

            IChannel channel = CreateAndStartChannel();

            // Set the Live Encoder to point to the channel's input endpoint:
            string ingestUrl = channel.Input.Endpoints.FirstOrDefault().Url.ToString();

            // Use the previewEndpoint to preview and verify
            // that the input from the encoder is actually reaching the Channel.
            string previewEndpoint = channel.Preview.Endpoints.FirstOrDefault().Url.ToString();

            IProgram program = CreateAndStartProgram(channel);
            ILocator locator = CreateLocatorForAsset(program.Asset, program.ArchiveWindowLength);
            IStreamingEndpoint streamingEndpoint = CreateAndStartStreamingEndpoint();
            GetLocatorsInAllStreamingEndpoints(program.Asset);

            // Once you are done streaming, clean up your resources.
            Cleanup(streamingEndpoint, channel);
        }

        public static IChannel CreateAndStartChannel()
        {
            //If you want to change the Smooth fragments to HLS segment ratio, you would set the ChannelCreationOptions’s Output property.

            IChannel channel = _context.Channels.Create(
            new ChannelCreationOptions
            {
            Name = ChannelName,
            Input = CreateChannelInput(),
            Preview = CreateChannelPreview()
            });

            //Starting and stopping Channels can take some time to execute. To determine the state of operations after calling Start or Stop, query the IChannel.State .

            channel.Start();

            return channel;
        }

        private static ChannelInput CreateChannelInput()
        {
            return new ChannelInput
            {
                StreamingProtocol = StreamingProtocol.RTMP,
                AccessControl = new ChannelAccessControl
                {
                    IPAllowList = new List<IPRange>
                            {
                            new IPRange
                        {
                            Name = "TestChannelInput001",
                            // Setting 0.0.0.0 for Address and 0 for SubnetPrefixLength
                            // will allow access to IP addresses.
                            Address = IPAddress.Parse("0.0.0.0"),
                            SubnetPrefixLength = 0
                        }
                    }
                }
            };
        }

        private static ChannelPreview CreateChannelPreview()
        {
            return new ChannelPreview
            {
                AccessControl = new ChannelAccessControl
                {
                    IPAllowList = new List<IPRange>
                    {
                        new IPRange
                        {
                            Name = "TestChannelPreview001",
                            // Setting 0.0.0.0 for Address and 0 for SubnetPrefixLength
                            // will allow access to IP addresses.
                            Address = IPAddress.Parse("0.0.0.0"),
                            SubnetPrefixLength = 0
                        }
                    }
                }
            };
        }

        public static void UpdateCrossSiteAccessPoliciesForChannel(IChannel channel)
        {
            var clientPolicy =
                @"<?xml version=""1.0"" encoding=""utf-8""?>
            <access-policy>
                <cross-domain-access>
                    <policy>
                        <allow-from http-request-headers=""*"" http-methods=""*"">
                            <domain uri=""*""/>
                        </allow-from>
                        <grant-to>
                           <resource path=""/"" include-subpaths=""true""/>
                        </grant-to>
                    </policy>
                </cross-domain-access>
            </access-policy>";

            var xdomainPolicy =
                @"<?xml version=""1.0"" ?>
            <cross-domain-policy>
                <allow-access-from domain=""*"" />
            </cross-domain-policy>";

            channel.CrossSiteAccessPolicies.ClientAccessPolicy = clientPolicy;
            channel.CrossSiteAccessPolicies.CrossDomainPolicy = xdomainPolicy;

            channel.Update();
        }

        public static IProgram CreateAndStartProgram(IChannel channel)
        {
            IAsset asset = _context.Assets.Create(AssetlName, AssetCreationOptions.None);

            // Create a Program on the Channel. You can have multiple Programs that overlap or are sequential;
            // however each Program must have a unique name within your Media Services account.
            IProgram program = channel.Programs.Create(ProgramlName, TimeSpan.FromHours(3), asset.Id);
            program.Start();

            return program;
        }

        public static ILocator CreateLocatorForAsset(IAsset asset, TimeSpan ArchiveWindowLength)
        {
            // You cannot create a streaming locator using an AccessPolicy that includes write or delete permissions.

            var locator = _context.Locators.CreateLocator
                (
                    LocatorType.OnDemandOrigin,
                    asset,
                    _context.AccessPolicies.Create
                    (
                        "Live Stream Policy",
                        ArchiveWindowLength,
                        AccessPermissions.Read
                    )
                );

            return locator;
        }

        public static IStreamingEndpoint CreateAndStartStreamingEndpoint()
        {
            var options = new StreamingEndpointCreationOptions
            {
                Name = StreamingEndpointName,
                ScaleUnits = 1,
                AccessControl = GetAccessControl(),
                CacheControl = GetCacheControl()
            };

            IStreamingEndpoint streamingEndpoint = _context.StreamingEndpoints.Create(options);
            streamingEndpoint.Start();

            return streamingEndpoint;
        }

        private static StreamingEndpointAccessControl GetAccessControl()
        {
            return new StreamingEndpointAccessControl
            {
                IPAllowList = new List<IPRange>
                {
                    new IPRange
                    {
                        Name = "Allow all",
                        Address = IPAddress.Parse("0.0.0.0"),
                        SubnetPrefixLength = 0
                    }
                },

                AkamaiSignatureHeaderAuthenticationKeyList = new List<AkamaiSignatureHeaderAuthenticationKey>
                {
                    new AkamaiSignatureHeaderAuthenticationKey
                    {
                        Identifier = "My key",
                        Expiration = DateTime.UtcNow + TimeSpan.FromDays(365),
                        Base64Key = Convert.ToBase64String(GenerateRandomBytes(16))
                    }
                }
            };
        }

        private static byte[] GenerateRandomBytes(int length)
        {
            var bytes = new byte[length];
            using (var rng = new RNGCryptoServiceProvider())
            {
                rng.GetBytes(bytes);
            }

            return bytes;
        }

        private static StreamingEndpointCacheControl GetCacheControl()
        {
            return new StreamingEndpointCacheControl
            {
                MaxAge = TimeSpan.FromSeconds(1000)
            };
        }

        public static void UpdateCrossSiteAccessPoliciesForStreamingEndpoint(IStreamingEndpoint streamingEndpoint)
        {
            var clientPolicy =
                @"<?xml version=""1.0"" encoding=""utf-8""?>
            <access-policy>
                <cross-domain-access>
                    <policy>
                        <allow-from http-request-headers=""*"" http-methods=""*"">
                            <domain uri=""*""/>
                        </allow-from>
                        <grant-to>
                           <resource path=""/"" include-subpaths=""true""/>
                        </grant-to>
                    </policy>
                </cross-domain-access>
            </access-policy>";

            var xdomainPolicy =
                @"<?xml version=""1.0"" ?>
            <cross-domain-policy>
                <allow-access-from domain=""*"" />
            </cross-domain-policy>";

            streamingEndpoint.CrossSiteAccessPolicies.ClientAccessPolicy = clientPolicy;
            streamingEndpoint.CrossSiteAccessPolicies.CrossDomainPolicy = xdomainPolicy;

            streamingEndpoint.Update();
        }

        public static void GetLocatorsInAllStreamingEndpoints(IAsset asset)
        {
            var locators = asset.Locators.Where(l => l.Type == LocatorType.OnDemandOrigin);
            var ismFile = asset.AssetFiles.AsEnumerable().FirstOrDefault(a => a.Name.EndsWith(".ism"));
            var template = new UriTemplate("{contentAccessComponent}/{ismFileName}/manifest");
            var urls = locators.SelectMany(l =>
                        _context
                            .StreamingEndpoints
                            .AsEnumerable()
                            .Where(se => se.State == StreamingEndpointState.Running)
                            .Select(
                                se =>
                                    template.BindByPosition(new Uri("http://" + se.HostName),
                                    l.ContentAccessComponent,
                                        ismFile.Name)))
                        .ToArray();

        }

        public static void Cleanup(IStreamingEndpoint streamingEndpoint,
                                    IChannel channel)
        {
            if (streamingEndpoint != null)
            {
                streamingEndpoint.Stop();
                streamingEndpoint.Delete();
            }

            IAsset asset;
            if (channel != null)
            {

                foreach (var program in channel.Programs)
                {
                    asset = _context.Assets.Where(se => se.Id == program.AssetId)
                                            .FirstOrDefault();

                    program.Stop();
                    program.Delete();

                    if (asset != null)
                    {
                        foreach (var l in asset.Locators)
                            l.Delete();

                        asset.Delete();
                    }
                }

                channel.Stop();
                channel.Delete();
            }
        }
    }
}
</code>```

Now I want to make a method to cut a live stream for example every 15 minutes and save it as mp4 but don't know where to start.

Can someone point me in the right direction?

Kind regards

UPDATE:

I want to save the mp4 files on my hard disk.

答:
You can use ffmpeg to save the stream on your hard drive. Please see the code:

```<code>ffmpeg -i InputStreamURL -acodec aac -strict -2 -vcodec libx264 -hls_wrap 100 -f hls -hls_time 20 /var/www/html/ts/1.m3u8
</code>```

The -hls_time 20 use for the time of your saved data. In fact you use ffmpeg for a HLS stream but its doing the things you want. You could access the saved data on your Hard drive in /var/www/html/ts/ (and you could change this as you want).

Or could use VLC :

```<code>cvlc -vvv rtp://@239.1.2.1:60001
--sout '#std{access=livehttp{seglen=5,delsegs=true,numsegs=5,
index=/path/to/stream.m3u8,
index-url=http://example.org/stream-########.ts},
mux=ts{use-key-frames},
dst=/path/to/stream-########.ts}'
</code>```

In above command either you could change the duration of the saved data in hard drive. But I personally do not use VLC and prefer use ffmpeg

Finally you could call one of above command in your C# application and see the result. Good Luck.

Body:
I am doing a research for cutting a live stream in piece and save it as mp4 files. I am using this source for the proof of concept:

https://learn.microsoft.com/en-us/azure/media-services/media-services-dotnet-creating-live-encoder-enabled-channel#download-sample

And this is the example code I use:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.MediaServices.Client;
using Newtonsoft.Json.Linq;

namespace AMSLiveTest
{
    class Program
    {
        private const string StreamingEndpointName = "streamingendpoint001";
        private const string ChannelName = "channel001";
        private const string AssetlName = "asset001";
        private const string ProgramlName = "program001";

        // Read values from the App.config file.
        private static readonly string _mediaServicesAccountName =
        ConfigurationManager.AppSettings["MediaServicesAccountName"];
        private static readonly string _mediaServicesAccountKey =
        ConfigurationManager.AppSettings["MediaServicesAccountKey"];

        // Field for service context.
        private static CloudMediaContext _context = null;
        private static MediaServicesCredentials _cachedCredentials = null;

        static void Main(string[] args)
        {
            // Create and cache the Media Services credentials in a static class variable.
            _cachedCredentials = new MediaServicesCredentials(
            _mediaServicesAccountName,
            _mediaServicesAccountKey);
            // Used the cached credentials to create CloudMediaContext.
            _context = new CloudMediaContext(_cachedCredentials);

            IChannel channel = CreateAndStartChannel();

            // Set the Live Encoder to point to the channel's input endpoint:
            string ingestUrl = channel.Input.Endpoints.FirstOrDefault().Url.ToString();

            // Use the previewEndpoint to preview and verify
            // that the input from the encoder is actually reaching the Channel.
            string previewEndpoint = channel.Preview.Endpoints.FirstOrDefault().Url.ToString();

            IProgram program = CreateAndStartProgram(channel);
            ILocator locator = CreateLocatorForAsset(program.Asset, program.ArchiveWindowLength);
            IStreamingEndpoint streamingEndpoint = CreateAndStartStreamingEndpoint();
            GetLocatorsInAllStreamingEndpoints(program.Asset);

            // Once you are done streaming, clean up your resources.
            Cleanup(streamingEndpoint, channel);
        }

        public static IChannel CreateAndStartChannel()
        {
            //If you want to change the Smooth fragments to HLS segment ratio, you would set the ChannelCreationOptions’s Output property.

            IChannel channel = _context.Channels.Create(
            new ChannelCreationOptions
            {
            Name = ChannelName,
            Input = CreateChannelInput(),
            Preview = CreateChannelPreview()
            });

            //Starting and stopping Channels can take some time to execute. To determine the state of operations after calling Start or Stop, query the IChannel.State .

            channel.Start();

            return channel;
        }

        private static ChannelInput CreateChannelInput()
        {
            return new ChannelInput
            {
                StreamingProtocol = StreamingProtocol.RTMP,
                AccessControl = new ChannelAccessControl
                {
                    IPAllowList = new List<IPRange>
                            {
                            new IPRange
                        {
                            Name = "TestChannelInput001",
                            // Setting 0.0.0.0 for Address and 0 for SubnetPrefixLength
                            // will allow access to IP addresses.
                            Address = IPAddress.Parse("0.0.0.0"),
                            SubnetPrefixLength = 0
                        }
                    }
                }
            };
        }

        private static ChannelPreview CreateChannelPreview()
        {
            return new ChannelPreview
            {
                AccessControl = new ChannelAccessControl
                {
                    IPAllowList = new List<IPRange>
                    {
                        new IPRange
                        {
                            Name = "TestChannelPreview001",
                            // Setting 0.0.0.0 for Address and 0 for SubnetPrefixLength
                            // will allow access to IP addresses.
                            Address = IPAddress.Parse("0.0.0.0"),
                            SubnetPrefixLength = 0
                        }
                    }
                }
            };
        }

        public static void UpdateCrossSiteAccessPoliciesForChannel(IChannel channel)
        {
            var clientPolicy =
                @"<?xml version=""1.0"" encoding=""utf-8""?>
            <access-policy>
                <cross-domain-access>
                    <policy>
                        <allow-from http-request-headers=""*"" http-methods=""*"">
                            <domain uri=""*""/>
                        </allow-from>
                        <grant-to>
                           <resource path=""/"" include-subpaths=""true""/>
                        </grant-to>
                    </policy>
                </cross-domain-access>
            </access-policy>";

            var xdomainPolicy =
                @"<?xml version=""1.0"" ?>
            <cross-domain-policy>
                <allow-access-from domain=""*"" />
            </cross-domain-policy>";

            channel.CrossSiteAccessPolicies.ClientAccessPolicy = clientPolicy;
            channel.CrossSiteAccessPolicies.CrossDomainPolicy = xdomainPolicy;

            channel.Update();
        }

        public static IProgram CreateAndStartProgram(IChannel channel)
        {
            IAsset asset = _context.Assets.Create(AssetlName, AssetCreationOptions.None);

            // Create a Program on the Channel. You can have multiple Programs that overlap or are sequential;
            // however each Program must have a unique name within your Media Services account.
            IProgram program = channel.Programs.Create(ProgramlName, TimeSpan.FromHours(3), asset.Id);
            program.Start();

            return program;
        }

        public static ILocator CreateLocatorForAsset(IAsset asset, TimeSpan ArchiveWindowLength)
        {
            // You cannot create a streaming locator using an AccessPolicy that includes write or delete permissions.

            var locator = _context.Locators.CreateLocator
                (
                    LocatorType.OnDemandOrigin,
                    asset,
                    _context.AccessPolicies.Create
                    (
                        "Live Stream Policy",
                        ArchiveWindowLength,
                        AccessPermissions.Read
                    )
                );

            return locator;
        }

        public static IStreamingEndpoint CreateAndStartStreamingEndpoint()
        {
            var options = new StreamingEndpointCreationOptions
            {
                Name = StreamingEndpointName,
                ScaleUnits = 1,
                AccessControl = GetAccessControl(),
                CacheControl = GetCacheControl()
            };

            IStreamingEndpoint streamingEndpoint = _context.StreamingEndpoints.Create(options);
            streamingEndpoint.Start();

            return streamingEndpoint;
        }

        private static StreamingEndpointAccessControl GetAccessControl()
        {
            return new StreamingEndpointAccessControl
            {
                IPAllowList = new List<IPRange>
                {
                    new IPRange
                    {
                        Name = "Allow all",
                        Address = IPAddress.Parse("0.0.0.0"),
                        SubnetPrefixLength = 0
                    }
                },

                AkamaiSignatureHeaderAuthenticationKeyList = new List<AkamaiSignatureHeaderAuthenticationKey>
                {
                    new AkamaiSignatureHeaderAuthenticationKey
                    {
                        Identifier = "My key",
                        Expiration = DateTime.UtcNow + TimeSpan.FromDays(365),
                        Base64Key = Convert.ToBase64String(GenerateRandomBytes(16))
                    }
                }
            };
        }

        private static byte[] GenerateRandomBytes(int length)
        {
            var bytes = new byte[length];
            using (var rng = new RNGCryptoServiceProvider())
            {
                rng.GetBytes(bytes);
            }

            return bytes;
        }

        private static StreamingEndpointCacheControl GetCacheControl()
        {
            return new StreamingEndpointCacheControl
            {
                MaxAge = TimeSpan.FromSeconds(1000)
            };
        }

        public static void UpdateCrossSiteAccessPoliciesForStreamingEndpoint(IStreamingEndpoint streamingEndpoint)
        {
            var clientPolicy =
                @"<?xml version=""1.0"" encoding=""utf-8""?>
            <access-policy>
                <cross-domain-access>
                    <policy>
                        <allow-from http-request-headers=""*"" http-methods=""*"">
                            <domain uri=""*""/>
                        </allow-from>
                        <grant-to>
                           <resource path=""/"" include-subpaths=""true""/>
                        </grant-to>
                    </policy>
                </cross-domain-access>
            </access-policy>";

            var xdomainPolicy =
                @"<?xml version=""1.0"" ?>
            <cross-domain-policy>
                <allow-access-from domain=""*"" />
            </cross-domain-policy>";

            streamingEndpoint.CrossSiteAccessPolicies.ClientAccessPolicy = clientPolicy;
            streamingEndpoint.CrossSiteAccessPolicies.CrossDomainPolicy = xdomainPolicy;

            streamingEndpoint.Update();
        }

        public static void GetLocatorsInAllStreamingEndpoints(IAsset asset)
        {
            var locators = asset.Locators.Where(l => l.Type == LocatorType.OnDemandOrigin);
            var ismFile = asset.AssetFiles.AsEnumerable().FirstOrDefault(a => a.Name.EndsWith(".ism"));
            var template = new UriTemplate("{contentAccessComponent}/{ismFileName}/manifest");
            var urls = locators.SelectMany(l =>
                        _context
                            .StreamingEndpoints
                            .AsEnumerable()
                            .Where(se => se.State == StreamingEndpointState.Running)
                            .Select(
                                se =>
                                    template.BindByPosition(new Uri("http://" + se.HostName),
                                    l.ContentAccessComponent,
                                        ismFile.Name)))
                        .ToArray();

        }

        public static void Cleanup(IStreamingEndpoint streamingEndpoint,
                                    IChannel channel)
        {
            if (streamingEndpoint != null)
            {
                streamingEndpoint.Stop();
                streamingEndpoint.Delete();
            }

            IAsset asset;
            if (channel != null)
            {

                foreach (var program in channel.Programs)
                {
                    asset = _context.Assets.Where(se => se.Id == program.AssetId)
                                            .FirstOrDefault();

                    program.Stop();
                    program.Delete();

                    if (asset != null)
                    {
                        foreach (var l in asset.Locators)
                            l.Delete();

                        asset.Delete();
                    }
                }

                channel.Stop();
                channel.Delete();
            }
        }
    }
}

Now I want to make a method to cut a live stream for example every 15 minutes and save it as mp4 but don't know where to start.

Can someone point me in the right direction?

Kind regards

UPDATE:

I want to save the mp4 files on my hard disk.

Body:
You can use ffmpeg to save the stream on your hard drive. Please see the code:

ffmpeg -i InputStreamURL -acodec aac -strict -2 -vcodec libx264 -hls_wrap 100 -f hls -hls_time 20 /var/www/html/ts/1.m3u8

The -hls_time 20 use for the time of your saved data. In fact you use ffmpeg for a HLS stream but its doing the things you want. You could access the saved data on your Hard drive in /var/www/html/ts/ (and you could change this as you want).

Or could use VLC :

cvlc -vvv rtp://@239.1.2.1:60001
--sout '#std{access=livehttp{seglen=5,delsegs=true,numsegs=5,
index=/path/to/stream.m3u8,
index-url=http://example.org/stream-########.ts},
mux=ts{use-key-frames},
dst=/path/to/stream-########.ts}'

In above command either you could change the duration of the saved data in hard drive. But I personally do not use VLC and prefer use ffmpeg

Finally you could call one of above command in your C# application and see the result. Good Luck.


问:
Dart analyzer is not parsing the dynamic generated files
I checked and the file is OK.

Dart 1.23.0
AngularDart 3.1.0

The error I am getting is:

Target of URI hasn't been generated: 'file.g.dart'

答:
It may help to run "Synchronize" -- bound by default to Ctrl-Q.

You can restart the analyzer on the dart analysis tab, in the top left is a button with arrows running in a circle, if you hover over it it says 'Restart Dart Analysis Server'.

Example picture


问:
Function which return dictionary of arguments in python
Function func(*args, **kwargs) should return dictionary, and all elements of that dictionary should be numeric or string variables.
If argument of function is dictionary, then function should return dictionary with all elements of argument dictionary, and other arguments.
For example:

```<code>arg1 = { 'x': 'X', 'y': 'Y' }
arg2 = 2
arg3 = { 'p': arg1, 'pi': 3.14 }
func(arg2, arg3, arg4=4)
</code>```

should return this:

```<code>{ 'x': 'X', 'y': 'Y', 'arg2': 2, 'pi': 3.14, 'arg4': 4 }
</code>```

How to do that? Recursion is not desirable.

答:
When you pass arg2 to the function, the function does not know that it was named arg2 when you passed it in, it just know its value is 2. You would have to get stack trace to know who called that function, scrape source code to get the name and then it would be simple.

But what if I call it like this:

```<code>func(2)
</code>```

what output do you expect then?

Body:
Function func(*args, **kwargs) should return dictionary, and all elements of that dictionary should be numeric or string variables.
If argument of function is dictionary, then function should return dictionary with all elements of argument dictionary, and other arguments.
For example:

arg1 = { 'x': 'X', 'y': 'Y' }
arg2 = 2
arg3 = { 'p': arg1, 'pi': 3.14 }
func(arg2, arg3, arg4=4)

should return this:

{ 'x': 'X', 'y': 'Y', 'arg2': 2, 'pi': 3.14, 'arg4': 4 }

How to do that? Recursion is not desirable.

Body:
When you pass arg2 to the function, the function does not know that it was named arg2 when you passed it in, it just know its value is 2. You would have to get stack trace to know who called that function, scrape source code to get the name and then it would be simple.

But what if I call it like this:

func(2)

what output do you expect then?


问:
How to train existing GRNN in MATLAB?
I have created a GRNN using command:

```<code>net = newgrnn(inputs, output);
</code>```

How do I train existing GRNN on new inputs in MATLAB? In other words, how to train net on other inputs?

答: GRNN can not be trained in the sense of backpropagation. It is single pass learning. It will assign new neuron for every input pattern so in order to train it just include the data point in the command newgrnn(1:n,1:m);</p>

Title: How to train existing GRNN in MATLAB?

Body:
I have created a GRNN using command:

net = newgrnn(inputs, output);

How do I train existing GRNN on new inputs in MATLAB? In other words, how to train net on other inputs?


问:
How to use environment variables to run node app in atom IDE
I have node project that contains .bat file to set all the env variables & then it run my server.js .
How can i achieve the same using IDE?
Currently when i am trying to run the code from atom ide its giving error for those environment variables not set as they are required to run my project.

While running from command prompt i can simply run the .bat file which sets all the environment variables required for my project followed by "node server.js" command to run my project.

But from atom IDE when i run server.js it is not able to find the environment variables. How can i define/set these environment variables so that the atom IDE can read it & use them when i run server.js.??

答:
Install XAtom NodeJS Debugger: apm install xatom-debug-nodejs

Toolbar will be shown,

Choose your project,
click on Node.js button and in the popup shown configure your project setting and
environment variables.


问:
Is there a way to return comparator which wont do anything?
I have two classes extending one parent class and there is a method which sorts data by some parameter. So for one of these two classes, I need to apply some sorting but for two others don't do anything. Is there such possibility?</p>

```<code>public class MedicalCompositeRatesData{

  @Override
  public List<RateTableData> buildData(RateTableInputBean inputBean)
  {
    SGQuotingData sgQuotingData = inputBean.getQuotingData();

    List<ProductData> products = extractorFactory
      .getProductExtractor(inputBean.getPlanType(), inputBean.getRatingType())
      .extract(sgQuotingData);

    List<Row> rates = products.stream()
        .map(it -> buildRow(it, sgQuotingData))
        .sorted(getProductComparator())
        .filter(Objects::nonNull)
        .collect(Collectors.toList());

    return buildRateTables(rates);
  }

  protected Comparator<Product> getProductComparator(){
    //should leave default sorting
  }

}

public class AlternateCompositeRatesBuilder extends MedicalCompositeRatesData
{

  protected Comparator<Product> getProductComparator(){
    //will sort by rate
  }

}
</code>```

答:
Stream.sort makes a stable sort if the stream is ordered. In other words, if two elements are equals then they'll keep their initial ordering.

Thus, as your stream is made from a List, you can simply make all elements equal :

```<code>protected Comparator<Product> getProductComparator() {
    return (a1, a2) -> 0;
}
</code>```

That's not very cool-looking though but it should do the job.

Body:
I have two classes extending one parent class and there is a method which sorts data by some parameter. So for one of these two classes, I need to apply some sorting but for two others don't do anything. Is there such possibility?

public class MedicalCompositeRatesData{

  @Override
  public List<RateTableData> buildData(RateTableInputBean inputBean)
  {
    SGQuotingData sgQuotingData = inputBean.getQuotingData();

    List<ProductData> products = extractorFactory
      .getProductExtractor(inputBean.getPlanType(), inputBean.getRatingType())
      .extract(sgQuotingData);

    List<Row> rates = products.stream()
        .map(it -> buildRow(it, sgQuotingData))
        .sorted(getProductComparator())
        .filter(Objects::nonNull)
        .collect(Collectors.toList());

    return buildRateTables(rates);
  }

  protected Comparator<Product> getProductComparator(){
    //should leave default sorting
  }

}

public class AlternateCompositeRatesBuilder extends MedicalCompositeRatesData
{

  protected Comparator<Product> getProductComparator(){
    //will sort by rate
  }

}

Body:
Stream.sort makes a stable sort if the stream is ordered. In other words, if two elements are equals then they'll keep their initial ordering.

Thus, as your stream is made from a List, you can simply make all elements equal :

protected Comparator<Product> getProductComparator() {
    return (a1, a2) -> 0;
}

That's not very cool-looking though but it should do the job.


问:
Simple Form Query
I'm using .Net 4.5.2 and MongoDB. What I want to make is just a simple query, which gets user list from table with given user FirstName , LastName etc. I wrote;

```<code>   var Users = DataAccess.DbLoad<User>().Where(UserInfo =>
        ((FirstName == null || FirstName == "") || UserInfo.FirstName == FirstName) &&
        ((LastName == null || LastName == "") || UserInfo.LastName == LastName)
        ).ToList();
</code>```

But if I write any surname and click for search, it doesn't bring any record but when I check db, I see it's there.

First Name Search Fiedl: null

Last Name Search Field: Lüle

Table: FirstName: "Ahmet", LastName: "Lüle"

How can I solve this? What is the problem?

答:
Just remove the && condition if you want to search in both fields As follow:-</p>

```<code>  var Users = DataAccess.DbLoad<User>();
If(FirstName != null){
users=users.Where(u => u.FirstName.ToLower().Equals(FirstName.ToLower()))
}
 If(LastName != null){
users=users.Where(u => u.LastName .ToLower().Equals(LastName .ToLower()))
}
</code>```

Title: Simple Form Query

Body:
I'm using .Net 4.5.2 and MongoDB. What I want to make is just a simple query, which gets user list from table with given user FirstName , LastName etc. I wrote;

   var Users = DataAccess.DbLoad<User>().Where(UserInfo =>
        ((FirstName == null || FirstName == "") || UserInfo.FirstName == FirstName) &&
        ((LastName == null || LastName == "") || UserInfo.LastName == LastName)
        ).ToList();

But if I write any surname and click for search, it doesn't bring any record but when I check db, I see it's there.

First Name Search Fiedl: null

Last Name Search Field: Lüle

Table: FirstName: "Ahmet", LastName: "Lüle"

How can I solve this? What is the problem?

Body:
Just remove the && condition if you want to search in both fields As follow:-

  var Users = DataAccess.DbLoad<User>();
If(FirstName != null){
users=users.Where(u => u.FirstName.ToLower().Equals(FirstName.ToLower()))
}
 If(LastName != null){
users=users.Where(u => u.LastName .ToLower().Equals(LastName .ToLower()))
}


问:
How can I access another user's resources (specifically emails) using Microsoft Graph in an MVC app?
I seem to be having issues giving my application the permissions required to access another user in the oranization's email messages. I had my admin grant my application all of the possible permissions through the Azure Portal and I’m getting an ‘Access is Denied’ error in the test application I downloaded from the Graph website. This makes me think that perhaps I am not using the correct call to the API.

Here is the code I’m using to retrieve another user’s email:

```<code>IMailFolderMessagesCollectionPage messages = await graphClient.Users["userID"].MailFolders.Inbox.Messages.Request().Top(25).GetAsync();
</code>```

where “userID” is the id value I obtained from getting all users in my organization through the graph explorer.

Full code:

(Controller)

```<code>[Authorize]
public async Task<ActionResult> GetEmails()
        {
        try
        {
            // Initialize the GraphServiceClient.
            GraphServiceClient graphClient = SDKHelper.GetAuthenticatedClient();

            ResultsViewModel results = new ResultsViewModel();
            // Get the messages.
            results.Items = await graphService.GetMyInboxMessages(graphClient);
            return View("Graph", results);
        }
        catch (ServiceException se)
        {
            if (se.Error.Code == Resource.Error_AuthChallengeNeeded) return new EmptyResult();
            return RedirectToAction("Index", "Error", new { message = Resource.Error_Message + Request.RawUrl + ": " + se.Error.Message });
        }
    }
</code>```

(graphService.cs)

```<code>public async Task<List<ResultsItem>> GetMyInboxMessages(GraphServiceClient graphClient)
    {
        List<ResultsItem> items = new List<ResultsItem>();

        // Get messages in the Inbox folder.
        //IMailFolderMessagesCollectionPage messages = await graphClient.Me.MailFolders.Inbox.Messages.Request().GetAsync();
        IMailFolderMessagesCollectionPage messages = await graphClient.Users["e87151ce-093b-4820-a98c-4cef247ed2be"].MailFolders.Inbox.Messages.Request().Top(25).GetAsync();

        string recipients = string.Empty;
        if (messages?.Count > 0)
        {
            foreach (Message message in messages)
            {
                //foreach (Recipient recipient in message.ToRecipients)
                for (int i = 0; i < message.ToRecipients.Count(); i++)
                    recipients += ((i != 0 ? "; " : "") + message.ToRecipients.ElementAt(i).EmailAddress.Address.ToString());

                items.Add(new ResultsItem
                {
                    Type = "message",
                    SentDateTime = message.SentDateTime.Value.DateTime.ToLocalTime(),
                    Subject = message.Subject,
                    From = message.From.EmailAddress.Address.ToString(),
                    To = recipients,
                    Id = message.Id,
                    Body = message.Body.Content.ToString()
                });
            }
        }
        return items;
    }
</code>```

Is this an incorrect GET request? Or is it a permissions issue?

Thanks in advance for your help.

答:
You could request app only token (client credential flow) using Read mail in all mailboxes application permissions for access to the Microsoft Graph.  According to your description , you register application in azure portal (azure ad v1.0) , you could try below steps:

set Read mail in all mailboxes application permissions for microsoft graph api :

ask your admin to grant permissions (do admin consent for application permission)for all accounts in current directory by clicking Grant Permissions button as shown in above screenshot .

Use client credential flow to acquire app only token using ADAL library :
AzureAuthenticationProvider .cs :

```<code>public class AzureAuthenticationProvider : IAuthenticationProvider
{
    private string _azureDomain = "xxxx.onmicrosoft.com";

    public async Task AuthenticateRequestAsync(HttpRequestMessage request)
    {
      try
      {
        string clientId = "xxxxx-xxxx-xxxx-xxxx-xxxxxxxx";
        string clientSecret = "xxxxxxxxxxxxxxxxxxxxxxxxxx";

        AuthenticationContext authContext = new AuthenticationContext("https://login.windows.net/" + _azureDomain + "/oauth2/token");

        ClientCredential credentials = new ClientCredential(clientId, clientSecret);

        AuthenticationResult authResult = await authContext.AcquireTokenAsync("https://graph.microsoft.com/", credentials);

        request.Headers.Add("Authorization", "Bearer " + authResult.AccessToken);
      }
      catch (Exception ex)
      {
      }
    }
}
</code>```

if you decode your token , you will find Mail.Read app permission in roles claim .

Then you could use Microsoft graph client library to get mails of users :

```<code>    GraphServiceClient graphClient = new GraphServiceClient(new AzureAuthenticationProvider());

    //List<ResultsItem> items = new List<ResultsItem>();
    IMailFolderMessagesCollectionPage messages = await graphClient.Users["77cac441-8279-452e-8904-ff24ddf5c715"].MailFolders.Inbox.Messages.Request().Top(25).GetAsync();
</code>```

The result :

Body:
I seem to be having issues giving my application the permissions required to access another user in the oranization's email messages. I had my admin grant my application all of the possible permissions through the Azure Portal and I’m getting an ‘Access is Denied’ error in the test application I downloaded from the Graph website. This makes me think that perhaps I am not using the correct call to the API.

Here is the code I’m using to retrieve another user’s email:

IMailFolderMessagesCollectionPage messages = await graphClient.Users["userID"].MailFolders.Inbox.Messages.Request().Top(25).GetAsync();

where “userID” is the id value I obtained from getting all users in my organization through the graph explorer.

Full code:

(Controller)

[Authorize]
public async Task<ActionResult> GetEmails()
        {
        try
        {
            // Initialize the GraphServiceClient.
            GraphServiceClient graphClient = SDKHelper.GetAuthenticatedClient();

            ResultsViewModel results = new ResultsViewModel();
            // Get the messages.
            results.Items = await graphService.GetMyInboxMessages(graphClient);
            return View("Graph", results);
        }
        catch (ServiceException se)
        {
            if (se.Error.Code == Resource.Error_AuthChallengeNeeded) return new EmptyResult();
            return RedirectToAction("Index", "Error", new { message = Resource.Error_Message + Request.RawUrl + ": " + se.Error.Message });
        }
    }

(graphService.cs)

public async Task<List<ResultsItem>> GetMyInboxMessages(GraphServiceClient graphClient)
    {
        List<ResultsItem> items = new List<ResultsItem>();

        // Get messages in the Inbox folder.
        //IMailFolderMessagesCollectionPage messages = await graphClient.Me.MailFolders.Inbox.Messages.Request().GetAsync();
        IMailFolderMessagesCollectionPage messages = await graphClient.Users["e87151ce-093b-4820-a98c-4cef247ed2be"].MailFolders.Inbox.Messages.Request().Top(25).GetAsync();

        string recipients = string.Empty;
        if (messages?.Count > 0)
        {
            foreach (Message message in messages)
            {
                //foreach (Recipient recipient in message.ToRecipients)
                for (int i = 0; i < message.ToRecipients.Count(); i++)
                    recipients += ((i != 0 ? "; " : "") + message.ToRecipients.ElementAt(i).EmailAddress.Address.ToString());

                items.Add(new ResultsItem
                {
                    Type = "message",
                    SentDateTime = message.SentDateTime.Value.DateTime.ToLocalTime(),
                    Subject = message.Subject,
                    From = message.From.EmailAddress.Address.ToString(),
                    To = recipients,
                    Id = message.Id,
                    Body = message.Body.Content.ToString()
                });
            }
        }
        return items;
    }

Is this an incorrect GET request? Or is it a permissions issue?

Thanks in advance for your help.

Body:
You could request app only token (client credential flow) using Read mail in all mailboxes application permissions for access to the Microsoft Graph.  According to your description , you register application in azure portal (azure ad v1.0) , you could try below steps:

set Read mail in all mailboxes application permissions for microsoft graph api :

ask your admin to grant permissions (do admin consent for application permission)for all accounts in current directory by clicking Grant Permissions button as shown in above screenshot .

Use client credential flow to acquire app only token using ADAL library :
AzureAuthenticationProvider .cs :

public class AzureAuthenticationProvider : IAuthenticationProvider
{
    private string _azureDomain = "xxxx.onmicrosoft.com";

    public async Task AuthenticateRequestAsync(HttpRequestMessage request)
    {
      try
      {
        string clientId = "xxxxx-xxxx-xxxx-xxxx-xxxxxxxx";
        string clientSecret = "xxxxxxxxxxxxxxxxxxxxxxxxxx";

        AuthenticationContext authContext = new AuthenticationContext("https://login.windows.net/" + _azureDomain + "/oauth2/token");

        ClientCredential credentials = new ClientCredential(clientId, clientSecret);

        AuthenticationResult authResult = await authContext.AcquireTokenAsync("https://graph.microsoft.com/", credentials);

        request.Headers.Add("Authorization", "Bearer " + authResult.AccessToken);
      }
      catch (Exception ex)
      {
      }
    }
}

if you decode your token , you will find Mail.Read app permission in roles claim .

Then you could use Microsoft graph client library to get mails of users :

    GraphServiceClient graphClient = new GraphServiceClient(new AzureAuthenticationProvider());

    //List<ResultsItem> items = new List<ResultsItem>();
    IMailFolderMessagesCollectionPage messages = await graphClient.Users["77cac441-8279-452e-8904-ff24ddf5c715"].MailFolders.Inbox.Messages.Request().Top(25).GetAsync();

The result :


问:
What Javascript Programming Patterns Do You Use?
I'm in the process of re-examining a lot of my code, and I keep coming back to the question, "Which pattern should I base all of my JS classes on?"

Some example patterns:
http://www.klauskomenda.com/code/javascript-programming-patterns/

I ended up with a mix-in approach, with basic pub/sub functionality. I don't use prototype, or the module pattern, I define public/private properties/methods within the constructor.

For example:

```<code>function ClassName(){
    var _privateVar = 'private';
    this.publicVar = 'public';
    function _privateMethod(){};
    this.publicMethod = function(){};
}
</code>```

What patterns do you often use in JS? For what purpose? Regular websites? Full web app? What made you pick one pattern over another?

Or do you think it matters less than I think it does?

Thanks in advance.

EDIT: well, I do use prototype, just not to define all my methods. But I'm leaning towards that approach due to performance? Thoughts?

答:
Some things to consider

Defining public functions with inner functions is more expensive since you generate a new function for every instantiation of an object. Defining it on the prototype uses a single copy of the methods.

I always use underscores for private methods/properties, as you have, for clarity.

I also use the module pattern to define static private methods within a class. Since they don't need access to the instance, they are only created once.

Body:
I'm in the process of re-examining a lot of my code, and I keep coming back to the question, "Which pattern should I base all of my JS classes on?"

Some example patterns:
http://www.klauskomenda.com/code/javascript-programming-patterns/

I ended up with a mix-in approach, with basic pub/sub functionality. I don't use prototype, or the module pattern, I define public/private properties/methods within the constructor.

For example:

function ClassName(){
    var _privateVar = 'private';
    this.publicVar = 'public';
    function _privateMethod(){};
    this.publicMethod = function(){};
}

What patterns do you often use in JS? For what purpose? Regular websites? Full web app? What made you pick one pattern over another?

Or do you think it matters less than I think it does?

Thanks in advance.

EDIT: well, I do use prototype, just not to define all my methods. But I'm leaning towards that approach due to performance? Thoughts?