问:
Subscribe inside subscribe and return an observable in Angular
Really need help on this. I have been trying different things but its not working.

```<code>function1() {
  return this.apiService.get().pipe(map(data => {
    return this.function2();
  }));
  }

function2() {
   const urls = [];

   for (let i = 1; i <= 5; i++) {
      urls.push(
        this.apiService
          .get('/users/?page=' + i)
          .pipe(map(data => data))
      );
    }

   forkJoin(...urls).subscribe(data => {
     data.forEach(element => {
        results = results.concat(element.results);
      });
     return results;
     })
    }

this.someService.function1().subscribe(data => {
console.log(data);
})
</code>```

So basically, i want to print out data that i subscribe in function1(). But the results of function1() relying on function2() which another subscribe().

I do know why but just dont know how to solve it.when i run the script i alway get undefined, the reason is because the function1() could not wait the function2() to return the results.

I got stuck here. Thanks,

ANSWER: I figured out that i should not return the results in function2 as an array.

```<code>function2() {
   const urls = [];

   for (let i = 1; i <= 5; i++) {
      urls.push(
        this.apiService
          .get('/users/?page=' + i)
          .pipe(map(data => data))
      );
    }

   return forkJoin(urls);
</code>```

and then based on the output of funtion2, i will do the rest in function1 which is the concat()....

答:
You're going to want switchMap - Documentation

Once you have the result from function1, you want to "switch" to waiting on function2

```<code>function1() {
    return this.apiService.get().pipe(switchMap(function1Data => {
        // Send function2 whatever data it needs
        // Example:
        return this.function2(function1Data.function2Argument).pipe(map(function2Data => {
            // Combine function1Data and function2Data as needed
            // Example:
            const result = {
                function1Property: function1Data.property,
                function2Property: function2Data.property
            };
            return result;
        }));
    });
}
</code>```

Body:
Really need help on this. I have been trying different things but its not working.

function1() {
  return this.apiService.get().pipe(map(data => {
    return this.function2();
  }));
  }

function2() {
   const urls = [];

   for (let i = 1; i <= 5; i++) {
      urls.push(
        this.apiService
          .get('/users/?page=' + i)
          .pipe(map(data => data))
      );
    }

   forkJoin(...urls).subscribe(data => {
     data.forEach(element => {
        results = results.concat(element.results);
      });
     return results;
     })
    }

this.someService.function1().subscribe(data => {
console.log(data);
})

So basically, i want to print out data that i subscribe in function1(). But the results of function1() relying on function2() which another subscribe().

I do know why but just dont know how to solve it.when i run the script i alway get undefined, the reason is because the function1() could not wait the function2() to return the results.

I got stuck here. Thanks,

ANSWER: I figured out that i should not return the results in function2 as an array.

function2() {
   const urls = [];

   for (let i = 1; i <= 5; i++) {
      urls.push(
        this.apiService
          .get('/users/?page=' + i)
          .pipe(map(data => data))
      );
    }

   return forkJoin(urls);

and then based on the output of funtion2, i will do the rest in function1 which is the concat()....

Body:
You're going to want switchMap - Documentation

Once you have the result from function1, you want to "switch" to waiting on function2

function1() {
    return this.apiService.get().pipe(switchMap(function1Data => {
        // Send function2 whatever data it needs
        // Example:
        return this.function2(function1Data.function2Argument).pipe(map(function2Data => {
            // Combine function1Data and function2Data as needed
            // Example:
            const result = {
                function1Property: function1Data.property,
                function2Property: function2Data.property
            };
            return result;
        }));
    });
}


来源: stackexchange

问:
Unable to get the response of mongoose query inside Vuejs but works with postman request
server side
first here is how my Api works

```<code>  searchPosts(params) {
    return Api().get('search', params);
  },
</code>```

```<code>var postRouter = express.Router();

postRouter.get('/search', (req, res) => {
  var db = req.db;
  Post.find({ capacity: { $lte : req.body.capacity } }, function (error, q) {
    if (error) { console.error(error); }
    res.send({q})
  })
})
</code>```

with this, in my express route im able to do GET request on /search with the body

```<code>{
    "capacity":60
}
</code>```

for exemple, and have a working-as-intended response

```<code>{
    "q": [
        {
         "obj":"obj"
        },
     ]
}
</code>```

Website side
in my .Vue file i call this function after a clic on a button

```<code><v-btn
:disabled="!formIsValid"
flat
color="primary"
type="submit"
@click="searchPost">Search</v-btn>
</code>```

```<code>  methods: {
    async searchPost() {
      const response = await PostsService.searchPosts({
        capacity: this.form.capacity,
        equipments: this.createObjectFromArray(this.form.equipments),
        date: this.form.date,
        time: this.form.time,
      });
      console.log(response);
      this.availableList = response.q;
    },
</code>```

in postman i'm correctly getting a q[] array with all my filtered object inside but on chrome request have no q inside

for my Api logs, i'm getting no error with Postman but

```<code>message:
   'Cast to number failed for value "undefined" at path "capacity" for model "Post"',
  name: 'CastError',
...
</code>```

on the real test on the web

for information, this.availableList is defined inside Data()

```<code> data() {
    const defaultForm = Object.freeze({
      capacity: 0,
      date: new Date().toISOString().substr(0, 10),
      time: null,
      equipments: [],
    });
    return {
      form: Object.assign({}, defaultForm),
      datePicker: false,
      hourMenu: false,
      availableList: [],
      allList: [],
      defaultForm,
    };
  },
</code>```

答:
i've edited my request like so in my vuejs file

```<code>async searchPost() {
      const response = await PostsService.searchPosts({
        capacity: this.form.capacity,
        equipments: this.createObjectFromArray(this.form.equipments),
        date: this.form.date,
        time: this.form.time,
      });
      this.availableList = response.data;
    },
</code>```

in my Api ive changed it like so

```<code>  searchPosts(params) {
    return Api().get('search', { params });
  },
</code>```

what a fool was i to try to run a get command by passing parameters inside the body and not the query string

and so, i've updated my get function accordingly

```<code>postRouter.get('/search', (req, res) => {
  var db = req.db;
  Post.find({ capacity: { $lte : req.query.capacity } }, 'title description capacity equipments resa', function (error, q) {
    if (error) { return res.status(500).send(error); }
    res.send(q);
  })
})
</code>```

to find my find parameter inside req.query and no more the body

ContentLicense: CC BY-SA 4.0

Body:
server side
first here is how my Api works

  searchPosts(params) {
    return Api().get('search', params);
  },

var postRouter = express.Router();

postRouter.get('/search', (req, res) => {
  var db = req.db;
  Post.find({ capacity: { $lte : req.body.capacity } }, function (error, q) {
    if (error) { console.error(error); }
    res.send({q})
  })
})

with this, in my express route im able to do GET request on /search with the body

{
    "capacity":60
}

for exemple, and have a working-as-intended response

{
    "q": [
        {
         "obj":"obj"
        },
     ]
}

Website side
in my .Vue file i call this function after a clic on a button

<v-btn
:disabled="!formIsValid"
flat
color="primary"
type="submit"
@click="searchPost">Search</v-btn>

  methods: {
    async searchPost() {
      const response = await PostsService.searchPosts({
        capacity: this.form.capacity,
        equipments: this.createObjectFromArray(this.form.equipments),
        date: this.form.date,
        time: this.form.time,
      });
      console.log(response);
      this.availableList = response.q;
    },

in postman i'm correctly getting a q[] array with all my filtered object inside but on chrome request have no q inside

for my Api logs, i'm getting no error with Postman but

message:
   'Cast to number failed for value "undefined" at path "capacity" for model "Post"',
  name: 'CastError',
...

on the real test on the web

for information, this.availableList is defined inside Data()

 data() {
    const defaultForm = Object.freeze({
      capacity: 0,
      date: new Date().toISOString().substr(0, 10),
      time: null,
      equipments: [],
    });
    return {
      form: Object.assign({}, defaultForm),
      datePicker: false,
      hourMenu: false,
      availableList: [],
      allList: [],
      defaultForm,
    };
  },

Body:
i've edited my request like so in my vuejs file

async searchPost() {
      const response = await PostsService.searchPosts({
        capacity: this.form.capacity,
        equipments: this.createObjectFromArray(this.form.equipments),
        date: this.form.date,
        time: this.form.time,
      });
      this.availableList = response.data;
    },

in my Api ive changed it like so

  searchPosts(params) {
    return Api().get('search', { params });
  },

what a fool was i to try to run a get command by passing parameters inside the body and not the query string

and so, i've updated my get function accordingly

postRouter.get('/search', (req, res) => {
  var db = req.db;
  Post.find({ capacity: { $lte : req.query.capacity } }, 'title description capacity equipments resa', function (error, q) {
    if (error) { return res.status(500).send(error); }
    res.send(q);
  })
})

to find my find parameter inside req.query and no more the body


问:
Package for creating Windows service
What currently can be used to distribute application as Windows service?

py2exe supports Python under 3.4 but pywin32 is deprecated.
Pyinstaller creates *.exe without errors, but it works only in debug mode.

Didn't try cx_Freeze. As I understand it overrides service name that I store in my app from parsed config.ini?

And for Pyinstaller I checked all hidden imports.  Only win32timezone is needed.
And that part was used too

```<code>if __name__ == '__main__':
        if len(sys.argv) == 1:
            servicemanager.Initialize()
            servicemanager.PrepareToHostSingle(WinService)
            servicemanager.StartServiceCtrlDispatcher()
        else:
            win32serviceutil.HandleCommandLine(WinService)
</code>```

I'd like to use Python 3.x, because of unicode.

答:
pywin32 on sourceforge is retired. See the migration to github pywin32-@github.

For an example see python-script-as-a-service-in-windows

Title: Package for creating Windows service

Body:
What currently can be used to distribute application as Windows service?

py2exe supports Python under 3.4 but pywin32 is deprecated.
Pyinstaller creates *.exe without errors, but it works only in debug mode.

Didn't try cx_Freeze. As I understand it overrides service name that I store in my app from parsed config.ini?

And for Pyinstaller I checked all hidden imports.  Only win32timezone is needed.
And that part was used too

if __name__ == '__main__':
        if len(sys.argv) == 1:
            servicemanager.Initialize()
            servicemanager.PrepareToHostSingle(WinService)
            servicemanager.StartServiceCtrlDispatcher()
        else:
            win32serviceutil.HandleCommandLine(WinService)

I'd like to use Python 3.x, because of unicode.


问:
php does not echo back POST data
I have the following jQuery script to post form data to php.  I'm testing the form data with a simple php file to echo back the firstname field of the input post:datastring as a test (I'm new to using php so that's why I'm testing it).

```<code><script type="text/javascript">
$("#btn_submit").on("click", function (event) {
    event.preventDefault();
    form_data = $('form').serialize()
    var datastring = JSON.stringify({form_data});
    console.log("Okay, I'm starting");
    console.log(form_data);
    console.log(datastring);
    return $.ajax({
        type: "POST",
        url: "echo_test.php",
        data: {post: datastring},
        success: function (responseText) {
            console.log(responseText);
        },
        error: function (error) {
            console.log("Okay, I failed" + error);
        }
    });
});
</code>```

The simple php file:

```<code><?php
echo 'Hello ' . htmlspecialchars($_POST["firstname"]) . '!';
?>
</code>```

Here's what the Firefox dev console echoes back:

```<code>Okay, I'm starting
email_field=mj%40abc.com&firstname=mary&lastname=jones&comments=no+comment%0D%0A
{"form_data":"email_field=mj%40abc.com&firstname=mary&lastname=jones&comments=no+comment%0D%0A"}
</code>```

and finally it echoes back:

```<code>Hello !
</code>```

So the Hello part and the exclamation point are echoed back, but not the firstname field.  I can see that the datastring it posts to the php file does contain firstname=mary, so there is a value in that field.

Why doesn't the firstname field echo back?

答:
Since you use

```<code>data: {post: datastring},
</code>```

the datastring value will be in $_POST['post']. It will be encoded as JSON, so you'll need to call json_decode() to decode it.

But you calso use form_data = $('form').serialize(). form_data will therefore be in URL-encoded format. You'll need to use parse_str() to decode this.

And the syntax {form_data} is shorthand for {form_data: form_data}, so you'll have to access the form_data property of the decoded JSON.

So the PHP needs to be:

```<code><?php
$datastring = $_POST['post'];
$datastring_decoded = json_decode($datastring);
$form_data = datastring_decoded->form_data;
$params = parse_str($form_data);
$firstname = $params['firstname'];
echo "Hello $firstname";
</code>```

It would have been much simpler if you just used

```<code>data: form_data,
</code>```

in the $.ajax() call. Then the parameter would be in $_POST['firstname']. There's rarely any need to use JSON when posting with $.ajax(), unless you're calling an API that specifically requires this instead of application/x-www-form-urlencoded or multipart/form-data format.

Title: php does not echo back POST data

Body:
Since you use

data: {post: datastring},

the datastring value will be in $_POST['post']. It will be encoded as JSON, so you'll need to call json_decode() to decode it.

But you calso use form_data = $('form').serialize(). form_data will therefore be in URL-encoded format. You'll need to use parse_str() to decode this.

And the syntax {form_data} is shorthand for {form_data: form_data}, so you'll have to access the form_data property of the decoded JSON.

So the PHP needs to be:

<?php
$datastring = $_POST['post'];
$datastring_decoded = json_decode($datastring);
$form_data = datastring_decoded->form_data;
$params = parse_str($form_data);
$firstname = $params['firstname'];
echo "Hello $firstname";

It would have been much simpler if you just used

data: form_data,

in the $.ajax() call. Then the parameter would be in $_POST['firstname']. There's rarely any need to use JSON when posting with $.ajax(), unless you're calling an API that specifically requires this instead of application/x-www-form-urlencoded or multipart/form-data format.


问:
Sum of two arrays
The exercise says "Make a function with parameters two int arrays and k which is their size. The function should return another array (size k) where every element of it is the sum of the two arrays of the same position. That's what I wrote, but it crashes. Do I have to do it with pointers?

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

void sumarray(int k,int A[k],int B[k]){
   int sum[k],i;
   for(i=0;i<k;i++){
   sum[i]=A[i]+B[i];
   printf("sum[%d]=%d\n",i,sum[i]);}

 }

main(){
   int i,g,a[g],b[g];
   printf("Give size of both arrays: ");
   scanf("%d",&g);
   for(i=0;i<g;i++){
      a[i]=rand();
      b[i]=rand();
   }
   sumarray(g,a,b);
   system("pause");
}
</code>```

Example: If i have A={1,2,3,4} and B={4,3,2,1} the program will return C={5,5,5,5).

答:
```<code>int sum[k] ;
</code>```

k is a variable but the size of the array should be a constant.

The function should return another array (size k) ...

But the function you wrote returns void which is clearly wrong.

Do I have to do it with pointers?

Yes.

ContentLicense: CC BY-SA 3.0

Title: Sum of two arrays

Body:
The exercise says "Make a function with parameters two int arrays and k which is their size. The function should return another array (size k) where every element of it is the sum of the two arrays of the same position. That's what I wrote, but it crashes. Do I have to do it with pointers?

#include <stdio.h>
#include <stdlib.h>

void sumarray(int k,int A[k],int B[k]){
   int sum[k],i;
   for(i=0;i<k;i++){
   sum[i]=A[i]+B[i];
   printf("sum[%d]=%d\n",i,sum[i]);}

 }

main(){
   int i,g,a[g],b[g];
   printf("Give size of both arrays: ");
   scanf("%d",&g);
   for(i=0;i<g;i++){
      a[i]=rand();
      b[i]=rand();
   }
   sumarray(g,a,b);
   system("pause");
}

Example: If i have A={1,2,3,4} and B={4,3,2,1} the program will return C={5,5,5,5).

Body:
int sum[k] ;

k is a variable but the size of the array should be a constant.

The function should return another array (size k) ...

But the function you wrote returns void which is clearly wrong.

Do I have to do it with pointers?

Yes.


问:
Apache Rewrite with Multiple Parameters
I need to rewrite the following types of URLs:

http://www.gocruise.co.uk/fusion/detailline3.pl?lineid=13&sid=6924&ccid=Fred+Olsen

into:

http://www.gocruise.co.uk/fred-olsen

using an Apache RewriteRule. I have been trying to get to grips with these rewrites as quick as i can but have run out of time. Any help will be much appreciated.

(the main bit im struggling with is how to manage the multiple parameters)

答: Unless lineid and sid are always going to be the same values, or they're not important to the code, I don't think it's going to work.  Typically, url rewrites include all the parameters, so you'd end up with something like http://www.gocruise.co.uk/13/6924/fred-olsen</p>

Title: Apache Rewrite with Multiple Parameters


问:
In dplyr groups, how can I select a group that has a combination of a specific value with only ONE other of multiple values
I have a dataset that looks like this

```<code>Group  Company
1      A
1      XX
1      A
1      XX
2      XX
2      A
2      XX
2      B
3      B
3      B
3      XX
3      A
4      C
4      C
4      XX
4      XX
</code>```

It's actually bigger with more columns and rows and values, but the problem I want to solve involves these two columns for now.

Now, what I would like to achieve is, for each Group, to replace Company in the following way:

If XX exists in a Group, together with any other unique Company value, then Company should be replaced with this unique value. Like so:

```<code>Group  Company
1      A
1      XX
1      A
1      XX
</code>```

Should become:

```<code>Group  Company
1      A
1      A
1      A
1      A
</code>```

If any Group contains more than 2 unique values for Company, including "XX", then this group's Company value should remain unchanged, like so:

```<code>Group  Company
2      XX
2      A
2      XX
2      B
</code>```

I am trying to achieve this using dplyr, I managed to do what I wanted but for only one value of Company, like so:

```<code>result <- df%>%
group_by(Group) %>%
mutate(final = ifelse(Company %in% c("A", "XX"), 1,2)) %>%
summarize(test = mean(final))

result$final <- ifelse(result$test== 1, "A", result$Company)
</code>```

I could probably do this with a loop, but I am pretty sure this would not be the best way to do it.

Is there a clean way to do this with dplyr ? (of course other solutions are more than welcome)

The final dataframe would then look like this:

```<code>Group  Company
1      A
1      A
1      A
1      A
2      XX
2      A
2      XX
2      B
3      B
3      B
3      XX
3      A
4      C
4      C
4      C
4      C
</code>```

Thank you all for your time.

答:
Here's a way with dplyr -

```<code>df %>%
  group_by(Group) %>%
  mutate(
    Company = case_when(
                ("XX" %in% Company) && (n_distinct(Company) == 2) ~ Company[Company != "XX"][1],
                TRUE ~ Company
              )
  ) %>%
  ungroup()

# A tibble: 16 x 2
   Group Company
   <int> <chr>
 1     1 A
 2     1 A
 3     1 A
 4     1 A
 5     2 XX
 6     2 A
 7     2 XX
 8     2 B
 9     3 B
10     3 B
11     3 XX
12     3 A
13     4 C
14     4 C
15     4 C
16     4 C
</code>```

Body:
I have a dataset that looks like this

Group  Company
1      A
1      XX
1      A
1      XX
2      XX
2      A
2      XX
2      B
3      B
3      B
3      XX
3      A
4      C
4      C
4      XX
4      XX

It's actually bigger with more columns and rows and values, but the problem I want to solve involves these two columns for now.

Now, what I would like to achieve is, for each Group, to replace Company in the following way:

If XX exists in a Group, together with any other unique Company value, then Company should be replaced with this unique value. Like so:

Group  Company
1      A
1      XX
1      A
1      XX

Should become:

Group  Company
1      A
1      A
1      A
1      A

If any Group contains more than 2 unique values for Company, including "XX", then this group's Company value should remain unchanged, like so:

Group  Company
2      XX
2      A
2      XX
2      B

I am trying to achieve this using dplyr, I managed to do what I wanted but for only one value of Company, like so:

result <- df%>%
group_by(Group) %>%
mutate(final = ifelse(Company %in% c("A", "XX"), 1,2)) %>%
summarize(test = mean(final))

result$final <- ifelse(result$test== 1, "A", result$Company)

I could probably do this with a loop, but I am pretty sure this would not be the best way to do it.

Is there a clean way to do this with dplyr ? (of course other solutions are more than welcome)

The final dataframe would then look like this:

Group  Company
1      A
1      A
1      A
1      A
2      XX
2      A
2      XX
2      B
3      B
3      B
3      XX
3      A
4      C
4      C
4      C
4      C

Thank you all for your time.

Body:
Here's a way with dplyr -

df %>%
  group_by(Group) %>%
  mutate(
    Company = case_when(
                ("XX" %in% Company) && (n_distinct(Company) == 2) ~ Company[Company != "XX"][1],
                TRUE ~ Company
              )
  ) %>%
  ungroup()

# A tibble: 16 x 2
   Group Company
   <int> <chr>
 1     1 A
 2     1 A
 3     1 A
 4     1 A
 5     2 XX
 6     2 A
 7     2 XX
 8     2 B
 9     3 B
10     3 B
11     3 XX
12     3 A
13     4 C
14     4 C
15     4 C
16     4 C


问:
Visual Studio 2017 keeps re-formatting my code and it's driving me nuts
There is 1 page, and only 1 page in all the pages I've ever built that has this problem.  Whenever I save my "Settings.aspx" page in Visual Studio, it loves to play a funny prank and re-format all my code!  And no, there's no other developer here playing an actual prank on me.  I thought this particular issue pops up because I have an unclosed tag somewhere, but I ran my code through a unclosed tag checker, and it says I'm good.

Haven't really tried any fix, since I have no idea where to begin.  I don't want to turn off Visual Studio's IntelliSense and the auto-formatting that happens as I type.  But I certainly want to turn off the auto-formatting that happens EVERY SINGLE TIME I press the Save button.  Which I do a lot..."Computers 101" right?

My beautiful code changes from this:

```<code><table style="width:100%;">
    <tr>
        <td>
            <h3>Job Titles</h3>
        </td>
        <td>

        </td>
        <td>
            <h3>Job Change Reasons</h3>
        </td>
        <td>

        </td>
        <td>
            <h3>Employment Types</h3>
        </td>
    </tr>
</table>
</code>```

To this:

```<code><table style="width:100%;">
    <tr>
        <td>
            <h3>Job Titles</h3></td><td>
              </td><td>
            <h3>Job Change Reasons</h3></td><td>
              </td><td>
            <h3>Employment Types</h3></td></tr><tr></table>
</code>```

And it's driving me nuts!  It not only reformats it, but somehow it wipes out an element and then I get an error in my code.

Please help save my sanity..

UPDATE

Well I did see 1 option that I wanted to change to make things more useful.  But nothing that applies to this particular issue.  My VS seems to have a mind of it's own.  I adjusted the specific formatting setting for "td" so it would auto-format like this:

```<code><td>

</td>
</code>```

And yet when it does it's crazy re-formatting, it still adjusts my stuff like this:

```<code><tr>
    <td>
          </td><td>
          </td></tr><tr>
</code>```

This code is smack dab in the middle of the body, so I don't think the Javascript options apply.  Any more ideas?

答:
You can turn this off for HTML in particular by going to 'Tools -> Options -> Text Editor -> HTML (Web Forms) -> Formatting'. There are a few options there that you can play with to get you what you're looking for.

Here's another link for reading on the topic: https://github.com/Microsoft/TypeScript/issues/21139

Body:
There is 1 page, and only 1 page in all the pages I've ever built that has this problem.  Whenever I save my "Settings.aspx" page in Visual Studio, it loves to play a funny prank and re-format all my code!  And no, there's no other developer here playing an actual prank on me.  I thought this particular issue pops up because I have an unclosed tag somewhere, but I ran my code through a unclosed tag checker, and it says I'm good.

Haven't really tried any fix, since I have no idea where to begin.  I don't want to turn off Visual Studio's IntelliSense and the auto-formatting that happens as I type.  But I certainly want to turn off the auto-formatting that happens EVERY SINGLE TIME I press the Save button.  Which I do a lot..."Computers 101" right?

My beautiful code changes from this:

Job Titles

Job Change Reasons

Employment Types

To this:

Job Titles

Job Change Reasons

Employment Types

And it's driving me nuts!  It not only reformats it, but somehow it wipes out an element and then I get an error in my code.

Please help save my sanity..

UPDATE

Well I did see 1 option that I wanted to change to make things more useful.  But nothing that applies to this particular issue.  My VS seems to have a mind of it's own.  I adjusted the specific formatting setting for "td" so it would auto-format like this:

And yet when it does it's crazy re-formatting, it still adjusts my stuff like this:

This code is smack dab in the middle of the body, so I don't think the Javascript options apply.  Any more ideas?


问:
Change colour of jitter points according to facet_wrap
I want to compare the number of different coloured flowers (red and green) at two different sites. I have a boxplot in ggplot2 with a jitter plot in the background. I want the colour of the jitter points to be different according to the colour of the flowers. Not sure how to do this! Is there a way to colour code my facets depending on the colour of the flower?

Some sample data:

```<code>site <- c(rep(1, 4), rep(2, 4))

colour <- c("red", "green", "red", "green", "red", "green", "red", "green")
number <- c(12, 24, 22, 14, 12, 16, 18, 17)

df <- data.frame(site, colour, number)
df$site <- as.factor(df$site)

ggplot(df, aes(site, number))+
  facet_wrap("colour")+
  geom_jitter(alpha = 0.3) +
  geom_boxplot(alpha = 0, colour = "black")+
  theme(legend.position = "none")
</code>```

答:
While both answers here address your problem, I think they are unnecessarily convoluted.

ggplot(df, aes(site, number)) +
  facet_wrap(~colour) +
  geom_jitter(alpha = 0.3, color = colour) +
  geom_boxplot(alpha = 0, color = "black")
```

Created on 2019-05-30 by the reprex package (v0.3.0)

You don't need theme(legend.position = "none") since within your geoms you don't have any arguments inside aes().

In one of the answers, while we set the legend position to none (it is needed there since colour is inside aesthetics)  we also have show.legend = F which is redundant.

Your colour columns is already c("red", "green") so we don't need to use scale_color.

Body:
I want to compare the number of different coloured flowers (red and green) at two different sites. I have a boxplot in ggplot2 with a jitter plot in the background. I want the colour of the jitter points to be different according to the colour of the flowers. Not sure how to do this! Is there a way to colour code my facets depending on the colour of the flower?

Some sample data:

site <- c(rep(1, 4), rep(2, 4))

colour <- c("red", "green", "red", "green", "red", "green", "red", "green")
number <- c(12, 24, 22, 14, 12, 16, 18, 17)

df <- data.frame(site, colour, number)
df$site <- as.factor(df$site)

ggplot(df, aes(site, number))+
  facet_wrap("colour")+
  geom_jitter(alpha = 0.3) +
  geom_boxplot(alpha = 0, colour = "black")+
  theme(legend.position = "none")

Body:
While both answers here address your problem, I think they are unnecessarily convoluted.

ggplot(df, aes(site, number)) +
  facet_wrap(~colour) +
  geom_jitter(alpha = 0.3, color = colour) +
  geom_boxplot(alpha = 0, color = "black")

Created on 2019-05-30 by the reprex package (v0.3.0)

You don't need theme(legend.position = "none") since within your geoms you don't have any arguments inside aes().

In one of the answers, while we set the legend position to none (it is needed there since colour is inside aesthetics)  we also have show.legend = F which is redundant.

Your colour columns is already c("red", "green") so we don't need to use scale_color.


问:
While creating Azure HDInsight cluster for Starburst Presto, can I create Spark Cluster?
While creating infrastructure for big data, I wanted to use Azure HDInsight with Presto installation. Azure HDInsight comes with different flavors like hadoop, spark etc. In documentations it is recommended to use hadoop cluster but I want to use the spark one.

Is it possible to use spark cluster with Starburst's Presto distribution?

答:
It looks like you want to use both Presto and Spark at the same time.
If you run them on a single cluster, you would need to configure them appropriately to make sure the JVMs for different processes can co-exist. This is possible, but hard to do in practice (you need to know how JVM allocates memory beyond -Xmx setting), so it's definitely not recommended.

While I can imagine that in some on-premises installations where provisioning new hardware is hard you could want to colocate services on one cluster. In the cloud, it's much more convenient to provision two separate clusters, each appropriately sized for your particular needs and workload. For example, you could have one cluster with Presto for interactive analytics, dashboarding and ad-hoc queries. And another one with Spark for your machine learning or ETL workloads.

Please refer to the Starburst Presto on Azure documentation for detailed configuration instructions.


问:
How can I use "float: left" in a div without breaking the containing element's height?
It seems that floated HTML elements don't expand the heights of their containers. For example, consider the following code:

.portfoliosite {
    background: #777;
    padding: 10px;
    width: 550px;
}
.portfoliothumbnail {
    background: red;
    margin: 0 10px 10px 0;
    float: left;
    height: 150px;
    width: 150px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="portfoliosite">
    <div class="portfoliothumbnail"><!-- Img tag goes here --></div>
    <p class="portfoliotitle">AwesomeSite.Com</p>
    <p class="portfoliodescription">An awesome site I did. It launched on Jan 1, 2009</p>
</div></code>```

Notice how the containing div with the gray background is shorter than the red div, and the red div extends outside the container's boundaries. I'd like the containing element to expand to the size of its contents, including the floated element.

Is there an elegant solution for accomplishing this, preferably one that doesn't involve setting a fixed height or using JavaScript?

答: Renders fine in my IE7 on Vista. What version of IE & what platform are you using?</p>

OwnerDisplayName: Joshua Carmody

Body:
It seems that floated HTML elements don't expand the heights of their containers. For example, consider the following code:

.portfoliosite {
    background: #777;
    padding: 10px;
    width: 550px;
}
.portfoliothumbnail {
    background: red;
    margin: 0 10px 10px 0;
    float: left;
    height: 150px;
    width: 150px;
}

AwesomeSite.Com

An awesome site I did. It launched on Jan 1, 2009

Notice how the containing div with the gray background is shorter than the red div, and the red div extends outside the container's boundaries. I'd like the containing element to expand to the size of its contents, including the floated element.

Is there an elegant solution for accomplishing this, preferably one that doesn't involve setting a fixed height or using JavaScript?

LastEditorDisplayName: Joshua Carmody

ContentLicense: CC BY-SA 2.5


问:
Java threadpool oversubscription
I have mainly CPU intensive operation which is running on a thread pool.
Operation however has certain amount of waiting foe external events which doesn't happen uniformly in time.
Since in Java, as far as I know, there is not a thread pool implementation which automatically sizes its number of threads based on observed task throughput (as in Microsoft's CLR 4), is there at least a way to manually tell to thread pool to increase its size when a blocking operation starts and to decrease when it ends?

For example with 8 cores, pool size is 8.
  If operation is 100% CPU bound, just use this fixed pool.
  If there is some blocking operation, one should be able to do this:

```<code>pool.increase();
waitForSpecialKeyPress();
pool.decrease();
</code>```

Here is how it is being done in Microsoft's C++ Async library: Use Oversubscription to Offset Latency

答:
You could extend ThreadPoolExecutor to add your own increase() and decrease() functions, which do simple setMaximumPoolSize(getMaximumPoolSize() +/- 1).

Make sure to synchronize the methods, to make sure you don't mess up the pool size by accident.

Title: Java threadpool oversubscription

Body:
I have mainly CPU intensive operation which is running on a thread pool.
Operation however has certain amount of waiting foe external events which doesn't happen uniformly in time.
Since in Java, as far as I know, there is not a thread pool implementation which automatically sizes its number of threads based on observed task throughput (as in Microsoft's CLR 4), is there at least a way to manually tell to thread pool to increase its size when a blocking operation starts and to decrease when it ends?

For example with 8 cores, pool size is 8.
  If operation is 100% CPU bound, just use this fixed pool.
  If there is some blocking operation, one should be able to do this:

pool.increase();
waitForSpecialKeyPress();
pool.decrease();

Here is how it is being done in Microsoft's C++ Async library: Use Oversubscription to Offset Latency


问:
Unable to extract Name from text in R
I am trying to figure out what regex to use to extract the name from text. Each name has a first initial, a period, and last name followed by what seems to be a code for space () which for some reason shows up when I uploaded the csv to R.

Here are four examples of how the text is laid out:

```<code>D. Nowitzki<U+00A0>misses 2-pt jump shot from 17 ft
J. Calderon<U+00A0>misses 2-pt jump shot from 12 ft
Turnover by<U+00A0>M. Ellis<U+00A0>(bad pass; steal by<U+00A0>T.
Splitter)
</code>```

Defensive rebound byS. Marion

```<code>    data$Player <- sub("(.*\\..*)<", "\\1", data$Play)

    data$Player <- sub("(.*\\..*)<", "\\1", data$Play)
</code>```

答:
Your pattern, (.*\..*)<, captures into Group 1 any 0+ chars as many as possible, then a . char,  then any 0+ chars as many as possible and then a < is matched. So, you match quite a lot of text and it is not quite clear if  is a literal text or if it is an entity standing for a non-breaking space in your data. If the latter is true, your pattern is just not matching because there is no <.

I assume you want to extract the first match starting with a letter as a whole word followed with a dot, then any 0 or more whitespaces and then 1+ letters. Hence, you may use

```<code>\b\p{Lu}\.\s*\p{L}+
</code>```

See the regex demo.

Details

\b - a word boundary

\p{Lu} - any uppercase Unicode letter
-\. - a dot

\s* - 0+ whitespaces

\p{L}+ - any 1+ Unicode letters

In R, you may easily use the pattern with stringr::str_extract that extracts the first match only:

```<code>res <- stringr::str_extract(data$Play, "\\b\\p{Lu}\\.\\s*\\p{L}+")
</code>```

Title: Unable to extract Name from text in R

Body:
I am trying to figure out what regex to use to extract the name from text. Each name has a first initial, a period, and last name followed by what seems to be a code for space () which for some reason shows up when I uploaded the csv to R.

Here are four examples of how the text is laid out:

D. Nowitzkimisses 2-pt jump shot from 17 ft
J. Calderonmisses 2-pt jump shot from 12 ft
Turnover byM. Ellis(bad pass; steal byT.
Splitter)

Defensive rebound byS. Marion

    data$Player <- sub("(.*\\..*)<", "\\1", data$Play)

    data$Player <- sub("(.*\\..*)<", "\\1", data$Play)

Body:
Your pattern, (.*\..*)<, captures into Group 1 any 0+ chars as many as possible, then a . char,  then any 0+ chars as many as possible and then a < is matched. So, you match quite a lot of text and it is not quite clear if <U+00A0> is a literal text or if it is an entity standing for a non-breaking space in your data. If the latter is true, your pattern is just not matching because there is no <.

I assume you want to extract the first match starting with a letter as a whole word followed with a dot, then any 0 or more whitespaces and then 1+ letters. Hence, you may use

\b\p{Lu}\.\s*\p{L}+

See the regex demo.

Details

\b - a word boundary

\p{Lu} - any uppercase Unicode letter
-\. - a dot

\s* - 0+ whitespaces

\p{L}+ - any 1+ Unicode letters

In R, you may easily use the pattern with stringr::str_extract that extracts the first match only:

res <- stringr::str_extract(data$Play, "\\b\\p{Lu}\\.\\s*\\p{L}+")


问:
How to externalise folder with electron?
I'm using angular-electron to build a windows desktop application with angular 7 and electron 4. Now I would like to externalise a specific folder(let's say config folder) at the root of the unpacked build. There are a lot of files inside config folder used in the application and which could be edited by the final user

Here is the unpacked structure I want:

How to manage this ?

答:
In the electron-builder.json under the build section add

```<code>"asarUnpack": [
      ... your files or folders
    ]
</code>```

Doc: https://www.electron.build/configuration/configuration#configuration-asarUnpack

After that, your file/folder will be inside the resources\asarUnpack folder.

Body:
In the electron-builder.json under the build section add

"asarUnpack": [
      ... your files or folders
    ]

Doc: https://www.electron.build/configuration/configuration#configuration-asarUnpack

After that, your file/folder will be inside the resources\asarUnpack folder.


问:
Get span Id's of selected text using getSelected()
I have a weird problem. I don’t quite know how to approach it. We have an application that spits out paragraphs of text with each and every word wrapped in a span with an ID. I am being asked to make a JavaScript to capture the ID's of all the words that a user highlights.

So a simple example of a paragraph is below.

```<code><span id="p-58" class="softWord" onClick="setTranscriptPosition(-58);return false"> that </span>
<span id="p177" class="softWord" onClick="setTranscriptPosition(177);return false"> quake </span>
<span id="p857" class="softWord" onClick="setTranscriptPosition(857);return false"> briefly </span>
<span id="p1697" class="softWord" onClick="setTranscriptPosition(1697);return false"> triggering </span>
<span id="p2267" class="softWord" onClick="setTranscriptPosition(2267);return false"> another </span>
<span id="p2697" class="softWord" onClick="setTranscriptPosition(2697);return false"> tsunami </span>
</code>```

I know there is a way to capture the selected text using something like this:(found this at site http://motyar.blogspot.com/2010/02/get-user-selected-text-with-jquery-and.html)

```<code>function getSelected() {
    if(window.getSelection) { return window.getSelection(); }
        else if(document.getSelection) { return document.getSelection(); }
                    else {
                            var selection = document.selection && document.selection.createRange();
                            if(selection.text) { return selection.text; }
                return false;
            }
            return false;
        }
</code>```

How would i get the id's of those spans though?

答:
Ok, this will do exactly what you need.  It's thanks to my friend's work on a project we did together, so the credit belongs to him:

http://jsfiddle.net/KC48j/11/

Just select some text and hit the button.  EDIT: updated to work with IE as well.  You can mess around with the logic yourself (how it handles whitespace between words is up to you).

Body:
I have a weird problem. I don’t quite know how to approach it. We have an application that spits out paragraphs of text with each and every word wrapped in a span with an ID. I am being asked to make a JavaScript to capture the ID's of all the words that a user highlights.

So a simple example of a paragraph is below.

 that
 quake
 briefly
 triggering
 another
 tsunami

I know there is a way to capture the selected text using something like this:(found this at site http://motyar.blogspot.com/2010/02/get-user-selected-text-with-jquery-and.html)

function getSelected() {
    if(window.getSelection) { return window.getSelection(); }
        else if(document.getSelection) { return document.getSelection(); }
                    else {
                            var selection = document.selection && document.selection.createRange();
                            if(selection.text) { return selection.text; }
                return false;
            }
            return false;
        }

How would i get the id's of those spans though?


问:
Antd: I'm trying to change the default styling of Antd's checkboxes using styled components to make the checkbox larger and change the color to black
I have an Antd checkbox that I'm trying to make larger, alter the thickness of the box itself and change the color to black but every style I apply creates a second square that sits over the checkbox and doesn't change the checkbox itself. Does anyone have any ideas on how to do this?</p>

答: Figured this out by using &&&{border: 2px solid ${({ theme }) => theme.colors.black} the triple ampersand allows you to add more specificity when working with mixed styled components like mine.


问:
Google Analytics - only track traffic to a folder of the site
I want to track traffic for mysite.com/current-campaign/ and careless about traffic on mysite.com in general.

Is it ok to place the GA tracking code in the files inside the /current-campaign/ folder or does it HAVE TO be in the root of the server for tracking to work?

答: In Google Analytics, you can add a filter to the profile and filter all but the chosen directories. Go to  Analytics Settings > Profile Settings and look for "Add Filter" link.</p>


问:
What makes the 'Request Entity Too Large' error when sending an image to Telegram?
File size: 51.2 KB
Trying to send:

>>> send_img_url = 'https://api.telegram.org/botXXXXXXXXXXXXXXXXXXXXX/sendPhoto'
>>> img_name = 'C:/Users/Administrator/Downloads/WhatsApp Image 2019-05-30 at 20.54.40.jpeg'
>>> r = requests.post(send_img_url, data={'chat_id': '-351543550', 'photo': open(img_name, 'rb')})
>>> r
<Response [413]>
>>> r.reason
'Request Entity Too Large'
>>> r.content
b''
>>>
```

<p>Also i try some another requests like:</p>

<pre class="lang-py prettyprint-override"><code>photo = open(('C:/Users/Administrator/Downloads/WhatsAppImage.jpeg').encode('utf-8'), 'rb')
r = requests.post(send_img_url, data={'chat_id': '-351543550', 'photo': photo})
</code>```

and:

 with io.open('C:/Users/Administrator/Downloads/WhatsAppImage.jpeg', encoding='utf-8', errors='ignore') as f:
    r = requests.post(send_img_url, data={'chat_id': '-351543550', 'photo': f})
```

<p>Last option give me next error:</p>

<pre class="lang-py prettyprint-override"><code>>>> r
<Response [400]>
>>> r.reason
'Bad Request'
</code>```

答:
You're probably doing it wrong.

As Bot API docs says:

Post the file using multipart/form-data in the usual way that files are uploaded via the browser. 10 MB max size for photos, 50 MB for other files.

In requests lib, by using data= keyword argument, you're sending payload using form-encoded type, not multipart/form-data.

Try to make your request like that:

import requests

chat_id = '-351543550'
url = 'https://api.telegram.org/botXXXXXXXXXXXXXXX/sendPhoto?chat_id={}'.format(chat_id)
filepath = 'C:\correct\path\to\your\file.jpg'
r = requests.post(url, files={"photo": open(filepath, 'rb')})  # note: files, not data
print(r.status_code)
```

<p>P.S.: you can also send <code>chat_id</code> as <code>form-encoded</code> param by using </p>

<pre class="lang-py prettyprint-override"><code>url = 'https://api.telegram.org/botXXXXXXXXXXXXXXX/sendPhoto'
...
r = requests.post(url, data={'chat_id': '-351543550'}, files={"photo": open(filepath, 'rb')})
</code>```

Body:
File size: 51.2 KB
Trying to send:

>>> send_img_url = 'https://api.telegram.org/botXXXXXXXXXXXXXXXXXXXXX/sendPhoto'
>>> img_name = 'C:/Users/Administrator/Downloads/WhatsApp Image 2019-05-30 at 20.54.40.jpeg'
>>> r = requests.post(send_img_url, data={'chat_id': '-351543550', 'photo': open(img_name, 'rb')})
>>> r
<Response [413]>
>>> r.reason
'Request Entity Too Large'
>>> r.content
b''
>>>

Also i try some another requests like:

photo = open(('C:/Users/Administrator/Downloads/WhatsAppImage.jpeg').encode('utf-8'), 'rb')
r = requests.post(send_img_url, data={'chat_id': '-351543550', 'photo': photo})

and:

 with io.open('C:/Users/Administrator/Downloads/WhatsAppImage.jpeg', encoding='utf-8', errors='ignore') as f:
    r = requests.post(send_img_url, data={'chat_id': '-351543550', 'photo': f})

Last option give me next error:

>>> r
<Response [400]>
>>> r.reason
'Bad Request'

Body:
You're probably doing it wrong.

As Bot API docs says:

Post the file using multipart/form-data in the usual way that files are uploaded via the browser. 10 MB max size for photos, 50 MB for other files.

In requests lib, by using data= keyword argument, you're sending payload using form-encoded type, not multipart/form-data.

Try to make your request like that:

import requests

chat_id = '-351543550'
url = 'https://api.telegram.org/botXXXXXXXXXXXXXXX/sendPhoto?chat_id={}'.format(chat_id)
filepath = 'C:\correct\path\to\your\file.jpg'
r = requests.post(url, files={"photo": open(filepath, 'rb')})  # note: files, not data
print(r.status_code)

P.S.: you can also send chat_id as form-encoded param by using

url = 'https://api.telegram.org/botXXXXXXXXXXXXXXX/sendPhoto'
...
r = requests.post(url, data={'chat_id': '-351543550'}, files={"photo": open(filepath, 'rb')})


问:
I need delete two " " with sed command
I need to delete "" in file

```<code>"CITFFUSKD-E0"
</code>```

I have tried sed 's/\"//.

Result is:

```<code>CITFFUSKD-E0"
</code>```

How I can delete both ?

Also I need to delete everything behind first word but input can be this one:

```<code>"CITFFUSKD-E0"
"CITFFUSKD_E0"
"CITFFUSKD E0"
</code>```

Result I want it:

```<code>CITFFUSKD
</code>```

答:
awk '{gsub(/^.|....$/,"")}NR==1' file

CITFFUSKD

Title: I need delete two " " with sed command

Body:
I need to delete "" in file

"CITFFUSKD-E0"

I have tried sed 's/\"//.

Result is:

CITFFUSKD-E0"

How I can delete both ?

Also I need to delete everything behind first word but input can be this one:

"CITFFUSKD-E0"
"CITFFUSKD_E0"
"CITFFUSKD E0"

Result I want it:

CITFFUSKD


问:
cv2.VideoWriter: Asks for a tuple as Size argument, then rejects it
I'm using OpenCV 4.0 and Python 3.7 to create a timelapse video.

When constructing a VideoWriter object, the documentation says the Size argument should be a tuple.

When I give it a tuple it rejects it. When I try to replace it with something else, it won't accept it because it says the argument isn't a tuple.

When Size not a tuple:

```<code>out = cv2.VideoWriter('project.avi', 1482049860, 30, height, width)
SystemError: new style getargs format but argument is not a tuple
</code>```

When I changed Size to a tuple:

```<code>out = cv2.VideoWriter('project.avi', 1482049860, 30, (height, width))
TypeError: must be real number, not tuple
</code>```

I just want to create a simple cv2.VideoWriter object.

答:
I was trying to take the height and width from an uploaded video using:

```<code>width = cap.get(cv2.CAP_PROP_FRAME_WIDTH)
height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
</code>```

I changed it to:

```<code>width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
</code>```

Now I don't get that error. It doesn't work yet as a whole, but that particular error isn't there anymore.

Body:
I'm using OpenCV 4.0 and Python 3.7 to create a timelapse video.

When constructing a VideoWriter object, the documentation says the Size argument should be a tuple.

When I give it a tuple it rejects it. When I try to replace it with something else, it won't accept it because it says the argument isn't a tuple.

When Size not a tuple:

out = cv2.VideoWriter('project.avi', 1482049860, 30, height, width)
SystemError: new style getargs format but argument is not a tuple

When I changed Size to a tuple:

out = cv2.VideoWriter('project.avi', 1482049860, 30, (height, width))
TypeError: must be real number, not tuple

I just want to create a simple cv2.VideoWriter object.

Body:
I was trying to take the height and width from an uploaded video using:

width = cap.get(cv2.CAP_PROP_FRAME_WIDTH)
height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)

I changed it to:

width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

Now I don't get that error. It doesn't work yet as a whole, but that particular error isn't there anymore.


问:
Remove the last part of a string after underscore and random digit
My string looks like

```<code>$img_name = "my_beautiful_picture_123456_789101112131415_16171819202122.jpg"
</code>```

What's the easiest way to remove from the first underscore followed by a digit to the end?

I would like to output

```<code>my_beautiful_picture
</code>```

I tried

```<code>$img_name = substr($img_name, 0, strpos($img_name, "_"));
</code>```

and

```<code>$img_name = preg_replace('/_[0-9].*/', '', $img_name);
</code>```

But result is my for both, I'm not very familiar with regex.

答:
We could simply use a simple expression with preg_replace or preg_match or preg_match_all:

```<code>_[0-9].+
</code>```

Test

```<code>$re = '/_[0-9].+/s';
$str = 'my_beautiful_picture_123456_789101112131415_16171819202122.jpg';
$subst = '';

$result = preg_replace($re, $subst, $str);

echo $result;
</code>```

Output

```<code>my_beautiful_picture
</code>```

DEMO

RegEx Circuit

jex.im visualizes regular expressions:

Body:
My string looks like

$img_name = "my_beautiful_picture_123456_789101112131415_16171819202122.jpg"

What's the easiest way to remove from the first underscore followed by a digit to the end?

I would like to output

my_beautiful_picture

I tried

$img_name = substr($img_name, 0, strpos($img_name, "_"));

and

$img_name = preg_replace('/_[0-9].*/', '', $img_name);

But result is my for both, I'm not very familiar with regex.

Body:
We could simply use a simple expression with preg_replace or preg_match or preg_match_all:

_[0-9].+

Test

$re = '/_[0-9].+/s';
$str = 'my_beautiful_picture_123456_789101112131415_16171819202122.jpg';
$subst = '';

$result = preg_replace($re, $subst, $str);

echo $result;

Output

my_beautiful_picture

DEMO

RegEx Circuit

jex.im visualizes regular expressions:


问:
How can I search in month and year in SQL Server 2012?
I'm trying to write a query for searching for month and year only. What I made is searching for month. Can someone tell how I can modify this query to search for month and year like : 5/2019 or 5-2019 ?</p>

```<code>select firstname, lastname, date
from tblInfo
where data = 02/2019
</code>```

答:
Compare DATEPART of date with your constant/variable like:

```<code>... WHERE DATEPART(yy,tbleInfoAwareness.date) = 2019 AND DATEPART(mm,tbleInfoAwareness.date) = 5
</code>```

Another method is to compare date range - it is better because may use index:

```<code>.... WHERE tbleInfoAwareness.date BETWEEN '2019-05-01` AND '2019-05-31 23:59:59'
</code>```

PS: Added time for last day.

Body:
I'm trying to write a query for searching for month and year only. What I made is searching for month. Can someone tell how I can modify this query to search for month and year like : 5/2019 or 5-2019 ?

select firstname, lastname, date
from tblInfo
where data = 02/2019

Body:
Compare DATEPART of date with your constant/variable like:

... WHERE DATEPART(yy,tbleInfoAwareness.date) = 2019 AND DATEPART(mm,tbleInfoAwareness.date) = 5

Another method is to compare date range - it is better because may use index:

.... WHERE tbleInfoAwareness.date BETWEEN '2019-05-01` AND '2019-05-31 23:59:59'

PS: Added time for last day.


问:
Heat map visualizing touch input on smartphone (weighted 2d binning, histogram)
I have a dataset where each sample consists of x- and y-position, timestamp and a pressure value of touch input on a smartphone. I have uploaded the dataset here (OneDrive): data.csv

It can be read by:

```<code>import pandas as pd
df = pd.read_csv('data.csv')
</code>```

Now, I would like to create a heat map visualizing the pressure distribution in the x-y space.

I envision a heat map which looks like the left or right image:

For a heat map of spatial positions a similar approach as given here could be used. For the heat map of pressure values the problem is that there are 3 dimensions, namely the x- and y-position and the pressure.

I'm happy about every input regarding the creation of the heat map.

答:
There are several ways data can be binned. One is just by the number of events. Functions like numpy.histogram2d or hist2d allow to specify weights to each data point to manipulate the weight of each event.

But there is a more general histogram function that might be useful in your case: scipy.stats.binned_statistic_2d

By using the keyword argument statistic you can pick how the value of each bin is calculated from the values that lie within:

mean

std

median

count

sum

min

max

or a user defined function

I guess in your case mean or median might be a good solution.

Body:
I have a dataset where each sample consists of x- and y-position, timestamp and a pressure value of touch input on a smartphone. I have uploaded the dataset here (OneDrive): data.csv

It can be read by:

import pandas as pd
df = pd.read_csv('data.csv')

Now, I would like to create a heat map visualizing the pressure distribution in the x-y space.

I envision a heat map which looks like the left or right image:

For a heat map of spatial positions a similar approach as given here could be used. For the heat map of pressure values the problem is that there are 3 dimensions, namely the x- and y-position and the pressure.

I'm happy about every input regarding the creation of the heat map.


问:
Adjust Xcode Build setting value based on environment variable
I have a user defined build setting at the project level:

Which is fed into the Other Swift flags build setting also at the project level:

This causes the compiler to emit a warning when any function takes longer than 1000 ms to compile. The problem is that CI is much slower than our dev machines, so on our dev machines we would like it to be more like 300 ms, and on CI 2000+ ms, or maybe even just disabled. We run with warnings as errors, so if the CI which is shared machines goes slow this often causes the build to fail.

When running on CI there is a CI environment variable that is set, so I'd like to change the value of the LONG_SWIFT_COMPILE_LIMIT_MS build setting if CI is set or not. How can I do this? I tried adding:

```<code>if [ -z ${CI+x} ]; then
    # Not running on CI
    setenv LONG_SWIFT_COMPILE_LIMIT_MS 300
else
    # Running on CI
    setenv LONG_SWIFT_COMPILE_LIMIT_MS 2000
fi
</code>```

as a prebuild script on the scheme, but that didn't work.

答:
You can specify build setting overrides on the xcodebuild command line by adding <setting>=<value> arguments. For your case, LONG_SWIFT_COMPILE_LIMIT_MS=2000.

This can't be done by an Xcode scheme pre-build script.

Body:
I have a user defined build setting at the project level:

Which is fed into the Other Swift flags build setting also at the project level:

This causes the compiler to emit a warning when any function takes longer than 1000 ms to compile. The problem is that CI is much slower than our dev machines, so on our dev machines we would like it to be more like 300 ms, and on CI 2000+ ms, or maybe even just disabled. We run with warnings as errors, so if the CI which is shared machines goes slow this often causes the build to fail.

When running on CI there is a CI environment variable that is set, so I'd like to change the value of the LONG_SWIFT_COMPILE_LIMIT_MS build setting if CI is set or not. How can I do this? I tried adding:

if [ -z ${CI+x} ]; then
    # Not running on CI
    setenv LONG_SWIFT_COMPILE_LIMIT_MS 300
else
    # Running on CI
    setenv LONG_SWIFT_COMPILE_LIMIT_MS 2000
fi

as a prebuild script on the scheme, but that didn't work.


问:
Receiving IIS 500 error for static files when installed with Sitecore 7.2
Hopefully somebody can point me in the direction of a solution for this particular problem.

The Scenario (Sitecore 7.2 rev 140526)

I have a static 'index.html' file hosted in a folder (let us call it 'test') inside my Sitecore web application.

If I access the index.html file directly via a web browser, everything loads correctly.

However, if I access the directory (i.e. http://myweb.site/test/) I receive a 500 error.

The error message is binding to the default document correctly, as evidenced by the details in the error message.

UPDATE: I have been able to reproduce with a fresh 7.2 instance with the NTTData CDN Connector configuration file in place.

What I have tried already

To prevent Sitecore from serving it's 404, I updated IgnoreUrlPrefixes setting

The index.html file name is in the list of default documents for the site (and folder)

In order to bypass the ExtensionlessUrl handler for .NET and resolve a 404 error, I have re-ordered the Handler Mappings to place the StaticFile handler before the ExtensionlessUrlHandler handlers.

Running on the same IIS instance, I setup a separate site with the same files and the default document loading worked correctly.

I have verified that the folder in IIS has Anonymous Authentication enabled

I have tried providing the Everyone group with full control to the folder in NTFS permissions

I have validated that the folder and folder parents are not marked as 'Hidden'.

IIS Failed request tracing did not provide much, but I did notice the Sitecore Rewrite module changing the URL a few times in the handler pipelines to append a "?". Subsequent calls by the static module did not show any warnings or errors though.

I have reproduced with a blank Sitecore 7.2 instance by adding the NTTData CDN Connector configuration file

The error I am seeing

```<code>HTTP Error 500.0 - Internal Server Error
Module: DefaultDocumentModule
Notification: ExecuteRequestHandler
Handler: StaticFile
Error Code: 0x800703e9
Requested URL: http://myweb.site/test/index.html
Physical Path: C:\MyWebsite\test\index.html
Logon Method: Anonymous
Logon User: Anonymous
</code>```

Any thoughts?

答: I accidentally had a web.config in the folder. Deleted that. Everything worked.</p>

Body:
Hopefully somebody can point me in the direction of a solution for this particular problem.

The Scenario (Sitecore 7.2 rev 140526)

I have a static 'index.html' file hosted in a folder (let us call it 'test') inside my Sitecore web application.

If I access the index.html file directly via a web browser, everything loads correctly.

However, if I access the directory (i.e. http://myweb.site/test/) I receive a 500 error.

The error message is binding to the default document correctly, as evidenced by the details in the error message.

UPDATE: I have been able to reproduce with a fresh 7.2 instance with the NTTData CDN Connector configuration file in place.

What I have tried already

To prevent Sitecore from serving it's 404, I updated IgnoreUrlPrefixes setting

The index.html file name is in the list of default documents for the site (and folder)

In order to bypass the ExtensionlessUrl handler for .NET and resolve a 404 error, I have re-ordered the Handler Mappings to place the StaticFile handler before the ExtensionlessUrlHandler handlers.

Running on the same IIS instance, I setup a separate site with the same files and the default document loading worked correctly.

I have verified that the folder in IIS has Anonymous Authentication enabled

I have tried providing the Everyone group with full control to the folder in NTFS permissions

I have validated that the folder and folder parents are not marked as 'Hidden'.

IIS Failed request tracing did not provide much, but I did notice the Sitecore Rewrite module changing the URL a few times in the handler pipelines to append a "?". Subsequent calls by the static module did not show any warnings or errors though.

I have reproduced with a blank Sitecore 7.2 instance by adding the NTTData CDN Connector configuration file

The error I am seeing

HTTP Error 500.0 - Internal Server Error
Module: DefaultDocumentModule
Notification: ExecuteRequestHandler
Handler: StaticFile
Error Code: 0x800703e9
Requested URL: http://myweb.site/test/index.html
Physical Path: C:\MyWebsite\test\index.html
Logon Method: Anonymous
Logon User: Anonymous

Any thoughts?


问:
How to iterate through all sub-folders and their sub-sub-folders and so on using vba to check a folder if it exist?
I have below code to check if a folder exist on the predefined directory.

```<code>Option Explicit
Public xStatus As String

Sub Status()
Application.ScreenUpdating = False
Dim fso As Object
Dim folder As Object
Dim subfolders As Object
Dim subfolder1 As Object
Dim Rg As Range
Dim xCell As Range
Dim xTxt As String

xTxt = ActiveWindow.RangeSelection.Address
Set Rg = Application.InputBox("Please select city/cities to check production status!!!      ", "Lmtools", xTxt, , , , , 8)
If Rg Is Nothing Then
    MsgBox ("No cities selected!!!")
    Exit Sub
End If
Set fso = CreateObject("Scripting.FileSystemObject")
Set folder = fso.GetFolder("D:\")
Set subfolders = folder.subfolders
For Each xCell In Rg
    If xCell.Value <> "" Then
        For Each subfolder1 In subfolders
            xStatus = subfolder1.path
            If xStatus Like "*?\" & xCell.Value Then
                Cells(xCell.Row, xCell.Column + 1).Value = "Completed"
                Cells(xCell.Row, xCell.Column + 2).Value = xStatus
                GoTo nextiteration
            Else
                Cells(xCell.Row, xCell.Column + 1).Value = "Ongoing"
            End If
        Next
    End If
nextiteration:
Next

Application.ScreenUpdating = True
End Sub
</code>```

It works fine but only checks the sub-folders of "D:\" and not beyond that.

My folder could be present anywhere (either inside the sub-folders or their sub-folders or alongside "D:\"'s sub-folders.

my concern is how to iterate through all the folders.

答:
I creted this a while back. Basically i used this to rename file in folders and sub-folders,</p>

```<code>Option Explicit
Sub VersionRename()

Dim SelectedFolder As FileDialog
Dim T_Str As String
Dim FSO As Object
Dim RenamingFolder As Object, SubFolder As Object
Dim T_Name As String

Set SelectedFolder = Application.FileDialog(msoFileDialogFolderPicker)
    SelectedFolder.Title = "Select folder:"
    SelectedFolder.ButtonName = "Select Folder"
    If SelectedFolder.Show = -1 Then
        T_Str = SelectedFolder.SelectedItems(1)
    Else
        'MsgBox "Cancelled by user.", vbInformation
    Set SelectedFolder = Nothing
    Exit Sub
    End If

    Set SelectedFolder = Nothing

    Set FSO = CreateObject("Scripting.FileSystemObject")
    Set RenamingFolder = FSO.GetFolder(T_Str)
        File_Renamer RenamingFolder

    For Each SubFolder In RenamingFolder.SubFolders
        File_Renamer SubFolder
    Next

    Set SubFolder = Nothing
    Set RenamingFolder = Nothing
    Set FSO = Nothing

    MsgBox "Process completed!", vbInformation, Title:="Renaming Files"

End Sub
Private Sub File_Renamer(Folder As Object)

Dim File As Object
Dim T_Str As String
Dim T_Name As String
Dim PreVersionID As Variant
Dim NextVersionID As Variant
Dim StringReplace As String

    PreVersionID = Application.InputBox("Input 1 if no version number otherwise input existing version number:", Type:=1)
    If PreVersionID = False Then Exit Sub
    NextVersionID = Application.InputBox("Input your next version number:", Type:=1)
    If NextVersionID = False Then Exit Sub

    T_Str = Format("_V" & NextVersionID)

    For Each File In Folder.Files
        T_Name = File.Name
        'Debug.Print T_Name
        If NextVersionID > 1 Then
            StringReplace = Replace(T_Name, "_V" & PreVersionID, "", 1, 3)
            'Debug.Print StringReplace
            File.Name = Left(StringReplace, InStrRev(StringReplace, ".") - 1) & T_Str & Right(StringReplace, Len(StringReplace) - (InStrRev(StringReplace, ".") - 1))
        Else
            File.Name = Left(T_Name, InStrRev(T_Name, ".") - 1) & T_Str & Right(T_Name, Len(T_Name) - (InStrRev(T_Name, ".") - 1))
        End If
    Next
End Sub
</code>```

Body:
I have below code to check if a folder exist on the predefined directory.

Option Explicit
Public xStatus As String

Sub Status()
Application.ScreenUpdating = False
Dim fso As Object
Dim folder As Object
Dim subfolders As Object
Dim subfolder1 As Object
Dim Rg As Range
Dim xCell As Range
Dim xTxt As String

xTxt = ActiveWindow.RangeSelection.Address
Set Rg = Application.InputBox("Please select city/cities to check production status!!!      ", "Lmtools", xTxt, , , , , 8)
If Rg Is Nothing Then
    MsgBox ("No cities selected!!!")
    Exit Sub
End If
Set fso = CreateObject("Scripting.FileSystemObject")
Set folder = fso.GetFolder("D:\")
Set subfolders = folder.subfolders
For Each xCell In Rg
    If xCell.Value <> "" Then
        For Each subfolder1 In subfolders
            xStatus = subfolder1.path
            If xStatus Like "*?\" & xCell.Value Then
                Cells(xCell.Row, xCell.Column + 1).Value = "Completed"
                Cells(xCell.Row, xCell.Column + 2).Value = xStatus
                GoTo nextiteration
            Else
                Cells(xCell.Row, xCell.Column + 1).Value = "Ongoing"
            End If
        Next
    End If
nextiteration:
Next

Application.ScreenUpdating = True
End Sub

It works fine but only checks the sub-folders of "D:\" and not beyond that.

My folder could be present anywhere (either inside the sub-folders or their sub-folders or alongside "D:\"'s sub-folders.

my concern is how to iterate through all the folders.

Body:
I creted this a while back. Basically i used this to rename file in folders and sub-folders,

Option Explicit
Sub VersionRename()

Dim SelectedFolder As FileDialog
Dim T_Str As String
Dim FSO As Object
Dim RenamingFolder As Object, SubFolder As Object
Dim T_Name As String

Set SelectedFolder = Application.FileDialog(msoFileDialogFolderPicker)
    SelectedFolder.Title = "Select folder:"
    SelectedFolder.ButtonName = "Select Folder"
    If SelectedFolder.Show = -1 Then
        T_Str = SelectedFolder.SelectedItems(1)
    Else
        'MsgBox "Cancelled by user.", vbInformation
    Set SelectedFolder = Nothing
    Exit Sub
    End If

    Set SelectedFolder = Nothing

    Set FSO = CreateObject("Scripting.FileSystemObject")
    Set RenamingFolder = FSO.GetFolder(T_Str)
        File_Renamer RenamingFolder

    For Each SubFolder In RenamingFolder.SubFolders
        File_Renamer SubFolder
    Next

    Set SubFolder = Nothing
    Set RenamingFolder = Nothing
    Set FSO = Nothing

    MsgBox "Process completed!", vbInformation, Title:="Renaming Files"

End Sub
Private Sub File_Renamer(Folder As Object)

Dim File As Object
Dim T_Str As String
Dim T_Name As String
Dim PreVersionID As Variant
Dim NextVersionID As Variant
Dim StringReplace As String

    PreVersionID = Application.InputBox("Input 1 if no version number otherwise input existing version number:", Type:=1)
    If PreVersionID = False Then Exit Sub
    NextVersionID = Application.InputBox("Input your next version number:", Type:=1)
    If NextVersionID = False Then Exit Sub

    T_Str = Format("_V" & NextVersionID)

    For Each File In Folder.Files
        T_Name = File.Name
        'Debug.Print T_Name
        If NextVersionID > 1 Then
            StringReplace = Replace(T_Name, "_V" & PreVersionID, "", 1, 3)
            'Debug.Print StringReplace
            File.Name = Left(StringReplace, InStrRev(StringReplace, ".") - 1) & T_Str & Right(StringReplace, Len(StringReplace) - (InStrRev(StringReplace, ".") - 1))
        Else
            File.Name = Left(T_Name, InStrRev(T_Name, ".") - 1) & T_Str & Right(T_Name, Len(T_Name) - (InStrRev(T_Name, ".") - 1))
        End If
    Next
End Sub


问:
Android (complex) Calendar Layout
I wrote a calendar app and I'm now rethinking how to display the items. I don't want to use a simple table layout anymore because the different tasks have different durations.

What options are there to create a Layout like this instead of this?

I think drawing is no option respect to performance?
I would also like to use xclicklisteners...

答:
I did something extremely similar to what you want by creating my own view type (extended the View class, and handled my own drawing).  Performance is excellent as this is not typically data that is rapidly changing while the view is active (like a video game might).

It's also very simple to support all the usual (or custom) listeners for navigation, selection, touch, etc., etc., etc.

Food for thought.

Title: Android (complex) Calendar Layout


问:
Trouble extending Flask-Security login template
I'm using Flask-Security in my project and I would like to extend templates (namely login) it offers, in order to style them with custom CSS. Following the documentation, I've changed the SECURITY_LOGIN_USER_TEMPLATE config value to point to my template. In this template I'm extending the template provided by Flask-Security ("security/login_user.html") and changing the content of some of the blocks it defines (or its base).

My template renders as expected (looks like the standard "security/login_user.html"), the only problem being is that the blocks I'm trying to overwrite are not overwritten.

My template looks like this: login.html:

```<code>{% extends "security/login_user.html" %}

{% block content %}
<p>There should be no form.</p>
{% endblock content %}
</code>```

To confirm that I'm not not rendering the original template I've tried changing contents of the template file to empty and it works as expected - nothing is rendered.

What am I missing?

答:
After some time with debugger, I realized that something is wrong with the package Flask-Security that is available on PyPi. When developing my project I relied on source code that is present on their official github page. If you take a look at the login template, you notice that it indeed extends base template which provides definition of the blocks you can later overwrite.

However when you download the package from PyPi and then check the template you notice that it differs - it does not use Jinja2 inheritance, nor does it use any blocks, therefore the problem described in the question.

In other words, PyPi package is reflecting latest stable release (as noted by nick-k9), which differs significantly from develop branch.

Body:
I'm using Flask-Security in my project and I would like to extend templates (namely login) it offers, in order to style them with custom CSS. Following the documentation, I've changed the SECURITY_LOGIN_USER_TEMPLATE config value to point to my template. In this template I'm extending the template provided by Flask-Security ("security/login_user.html") and changing the content of some of the blocks it defines (or its base).

My template renders as expected (looks like the standard "security/login_user.html"), the only problem being is that the blocks I'm trying to overwrite are not overwritten.

My template looks like this: login.html:

{% extends "security/login_user.html" %}

{% block content %}

There should be no form.

{% endblock content %}

To confirm that I'm not not rendering the original template I've tried changing contents of the template file to empty and it works as expected - nothing is rendered.

What am I missing?


答:
You can use the MONTH and YEAR functions from T-SQL:

SELECT firstname, lastname , date FROM tblInfo
   WHERE MONTH(date) = 2 AND YEAR(date) = 2019
```

Title: How can I search in month and year in SQL Server 2012?


问:
How to speed up accessing a list of dicts inside a pandas dataframe column?
This may sound like a crazy way of storing data, but I am working with data that is sparse, and in an attempt to save space I have created dataframe where one column is a variable length list of dicts (from 1 to over a dozen dicts with three elements each).  I am trying to access the second element in each dict and make a new column with just a list of those second elements.  I can't actually paste my data, however I can provide an example that closely approximates it.

Imagine I have a dataframe of the attributes of my cats, dogs, and hamsters, and I had 3 cats, 1 dog, and 1 hamster, each with color and fur length data.  I'm basically trying to access a list of specific attributes for each animal type.  Now the code below works just fine.  However if you expand it to over 22,000 rows, it is VERY impossibly slow.  This is probably due to the for loop.

```<code>df = pd.DataFrame({'name':['cats','dogs','hamsters'],'attributes':[[{'color':'white','fur':'short'},{'color':'black','fur':'long'},{'color':'gray','fur':'long'}],[{'color':'brown','fur':'short'}],[{'color':'brown','fur':'short'}]]})

df['colors']=''
for i in range(len(df)):
  attributes = df.attributes.iloc[i]
  df.loc[i,['colors']] = [list(map(lambda x: x['color'],attributes))]
</code>```

df before:

```<code>       name                                         attributes
0      cats  [{'color': 'white', 'fur': 'short'}, {'color':...
1      dogs               [{'color': 'brown', 'fur': 'short'}]
2  hamsters               [{'color': 'brown', 'fur': 'short'}]
</code>```

df after:

```<code>       name  ...                colors
0      cats  ...  [white, black, gray]
1      dogs  ...               [brown]
2  hamsters  ...               [brown]
</code>```

I'm looking for a way to speed up this process, possibly with a lambda function?  Not sure, but there is almost always a way to ditch a for loop, however I'm just not able to see it.

答:
Doing it with function first (which can easily be a lambda if you want) and the dataframe.apply() method.

```<code>def extract_colors(x):
    return list(map(lambda a: a["color"], x))

df["colors"] = df.attributes.apply(extract_colors)
</code>```

If anything this should have a lower memory footprint as the function is broadcast across the dataframe/series and no large intermediate list is created.

Body:
This may sound like a crazy way of storing data, but I am working with data that is sparse, and in an attempt to save space I have created dataframe where one column is a variable length list of dicts (from 1 to over a dozen dicts with three elements each).  I am trying to access the second element in each dict and make a new column with just a list of those second elements.  I can't actually paste my data, however I can provide an example that closely approximates it.

Imagine I have a dataframe of the attributes of my cats, dogs, and hamsters, and I had 3 cats, 1 dog, and 1 hamster, each with color and fur length data.  I'm basically trying to access a list of specific attributes for each animal type.  Now the code below works just fine.  However if you expand it to over 22,000 rows, it is VERY impossibly slow.  This is probably due to the for loop.

df = pd.DataFrame({'name':['cats','dogs','hamsters'],'attributes':[[{'color':'white','fur':'short'},{'color':'black','fur':'long'},{'color':'gray','fur':'long'}],[{'color':'brown','fur':'short'}],[{'color':'brown','fur':'short'}]]})

df['colors']=''
for i in range(len(df)):
  attributes = df.attributes.iloc[i]
  df.loc[i,['colors']] = [list(map(lambda x: x['color'],attributes))]

df before:

       name                                         attributes
0      cats  [{'color': 'white', 'fur': 'short'}, {'color':...
1      dogs               [{'color': 'brown', 'fur': 'short'}]
2  hamsters               [{'color': 'brown', 'fur': 'short'}]

df after:

       name  ...                colors
0      cats  ...  [white, black, gray]
1      dogs  ...               [brown]
2  hamsters  ...               [brown]

I'm looking for a way to speed up this process, possibly with a lambda function?  Not sure, but there is almost always a way to ditch a for loop, however I'm just not able to see it.

Body:
Doing it with function first (which can easily be a lambda if you want) and the dataframe.apply() method.

def extract_colors(x):
    return list(map(lambda a: a["color"], x))

df["colors"] = df.attributes.apply(extract_colors)

If anything this should have a lower memory footprint as the function is broadcast across the dataframe/series and no large intermediate list is created.


问:
I want Shiny UI with multiple inputs in a row
I want shiny sliderInput to be biuld like attached image

side by side values i want like min and max. the input should be manual and not by slider or dropdown

I tried selectInput but its taking one value in a row I want two values in one row

答:
@BigDataScientist has a great answer. You can also look into splitLayout in your UI. First you call splitLayout, define the desired cellWidths, then call the objects.

```<code>splitLayout(cellWidths = c("50%", "50%"), selectInput(...), selectInput(...))
</code>```

Body:
@BigDataScientist has a great answer. You can also look into splitLayout in your UI. First you call splitLayout, define the desired cellWidths, then call the objects.

splitLayout(cellWidths = c("50%", "50%"), selectInput(...), selectInput(...))


问:
Sum of two arrays
The exercise says "Make a function with parameters two int arrays and k which is their size. The function should return another array (size k) where every element of it is the sum of the two arrays of the same position. That's what I wrote, but it crashes. Do I have to do it with pointers?

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

void sumarray(int k,int A[k],int B[k]){
   int sum[k],i;
   for(i=0;i<k;i++){
   sum[i]=A[i]+B[i];
   printf("sum[%d]=%d\n",i,sum[i]);}

 }

main(){
   int i,g,a[g],b[g];
   printf("Give size of both arrays: ");
   scanf("%d",&g);
   for(i=0;i<g;i++){
      a[i]=rand();
      b[i]=rand();
   }
   sumarray(g,a,b);
   system("pause");
}
</code>```

Example: If i have A={1,2,3,4} and B={4,3,2,1} the program will return C={5,5,5,5).

答: One issue is that you've attempted to declare dynamically sized arrays on the stack (e.g. a[g]).  You need to declare pointers for each array and then dynamically allocate your variable sized array once you've read in the value of g.

Title: Sum of two arrays

Body:
The exercise says "Make a function with parameters two int arrays and k which is their size. The function should return another array (size k) where every element of it is the sum of the two arrays of the same position. That's what I wrote, but it crashes. Do I have to do it with pointers?

#include <stdio.h>
#include <stdlib.h>

void sumarray(int k,int A[k],int B[k]){
   int sum[k],i;
   for(i=0;i<k;i++){
   sum[i]=A[i]+B[i];
   printf("sum[%d]=%d\n",i,sum[i]);}

 }

main(){
   int i,g,a[g],b[g];
   printf("Give size of both arrays: ");
   scanf("%d",&g);
   for(i=0;i<g;i++){
      a[i]=rand();
      b[i]=rand();
   }
   sumarray(g,a,b);
   system("pause");
}

Example: If i have A={1,2,3,4} and B={4,3,2,1} the program will return C={5,5,5,5).


问:
Insert column of data from excel into emacs dat file
I'd like to copy and paste a column of numbers from an excel spreadsheet to make another column in a data file.

That is, in my .dat file I have data like

```<code>x1  y1  z1
x2  y2  z2
x3  y3  z3
..  ..  ..
</code>```

and so on. I'd like to copy and paste a column of numbers ei from my excel spreadsheet to make another column in this dat file such that I get

```<code>x1  y1  z1  e1
x2  y2  z2  e2
x3  y3  z3  e3
..  ..  ..  ..
</code>```

Is there an easy way to do this? The existing rectangles emacs functions, as far as I can see, only allow you to generate columns with a single number input by user and not file. Thanks!

答:
Paste the column from excel into a different/temporary buffer1, and then use the rectangle commands to copy/kill that as a rectangle and yank it into the .dat file buffer.

1 or you could even do the initial paste it at the end of the .dat buffer, if that was more convenient.

Body:
I'd like to copy and paste a column of numbers from an excel spreadsheet to make another column in a data file.

That is, in my .dat file I have data like

x1  y1  z1
x2  y2  z2
x3  y3  z3
..  ..  ..

and so on. I'd like to copy and paste a column of numbers ei from my excel spreadsheet to make another column in this dat file such that I get

x1  y1  z1  e1
x2  y2  z2  e2
x3  y3  z3  e3
..  ..  ..  ..

Is there an easy way to do this? The existing rectangles emacs functions, as far as I can see, only allow you to generate columns with a single number input by user and not file. Thanks!


问:
flake8: F821 undefined name for a global variable
I've edited my script to remove all of the flake8 warnings except one:

```<code>/tmp/flake8.tempfile.py:535:26: F821 undefined name 'salt'

/tmp/flake8.tempfile.py:536:29: F821 undefined name 'salt'

/tmp/flake8.tempfile.py:554:22: F821 undefined name 'salt'

/tmp/flake8.tempfile.py:602:21: F821 undefined name 'salt'

/tmp/flake8.tempfile.py:602:32: F821 undefined name 'salt'

/tmp/flake8.tempfile.py:609:21: F821 undefined name 'salt'

/tmp/flake8.tempfile.py:609:32: F821 undefined name 'salt'

/tmp/flake8.tempfile.py:623:44: F821 undefined name 'salt'

/tmp/flake8.tempfile.py:646:39: F821 undefined name 'salt'

/tmp/flake8.tempfile.py:651:39: F821 undefined name 'salt'

/tmp/flake8.tempfile.py:654:39: F821 undefined name 'salt'

...
</code>```

salt is a hashlib ojbect that is used by many functions. It is defined in the main section of the script (at the bottom) with the line:

```<code>salt = hashlib.sha512()
</code>```

Before being updated with data. All of my other globals work fine, so I don't know why this one makes flake8 flake out.

答:
If you have a file like the

```<code># file_a.py
import hashlib

def my_func():

   ...

   if salt == ... :
      ...

if __name__ == '__main__':
    salt = hashlib.sha512()
    my_func()
</code>```

then it will run just fine when calling python file_a.py, but syntax checkers will throw warnings because there is a chance that salt might not be defined.

For example, if you create another file in the same folder like

```<code># file_b.py
from file_a import my_func()

</code>```

then you will end up with salt not being defined as the part inside the if __name__ == '__main__': does not get called because file_a.py is not the "main"-file.

if you want to define a constant, then you need to define it outside – preferable at the top of the file:

```<code># file_a.py
import hashlib

SALT = hashlib.sha512()

def my_func():

   ...

   if SALT == ... :
      ...

if __name__ == '__main__':
    my_func()
</code>```

but most likely, it would be better to avoid constants and use keyword arguments instead.

I hope this is what is happening. If I'm completely off, then I apologise, but you would need to provide more code in that case, it is very much a guessing game like that :)

Body:
I've edited my script to remove all of the flake8 warnings except one:

/tmp/flake8.tempfile.py:535:26: F821 undefined name 'salt'

/tmp/flake8.tempfile.py:536:29: F821 undefined name 'salt'

/tmp/flake8.tempfile.py:554:22: F821 undefined name 'salt'

/tmp/flake8.tempfile.py:602:21: F821 undefined name 'salt'

/tmp/flake8.tempfile.py:602:32: F821 undefined name 'salt'

/tmp/flake8.tempfile.py:609:21: F821 undefined name 'salt'

/tmp/flake8.tempfile.py:609:32: F821 undefined name 'salt'

/tmp/flake8.tempfile.py:623:44: F821 undefined name 'salt'

/tmp/flake8.tempfile.py:646:39: F821 undefined name 'salt'

/tmp/flake8.tempfile.py:651:39: F821 undefined name 'salt'

/tmp/flake8.tempfile.py:654:39: F821 undefined name 'salt'

...

salt is a hashlib ojbect that is used by many functions. It is defined in the main section of the script (at the bottom) with the line:

salt = hashlib.sha512()

Before being updated with data. All of my other globals work fine, so I don't know why this one makes flake8 flake out.

Body:
If you have a file like the

# file_a.py
import hashlib

def my_func():

   ...

   if salt == ... :
      ...

if __name__ == '__main__':
    salt = hashlib.sha512()
    my_func()

then it will run just fine when calling python file_a.py, but syntax checkers will throw warnings because there is a chance that salt might not be defined.

For example, if you create another file in the same folder like

# file_b.py
from file_a import my_func()

then you will end up with salt not being defined as the part inside the if __name__ == '__main__': does not get called because file_a.py is not the "main"-file.

if you want to define a constant, then you need to define it outside – preferable at the top of the file:

# file_a.py
import hashlib

SALT = hashlib.sha512()

def my_func():

   ...

   if SALT == ... :
      ...

if __name__ == '__main__':
    my_func()

but most likely, it would be better to avoid constants and use keyword arguments instead.

I hope this is what is happening. If I'm completely off, then I apologise, but you would need to provide more code in that case, it is very much a guessing game like that :)


问:
how do I use this OnCompleted function?
This library I found that handles music playing has the following variable public.

```<code>void Function() onCompleted;
</code>```

I want to change the icon of a button when the track is finished, so that it returns to a play icon.

I tried using musicPlayer.OnCompleted(() { **stuff** }); but that gives me a syntax error Too many positional arguments: 0 expected, but 1 found.

How do I subscribe on that event, or how do I check if OnCompleted has been called?

I am still pretty new to dart but can't wrap my head around this one. I tried subscribing like in Angular or looking up if there's a different syntax for it, but I am at a loss.

答:
Presumably you have to set onCompleted to something, specifically a function taking no parameters and returning void.

It would be normal to provide something like this in the constructor. Is there a named, optional parameter for this? Alternatively, there may be a setter.

Let's assume there's a setter. You could write:

```<code>  musicPlayer.onCompleted = (){/* do stuff*/};
</code>```

Title: how do I use this OnCompleted function?

Body:
This library I found that handles music playing has the following variable public.

void Function() onCompleted;

I want to change the icon of a button when the track is finished, so that it returns to a play icon.

I tried using musicPlayer.OnCompleted(() { **stuff** }); but that gives me a syntax error Too many positional arguments: 0 expected, but 1 found.

How do I subscribe on that event, or how do I check if OnCompleted has been called?

I am still pretty new to dart but can't wrap my head around this one. I tried subscribing like in Angular or looking up if there's a different syntax for it, but I am at a loss.

Body:
Presumably you have to set onCompleted to something, specifically a function taking no parameters and returning void.

It would be normal to provide something like this in the constructor. Is there a named, optional parameter for this? Alternatively, there may be a setter.

Let's assume there's a setter. You could write:

  musicPlayer.onCompleted = (){/* do stuff*/};


问:
How do I add files and folders into GitHub repos?
I created an account on GitHub and I'm facing a problem with adding files. I have added readme.txt. Also, I have 3 other PHP files and a folder including images.

How do I add the files and folder? I tried it with git pull because git push origin -u master showed me an error.

答: I'm using VS SSDT on Windows. I started a project and set up local version control. I later installed git and and created a Github repo. Once I had my repo on Github I grabbed the URL and put that into VS when it asked me for the URL when I hit the "publish to Github" button.</p>


问:
Filtering pandas dataframe by date to count views for timeline of programs
I need to count viewers by program for a streaming channel from a json logfile.
I identify the programs by their starttimes, such as:

So far I have two Dataframes like this:

The first one contains all the timestamps from the logfile

```<code>viewers_from_log = pd.read_json('sqllog.json', encoding='UTF-8')
# Convert date string to pandas datetime object:
viewers_from_log['time'] = pd.to_datetime(viewers_from_log['time'])
</code>```

Source JSON file:

```<code>[
    {
        "logid": 191605,
        "time": "0:00:17"
    },
    {
        "logid": 191607,
        "time": "0:00:26"
    },
    {
        "logid": 191611,
        "time": "0:01:20"
    }
]
</code>```

The second contains the starting times and titles of the programs

```<code>programs_start_time = pd.DataFrame.from_dict('programs.json', orient='index')
</code>```

Source JSON file:

```<code>{
    "2019-05-29": [
        {
            "title": "\"Amiről a kövek mesélnek\"",
            "startTime_dt": "2019-05-29T00:00:40Z"
        },
        {
            "title": "Koffer - Kedvcsináló Kul(t)túrák Külföldön",
            "startTime_dt": "2019-05-29T00:22:44Z"
        },
        {
            "title": "Gubancok",
            "startTime_dt": "2019-05-29T00:48:08Z"
        }
    ]
}
</code>```

So what I need to do is to count the entries / program in the log file and link them to the program titles.

答:
Solution with histogram, using numpy:

```<code>import pandas as pd
import numpy as np

df_p = pd.DataFrame([
        {
            "title": "\"Amiről a kövek mesélnek\"",
            "startTime_dt": "2019-05-29T00:00:40Z"
        },
        {
            "title": "Koffer - Kedvcsináló Kul(t)túrák Külföldön",
            "startTime_dt": "2019-05-29T00:22:44Z"
        },
        {
            "title": "Gubancok",
            "startTime_dt": "2019-05-29T00:48:08Z"
        }
    ])

df_v = pd.DataFrame([
    {
        "logid": 191605,
        "time": "2019-05-29 0:00:17"
    },
    {
        "logid": 191607,
        "time": "2019-05-29 0:00:26"
    },
    {
        "logid": 191611,
        "time": "2019-05-29 0:01:20"
    }
])

df_p.startTime_dt = pd.to_datetime(df_p.startTime_dt)
df_v.time = pd.to_datetime(df_v.time)

# here's part where I convert datetime to timestamp in seconds - astype(int) casts it to nanoseconds, hence there's // 10**9
programmes_start = df_p.startTime_dt.astype(int).values // 10**9
viewings_starts = df_v.time.astype(int).values // 10**9

# make bins for histogram
# add zero to the beginning of the array
# add value that is time an hour after the start of the last given programme to the end of the array
programmes_start = np.pad(programmes_start, (1, 1), mode='constant', constant_values=(0, programmes_start.max()+3600))

histogram = np.histogram(viewings_starts, bins=programmes_start)
print(histogram[0]
# prints [2 1 0 0]
</code>```

Interpretation: there were 2 log entries before 'Amiről a kövek mesélnek' started, 1 log entry between starts of 'Amiről a kövek mesélnek' and 'Koffer - Kedvcsináló Kul(t)túrák Külföldön', 0 log entries between starts of 'Koffer - Kedvcsináló Kul(t)túrák Külföldön' and 'Gubancok' and 0 entries after start od 'Gubancok'. Which, looking at the data you provided, seems correct :) Hope this helps.

NOTE: I assume, that you have the date of the viewings. You don't have them in the example log file, but they appear in the screenshot - so I assumed that you can compute/get them somehow and added them by hand to the input dict.

Body:
I need to count viewers by program for a streaming channel from a json logfile.
I identify the programs by their starttimes, such as:

So far I have two Dataframes like this:

The first one contains all the timestamps from the logfile

viewers_from_log = pd.read_json('sqllog.json', encoding='UTF-8')
# Convert date string to pandas datetime object:
viewers_from_log['time'] = pd.to_datetime(viewers_from_log['time'])

Source JSON file:

[
    {
        "logid": 191605,
        "time": "0:00:17"
    },
    {
        "logid": 191607,
        "time": "0:00:26"
    },
    {
        "logid": 191611,
        "time": "0:01:20"
    }
]

The second contains the starting times and titles of the programs

programs_start_time = pd.DataFrame.from_dict('programs.json', orient='index')

Source JSON file:

{
    "2019-05-29": [
        {
            "title": "\"Amiről a kövek mesélnek\"",
            "startTime_dt": "2019-05-29T00:00:40Z"
        },
        {
            "title": "Koffer - Kedvcsináló Kul(t)túrák Külföldön",
            "startTime_dt": "2019-05-29T00:22:44Z"
        },
        {
            "title": "Gubancok",
            "startTime_dt": "2019-05-29T00:48:08Z"
        }
    ]
}

So what I need to do is to count the entries / program in the log file and link them to the program titles.

Body:
Solution with histogram, using numpy:

import pandas as pd
import numpy as np

df_p = pd.DataFrame([
        {
            "title": "\"Amiről a kövek mesélnek\"",
            "startTime_dt": "2019-05-29T00:00:40Z"
        },
        {
            "title": "Koffer - Kedvcsináló Kul(t)túrák Külföldön",
            "startTime_dt": "2019-05-29T00:22:44Z"
        },
        {
            "title": "Gubancok",
            "startTime_dt": "2019-05-29T00:48:08Z"
        }
    ])

df_v = pd.DataFrame([
    {
        "logid": 191605,
        "time": "2019-05-29 0:00:17"
    },
    {
        "logid": 191607,
        "time": "2019-05-29 0:00:26"
    },
    {
        "logid": 191611,
        "time": "2019-05-29 0:01:20"
    }
])

df_p.startTime_dt = pd.to_datetime(df_p.startTime_dt)
df_v.time = pd.to_datetime(df_v.time)

# here's part where I convert datetime to timestamp in seconds - astype(int) casts it to nanoseconds, hence there's // 10**9
programmes_start = df_p.startTime_dt.astype(int).values // 10**9
viewings_starts = df_v.time.astype(int).values // 10**9

# make bins for histogram
# add zero to the beginning of the array
# add value that is time an hour after the start of the last given programme to the end of the array
programmes_start = np.pad(programmes_start, (1, 1), mode='constant', constant_values=(0, programmes_start.max()+3600))

histogram = np.histogram(viewings_starts, bins=programmes_start)
print(histogram[0]
# prints [2 1 0 0]

Interpretation: there were 2 log entries before 'Amiről a kövek mesélnek' started, 1 log entry between starts of 'Amiről a kövek mesélnek' and 'Koffer - Kedvcsináló Kul(t)túrák Külföldön', 0 log entries between starts of 'Koffer - Kedvcsináló Kul(t)túrák Külföldön' and 'Gubancok' and 0 entries after start od 'Gubancok'. Which, looking at the data you provided, seems correct :) Hope this helps.

NOTE: I assume, that you have the date of the viewings. You don't have them in the example log file, but they appear in the screenshot - so I assumed that you can compute/get them somehow and added them by hand to the input dict.


问:
jQuery trigger call to URL on click event
I'm trying to to trigger pregenerated URL to export CSV as follow:

```<code>// call API for CSV export
$( ".buttons-csv" ).click(function(e) {

    var csvURL = csvAPI(dlog);
    $.get( csvURL, function( data ) {
        alert( "Export was performed." );
    });
});
</code>```

problem is that will not call created csvURL URL to download a file.

I have tried to get it done via

```<code>window.location.href = csvURL
</code>```

but that wasn't work either.

答:
Downloads don't occur when you use AJAX, only when the browser opens the URL normally in a window. Use window.open() to open a new window that performs the download, while not replacing the current window.

```<code>$( ".buttons-csv" ).click(function(e) {

    var csvURL = csvAPI(dlog);
    window.open(csvURL);
});
</code>```

Body:
I'm trying to to trigger pregenerated URL to export CSV as follow:

// call API for CSV export
$( ".buttons-csv" ).click(function(e) {

    var csvURL = csvAPI(dlog);
    $.get( csvURL, function( data ) {
        alert( "Export was performed." );
    });
});

problem is that will not call created csvURL URL to download a file.

I have tried to get it done via

window.location.href = csvURL

but that wasn't work either.

Body:
Downloads don't occur when you use AJAX, only when the browser opens the URL normally in a window. Use window.open() to open a new window that performs the download, while not replacing the current window.

$( ".buttons-csv" ).click(function(e) {

    var csvURL = csvAPI(dlog);
    window.open(csvURL);
});