问:
Remove consecutive duplicates from a list using yield generator?
i'm trying to compress a list using generator:

examples

```<code>[1, 1, 1, 1, 2, 2, 2, 1, 1, 1] == [1, 2, 1]

[5, 5, 5, 4, 5, 6, 6, 5, 5, 7, 8, 0, 0])) == [5, 4, 5, 6, 5, 7, 8, 0]
</code>```

I tried to use a generator that checks if the 1st and 2nd element are equal then check 2nd and 3rd and so on until it is no longer equal "when it reaches 4" and then yield "5" then it would repeat the process starting with "4"

code

```<code>test = [5, 5, 5, 4, 5, 6, 6, 5, 5, 7, 8, 0, 0] # sample list
from typing import Iterable
def compress(items: list) -> Iterable:

    x = 0
    while items[x] == items[x + 1]:
        x += 1
    yield items[x]

ans = compress(test)
for x in ans:
    print(ans)
</code>```

but i keep getting

generator object compress at 0x00000254D383C820.
why won't it loop?

if i try and use next() it only goes up to 5 and wont check the other numbers.

any assistance is greatly appreciated.

答:
As others have explained, your structure is incorrect - you're only encountering the yield once outside the loop. The ideal way would be to iterate over pairs of consecutive numbers and yield the first one in the loop if they are different.

However, here's a canonical method via itertools.groupby which removes consecutive duplicates:

```<code>from itertools import groupby
from operator import itemgetter

list(map(itemgetter(0), groupby(l)))
# [1, 2, 1]
</code>```

Body:
i'm trying to compress a list using generator:

examples

[1, 1, 1, 1, 2, 2, 2, 1, 1, 1] == [1, 2, 1]

[5, 5, 5, 4, 5, 6, 6, 5, 5, 7, 8, 0, 0])) == [5, 4, 5, 6, 5, 7, 8, 0]

I tried to use a generator that checks if the 1st and 2nd element are equal then check 2nd and 3rd and so on until it is no longer equal "when it reaches 4" and then yield "5" then it would repeat the process starting with "4"

code

test = [5, 5, 5, 4, 5, 6, 6, 5, 5, 7, 8, 0, 0] # sample list
from typing import Iterable
def compress(items: list) -> Iterable:

    x = 0
    while items[x] == items[x + 1]:
        x += 1
    yield items[x]

ans = compress(test)
for x in ans:
    print(ans)

but i keep getting

generator object compress at 0x00000254D383C820.
why won't it loop?

if i try and use next() it only goes up to 5 and wont check the other numbers.

any assistance is greatly appreciated.

Body:
As others have explained, your structure is incorrect - you're only encountering the yield once outside the loop. The ideal way would be to iterate over pairs of consecutive numbers and yield the first one in the loop if they are different.

However, here's a canonical method via itertools.groupby which removes consecutive duplicates:

from itertools import groupby
from operator import itemgetter

list(map(itemgetter(0), groupby(l)))
# [1, 2, 1]


来源: stackexchange

问:
Can't convert to Lower/uppercase a char* pointer using a loop in C without toupper
I am trying to make a function toLowerCase(char *string) but I am unable to make it work properly.

This is my code

```<code>void toLowerCase(char *string) {
    int i = 0;
    while (*(string+i) != '\0') {
        if (*(string+i) >= 'A' && *(string+i) <= 'Z') {
            *(string+i) = *(string+i) + 32;
        }
        i++;
    }
    printf("%s", string);
}
</code>```

I am trying to loop through the string that is a char * pointer by accessing each element using *(string + i) and using ASCII to convert to Lowercase.

I am new here, if this was answered before I am sorry, but I am asking because I couldn't find a specific solution to my problem. I've tried what's in this thread: Converting Char * to Uppercase in C
but it didn't work for me either.

EDIT: This is how I call my function

```<code>int main() {
    toLowerCase("HELLO WORLD");
    return 0;
}
</code>```

EDIT 2: So, I did this, as showed by PSkocik. And it worked, but I don't know why it works like this. Will the toLowerCase() function work with any char * pointer? even if I don't declare it as char array?

This also fixes the problem that Vlad from Moscow pointed out that I am using a string literal

```<code>#define T 100
int main() {
    char string[T] = "HELLO WORLD";
    toLowerCase(&string);
    return 0;
}
</code>```

EDIT 3: Thank you very much for your help! I wasn't expecting to get help so quickly! I didn't know what a string literal was!

Thank you very much for your time

答:
You are passing a string literal to the function toLowerCase and then trying to change it using *(string+i)= *(string+i)+32;.

You should contain Hello World in a variable and then pass it to the function if you want to change the case of characters.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to make a function toLowerCase(char *string) but I am unable to make it work properly.

This is my code

void toLowerCase(char *string) {
    int i = 0;
    while (*(string+i) != '\0') {
        if (*(string+i) >= 'A' && *(string+i) <= 'Z') {
            *(string+i) = *(string+i) + 32;
        }
        i++;
    }
    printf("%s", string);
}

I am trying to loop through the string that is a char * pointer by accessing each element using *(string + i) and using ASCII to convert to Lowercase.

I am new here, if this was answered before I am sorry, but I am asking because I couldn't find a specific solution to my problem. I've tried what's in this thread: Converting Char * to Uppercase in C
but it didn't work for me either.

EDIT: This is how I call my function

int main() {
    toLowerCase("HELLO WORLD");
    return 0;
}

EDIT 2: So, I did this, as showed by PSkocik. And it worked, but I don't know why it works like this. Will the toLowerCase() function work with any char * pointer? even if I don't declare it as char array?

This also fixes the problem that Vlad from Moscow pointed out that I am using a string literal

#define T 100
int main() {
    char string[T] = "HELLO WORLD";
    toLowerCase(&string);
    return 0;
}

EDIT 3: Thank you very much for your help! I wasn't expecting to get help so quickly! I didn't know what a string literal was!

Thank you very much for your time


问:
Problems with reading and writing to text files in python
I am trying to take an input and write the input to a text file to keep it stored. However, I can't seem to get the user input written over to the text file. Here is my code:

```<code>SaveUsername = open(r"C:\Users\Ty\Desktop\Login_sys\SaveUsername.txt","w+")
SavePassword = open(r"C:\Users\Ty\Desktop\Login_sys\SavePassword.txt","w+")
NewUsername = input("Please enter a username: ")
NewPassword = input("Please enter a password: ")
SaveUsername.write(NewUsername)
print (SaveUsername.readline())
SavePassword.write(NewPassword)
print (SavePassword.readline())
</code>```

I am printing the readline to see if the code gets written and it never does.  Please help, thanks.

答:
First of all, you should close the file after you write to it before reading the changes. You should also use with open(...) as it is a better practice (for multiple reasons).
Here is the code you should use:

```<code>
with open(r"C:\Users\Ty\Desktop\Login_sys\SaveUsername.txt", "w") as SaveUsername:
    NewUsername = input("Please enter a username: ")
    SaveUsername.write(NewUsername)

with open(r"C:\Users\Ty\Desktop\Login_sys\SavePassword.txt", "w") as SavePassword:
    NewPassword = input("Please enter a password: ")
    SavePassword.write(NewPassword)

with open(r"C:\Users\Ty\Desktop\Login_sys\SaveUsername.txt", "r") as SaveUsername:
    print(SavePassword.readline())

with open(r"C:\Users\Ty\Desktop\Login_sys\SavePassword.txt", "r") as SavePassword:
    print(SavePassword.readline())
</code>```

Body:
I am trying to take an input and write the input to a text file to keep it stored. However, I can't seem to get the user input written over to the text file. Here is my code:

SaveUsername = open(r"C:\Users\Ty\Desktop\Login_sys\SaveUsername.txt","w+")
SavePassword = open(r"C:\Users\Ty\Desktop\Login_sys\SavePassword.txt","w+")
NewUsername = input("Please enter a username: ")
NewPassword = input("Please enter a password: ")
SaveUsername.write(NewUsername)
print (SaveUsername.readline())
SavePassword.write(NewPassword)
print (SavePassword.readline())

I am printing the readline to see if the code gets written and it never does.  Please help, thanks.

Body:
First of all, you should close the file after you write to it before reading the changes. You should also use with open(...) as it is a better practice (for multiple reasons).
Here is the code you should use:

with open(r"C:\Users\Ty\Desktop\Login_sys\SaveUsername.txt", "w") as SaveUsername:
    NewUsername = input("Please enter a username: ")
    SaveUsername.write(NewUsername)

with open(r"C:\Users\Ty\Desktop\Login_sys\SavePassword.txt", "w") as SavePassword:
    NewPassword = input("Please enter a password: ")
    SavePassword.write(NewPassword)

with open(r"C:\Users\Ty\Desktop\Login_sys\SaveUsername.txt", "r") as SaveUsername:
    print(SavePassword.readline())

with open(r"C:\Users\Ty\Desktop\Login_sys\SavePassword.txt", "r") as SavePassword:
    print(SavePassword.readline())


答:
If you're looking for the same effect as that, look into the itertools.groupby function. It's smarter to use built-in tools.

If you're interested in learning generators, write it. You didn't make any mistakes outside of having "yield" at the wrong level, but you wrote un-Pythonic code. Keeping track of x and x+1 and keeping the whole thing in memory are all bad.

```<code>class NeverInList: pass

from typing import Iterable
def compress(items: list) -> Iterable:
    previous = NeverInList()  # Something never in a list, duh.
    for item in items:
        if item != previous:
            yield item
            previous = item

ans = compress(test)
for x in ans:
    print(x)   # "x", not "ans"
</code>```

Title: Remove consecutive duplicates from a list using yield generator?

Body:
If you're looking for the same effect as that, look into the itertools.groupby function. It's smarter to use built-in tools.

If you're interested in learning generators, write it. You didn't make any mistakes outside of having "yield" at the wrong level, but you wrote un-Pythonic code. Keeping track of x and x+1 and keeping the whole thing in memory are all bad.

class NeverInList: pass

from typing import Iterable
def compress(items: list) -> Iterable:
    previous = NeverInList()  # Something never in a list, duh.
    for item in items:
        if item != previous:
            yield item
            previous = item

ans = compress(test)
for x in ans:
    print(x)   # "x", not "ans"


答:
You may not change string literals. Any attempt to change a string literal results in undefined behavior.

From the C Standard (6.4.5 String literals)

7 It is unspecified whether these arrays are distinct provided their
  elements have the appropriate values. If the program attempts to
  modify such an array, the behavior is undefined.

So instead of this call

```<code>toLowerCase("HELLO WORLD");
</code>```

use at least

```<code>char s[] = "HELLO WORLD";

toLowerCase( s );
</code>```

Pay attention to that it will be much better when the function will return pointer to the modified string and will not output the string. It is the caller of the function that will decide whether to output the modified string.

So define the function like

```<code>char * toLowerCase( char *string )
{
    // ...
    return string;
}
</code>```

Title: Can't convert to Lower/uppercase a char* pointer using a loop in C without toupper

Body:
You may not change string literals. Any attempt to change a string literal results in undefined behavior.

From the C Standard (6.4.5 String literals)

7 It is unspecified whether these arrays are distinct provided their
  elements have the appropriate values. If the program attempts to
  modify such an array, the behavior is undefined.

So instead of this call

toLowerCase("HELLO WORLD");

use at least

char s[] = "HELLO WORLD";

toLowerCase( s );

Pay attention to that it will be much better when the function will return pointer to the modified string and will not output the string. It is the caller of the function that will decide whether to output the modified string.

So define the function like

char * toLowerCase( char *string )
{
    // ...
    return string;
}


问:
css border radius bug in chrome with percentages
Hi I'm having troubles with a problem in chrome. I think it might be a bug but I can't find much info on it. Basically I want to apply border radius on an image. The border-radius will be 50% forming a circle. The reason I've set it as a % is because i wont explicity know the width/hieghtt of the image.

Any ideas why chrome doesn't display the border correclty? I haven't tested in FF < 4. but FF4 works well as does IE for a change

答: I figured out a way around it, by adding the border and the border-radius onto the parent . I then applied the border radius to the image too. Although there is a minute gap It works in chrome now. I haven't tested it in FF3.6. But FF4 displays the same result</p>

ContentLicense: CC BY-SA 3.0


问:
Change order of multiple optional substrings
That's a bit like this question, but I have multiple substrings that may or may not occur.

The substrings code for two different dimensions, in my example "test" and "eye". They can occur in any imaginable order.
The variables can be coded in different ways - in my example, "method|test" would be two ways to code for "test", as well as "r|re|l|le" different ways to code for eyes.

I found a convoluted solution, which is using a chain of seven (!) gsub calls, and I wondered if there is a more concise way.

x <- c("id", "r_test", "l_method", "test_re", "method_le", "test_r_old",
       "test_l_old", "re_test_new","new_le_method", "new_r_test")
x
#>  [1] "id"            "r_test"        "l_method"      "test_re"
#>  [5] "method_le"     "test_r_old"    "test_l_old"    "re_test_new"
#>  [9] "new_le_method" "new_r_test"
```

<p>Desired output</p>

```#>  [1] "id"         "r_test"     "l_test"     "r_test"     "l_test"
#>  [6] "r_test_old" "l_test_old" "r_test_new" "l_test_new" "r_test_new"
```

<p>How I got there (convoluted)</p>

```## Unify codes for variables, I use the underscores to make it more unique for future regex
clean_test<- gsub("(?<![a-z])(test|method)(?![a-z])", "_test_", tolower(x), perl = TRUE)
clean_r <- gsub("(?<![a-z])(r|re)(?![a-z])", "_r_", tolower(clean_test), perl = TRUE)
clean_l <- gsub("(?<![a-z])(l|le)(?![a-z])", "_l_", tolower(clean_r), perl = TRUE)

## Now sort, one after the other
sort_eye <- gsub("(.*)(_r_|_l_)(.*)", "\\2\\1\\3", clean_l, perl = TRUE)
sort_test <- gsub("(_r_|_l_)(.*)(_test_)(.*)", "\\1\\3\\2\\4", sort_eye, perl = TRUE)

## Remove underscores
clean_underscore_mult <- gsub("_{2,}", "_", sort_test)
clean_underscore_ends <- gsub("^_|_$", "", clean_underscore_mult)

clean_underscore_ends
#>  [1] "id"         "r_test"     "l_test"     "r_test"     "l_test"
#>  [6] "r_test_old" "l_test_old" "r_test_new" "l_test_new" "r_test_new"
```

I'd be already very very grateful for a suggestion how to better proceed from ## Now sort, one after the other downwards...

答:
Much inspired and building on user MichaelChirico's answer, this is a function using base R only, which (in theory) should work with any number of substrings to sort. The list defines the sort (by its elements), and it specifies all ways to code for the default tokens (the list names).

## I've added some more ways to code for right and left eyes, as well as different further strings that are not known.

x <- c("id", "r_random_test_old", "r_test", "r_test_else", "l_method", "test_re", "method_le", "test_od_old",
       "test_os_old", "re_mth_new","new_le_method", "new_r_test_random")
x
#>  [1] "id"                "r_random_test_old" "r_test"
#>  [4] "r_test_else"       "l_method"          "test_re"
#>  [7] "method_le"         "test_od_old"       "test_os_old"
#> [10] "re_mth_new"        "new_le_method"     "new_r_test_random"

sort_substr(x, list(r = c("od","re"), l = c("os","le"), test = c("method", "mth"), time = c("old","new")))
#>  [1] "id"                 "r_test_time_random" "r_test"
#>  [4] "r_test_else"        "l_test"             "r_test"
#>  [7] "l_test"             "r_test_time"        "l_test_time"
#> [10] "r_test_time"        "l_test_time"        "r_test_time_random"

```

<p>sort_substr</p>

```sort_substr <- function(x, list_substr) {
  lookups <- data.frame(match = rep(names(list_substr), lengths(list_substr)),
                        token = unlist(list_substr))
  l <- strsplit(x, "_", fixed = TRUE)
  DF <- data.frame(id = rep(seq_along(l), lengths(l)), token = unlist(l))
  match_token <- lookups$match[match(DF$token, lookups$token)]
  DF$match <- ifelse(is.na(match_token), DF$token, match_token)
  rest_token <- base::setdiff(DF$match, names(list_substr))
  DF$match <- factor(DF$match, levels = c(names(list_substr), rest_token))
  DF <- DF[with(DF, order(id, match)), ]
  out <- vapply(split(DF$match, DF$id),
         paste, collapse = "_",
         FUN.VALUE = character(1),
         USE.NAMES = FALSE)
  out
}
```

Body:
That's a bit like this question, but I have multiple substrings that may or may not occur.

The substrings code for two different dimensions, in my example "test" and "eye". They can occur in any imaginable order.
The variables can be coded in different ways - in my example, "method|test" would be two ways to code for "test", as well as "r|re|l|le" different ways to code for eyes.

I found a convoluted solution, which is using a chain of seven (!) gsub calls, and I wondered if there is a more concise way.

x <- c("id", "r_test", "l_method", "test_re", "method_le", "test_r_old",
       "test_l_old", "re_test_new","new_le_method", "new_r_test")
x
#>  [1] "id"            "r_test"        "l_method"      "test_re"
#>  [5] "method_le"     "test_r_old"    "test_l_old"    "re_test_new"
#>  [9] "new_le_method" "new_r_test"

Desired output

#>  [1] "id"         "r_test"     "l_test"     "r_test"     "l_test"
#>  [6] "r_test_old" "l_test_old" "r_test_new" "l_test_new" "r_test_new"

How I got there (convoluted)

## Unify codes for variables, I use the underscores to make it more unique for future regex
clean_test<- gsub("(?<![a-z])(test|method)(?![a-z])", "_test_", tolower(x), perl = TRUE)
clean_r <- gsub("(?<![a-z])(r|re)(?![a-z])", "_r_", tolower(clean_test), perl = TRUE)
clean_l <- gsub("(?<![a-z])(l|le)(?![a-z])", "_l_", tolower(clean_r), perl = TRUE)

## Now sort, one after the other
sort_eye <- gsub("(.*)(_r_|_l_)(.*)", "\\2\\1\\3", clean_l, perl = TRUE)
sort_test <- gsub("(_r_|_l_)(.*)(_test_)(.*)", "\\1\\3\\2\\4", sort_eye, perl = TRUE)

## Remove underscores
clean_underscore_mult <- gsub("_{2,}", "_", sort_test)
clean_underscore_ends <- gsub("^_|_$", "", clean_underscore_mult)

clean_underscore_ends
#>  [1] "id"         "r_test"     "l_test"     "r_test"     "l_test"
#>  [6] "r_test_old" "l_test_old" "r_test_new" "l_test_new" "r_test_new"

I'd be already very very grateful for a suggestion how to better proceed from ## Now sort, one after the other downwards...

Body:
Much inspired and building on user MichaelChirico's answer, this is a function using base R only, which (in theory) should work with any number of substrings to sort. The list defines the sort (by its elements), and it specifies all ways to code for the default tokens (the list names).

## I've added some more ways to code for right and left eyes, as well as different further strings that are not known.

x <- c("id", "r_random_test_old", "r_test", "r_test_else", "l_method", "test_re", "method_le", "test_od_old",
       "test_os_old", "re_mth_new","new_le_method", "new_r_test_random")
x
#>  [1] "id"                "r_random_test_old" "r_test"
#>  [4] "r_test_else"       "l_method"          "test_re"
#>  [7] "method_le"         "test_od_old"       "test_os_old"
#> [10] "re_mth_new"        "new_le_method"     "new_r_test_random"

sort_substr(x, list(r = c("od","re"), l = c("os","le"), test = c("method", "mth"), time = c("old","new")))
#>  [1] "id"                 "r_test_time_random" "r_test"
#>  [4] "r_test_else"        "l_test"             "r_test"
#>  [7] "l_test"             "r_test_time"        "l_test_time"
#> [10] "r_test_time"        "l_test_time"        "r_test_time_random"

sort_substr

sort_substr <- function(x, list_substr) {
  lookups <- data.frame(match = rep(names(list_substr), lengths(list_substr)),
                        token = unlist(list_substr))
  l <- strsplit(x, "_", fixed = TRUE)
  DF <- data.frame(id = rep(seq_along(l), lengths(l)), token = unlist(l))
  match_token <- lookups$match[match(DF$token, lookups$token)]
  DF$match <- ifelse(is.na(match_token), DF$token, match_token)
  rest_token <- base::setdiff(DF$match, names(list_substr))
  DF$match <- factor(DF$match, levels = c(names(list_substr), rest_token))
  DF <- DF[with(DF, order(id, match)), ]
  out <- vapply(split(DF$match, DF$id),
         paste, collapse = "_",
         FUN.VALUE = character(1),
         USE.NAMES = FALSE)
  out
}


问:
ionic Failed to load webpage with error: Could not connect to the server
I'm having an issue with Ionic projects after updating to Xcode 6 and iOS 8.

When trying to run projects I get the following error in Xcode:

```<code>Failed to load webpage with error: Could not connect to the server.
</code>```

The full log is:

```<code>2014-10-11 14:08:29.468 test[23293:109668] Apache Cordova native platform version 3.6.3 is starting.
2014-10-11 14:08:29.469 test[23293:109668] Multi-tasking -> Device: YES, App: YES
2014-10-11 14:08:29.495 test[23293:109668] Unlimited access to network resources
2014-10-11 14:08:29.866 test[23293:109668] [CDVTimer][keyboard] 0.079989ms
2014-10-11 14:08:29.866 test[23293:109668] [CDVTimer][TotalPluginStartup] 0.284970ms
2014-10-11 14:08:30.721 test[23293:109668] Resetting plugins due to page load.
2014-10-11 14:08:30.764 test[23293:109668] Failed to load webpage with error: Could not connect to the server.
</code>```

Even when trying to update Ionic and Cordova and starting a new project this error keeps popping up.

I couldn't find any threads with this particular error and I'm not sure if this is an iOS 8 compatibility issue or something is messed up with my setup.

Thanks!

EDIT:

A bit more info on what's in the index.html and app.js

index.html:

```<code><!DOCTYPE html>
<html ng-app="app" ng-controller="AppCtrl">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">

    <!-- compiled CSS -->
    <link rel="stylesheet" type="text/css" href="assets/app-0.0.1.css" />

    <!-- compiled JavaScript -->
    <script type="text/javascript" src="src/app/app.js"></script>

    <!-- cordova script (this will be a 404 during development) -->
    <script src="cordova.js"></script>
  </head>
  <body >
    <ion-nav-view></ion-nav-view>

    <!-- Load deferred scripts -->

    <!-- Google Maps -->
    <script src='http://maps.googleapis.com/maps/api/js?sensor=true&callback=googleMapsLoaded' defer async></script>
  </body>
</html>
</code>```

and app.js (before compilation with the rest of the files using ngbp):

```<code>angular.module( 'app', [
  'ionic',

  // Common requirements
  'templates-app',
  'templates-common',

  // Common Components
  'app.auth',

  // All page modules
  'app.businesses',
  'app.business',
  'app.search',
  'app.branch',
  'app.profile',
  'app.feed',

  // Other dependencies
  'ui.router'
])

.config(['$stateProvider', '$urlRouterProvider', function myAppConfig ($stateProvider, $urlRouterProvider) {
  $stateProvider
  .state('app', {
    url: "/app",
    abstract: true,
    templateUrl: "menu/menu.tpl.html",
    controller: 'AppCtrl'
  });

  $urlRouterProvider.otherwise( 'app/feed' );
}])

.run(['$ionicPlatform', 'appAuthService', '$sessionStorage', function($ionicPlatform, appAuthService, $sessionStorage) {
  // Initialize ionic styles
  $ionicPlatform.ready(function() {
    if(window.StatusBar) {
      // org.apache.cordova.statusbar required
      StatusBar.styleDefault();
      StatusBar.styleLightContent();
    }
  });

  // Initialize app authentication service
  appAuthService.init();

  // Initialize a session cache validation object
  $sessionStorage.updated = {};
}])

.controller( 'AppCtrl', ['$scope', '$location', function AppCtrl ($scope, $location) {

}])

;
</code>```

答:
I had the same issue, reinstalling the cordova-plugin-ionic-webview worked for me.

```<code>cordova plugin rm cordova-plugin-ionic-webview
cordova plugin add cordova-plugin-ionic-webview
</code>```

Body:
I'm having an issue with Ionic projects after updating to Xcode 6 and iOS 8.

When trying to run projects I get the following error in Xcode:

Failed to load webpage with error: Could not connect to the server.

The full log is:

2014-10-11 14:08:29.468 test[23293:109668] Apache Cordova native platform version 3.6.3 is starting.
2014-10-11 14:08:29.469 test[23293:109668] Multi-tasking -> Device: YES, App: YES
2014-10-11 14:08:29.495 test[23293:109668] Unlimited access to network resources
2014-10-11 14:08:29.866 test[23293:109668] [CDVTimer][keyboard] 0.079989ms
2014-10-11 14:08:29.866 test[23293:109668] [CDVTimer][TotalPluginStartup] 0.284970ms
2014-10-11 14:08:30.721 test[23293:109668] Resetting plugins due to page load.
2014-10-11 14:08:30.764 test[23293:109668] Failed to load webpage with error: Could not connect to the server.

Even when trying to update Ionic and Cordova and starting a new project this error keeps popping up.

I couldn't find any threads with this particular error and I'm not sure if this is an iOS 8 compatibility issue or something is messed up with my setup.

Thanks!

EDIT:

A bit more info on what's in the index.html and app.js

index.html:

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">

    <link rel="stylesheet" type="text/css" href="assets/app-0.0.1.css" />

    <ion-nav-view></ion-nav-view>

and app.js (before compilation with the rest of the files using ngbp):

angular.module( 'app', [
  'ionic',

  // Common requirements
  'templates-app',
  'templates-common',

  // Common Components
  'app.auth',

  // All page modules
  'app.businesses',
  'app.business',
  'app.search',
  'app.branch',
  'app.profile',
  'app.feed',

  // Other dependencies
  'ui.router'
])

.config(['$stateProvider', '$urlRouterProvider', function myAppConfig ($stateProvider, $urlRouterProvider) {
  $stateProvider
  .state('app', {
    url: "/app",
    abstract: true,
    templateUrl: "menu/menu.tpl.html",
    controller: 'AppCtrl'
  });

  $urlRouterProvider.otherwise( 'app/feed' );
}])

.run(['$ionicPlatform', 'appAuthService', '$sessionStorage', function($ionicPlatform, appAuthService, $sessionStorage) {
  // Initialize ionic styles
  $ionicPlatform.ready(function() {
    if(window.StatusBar) {
      // org.apache.cordova.statusbar required
      StatusBar.styleDefault();
      StatusBar.styleLightContent();
    }
  });

  // Initialize app authentication service
  appAuthService.init();

  // Initialize a session cache validation object
  $sessionStorage.updated = {};
}])

.controller( 'AppCtrl', ['$scope', '$location', function AppCtrl ($scope, $location) {

}])

;

Body:
I had the same issue, reinstalling the cordova-plugin-ionic-webview worked for me.

cordova plugin rm cordova-plugin-ionic-webview
cordova plugin add cordova-plugin-ionic-webview


问:
Can ffmpeg transcode an audio track and add it as a second audio track at the same time, or if not, how to do it as separate commands?
A bit of history. I am using Plex as my media server, but for reasons unknown, it has issues transcoding the DTS-HD MA 7.1 audio to EAC3 stereo and keeps buffering (the server has plenty of horsepower on all fronts, CPU/RAM/drive space & speed, gigabit networks connections for all devices. The playback device (TCL Roku TV, with a 3rd party soundbar connected via HDMI ARC) doesn't support the built-in 7.1 audio, so I get silence if I play it back directly by putting the file on a USB stick.

Also, I am by no means a ffmpeg guru, I figured out what I do know by Google University and asking questions, so please be kind and forgive me if I ask follow-up questions that may seem n00b-ish, and please provide example commands (preferably in the context of my command below so that I can have a known point of reference to start with).

I have a movie with 4K (HEVC Main 10 HDR) video and DTS-HD MA 7.1 audio that I am looking to leave the video and audio untouched, but to add a 2nd audio track in either EAC3 or if necessary, just AC3 in stereo

So what I am looking for is as follows:

video.mkv

Existing->4k video file (no change)

Existing->7.1 audio (no change)

Convert and add->stereo audio as a 2nd audio track to the output.mkv file

Below is the command I've historically used with ffmpeg to convert and replace the audio file with the stereo audio, but since I'd prefer to leave the 7.1 audio in place, this doesn't work:
ffmpeg -i "D:\video.mkv" -c:v copy -c:a aac -b:a 128k "D:\output.mkv"

And if this cannot be done as a single command, please also let me know what steps I do need to take to be able to do it.

Thanks in advace,
Mike

答:
```<code>ffmpeg -i input.mkv -map 0 -map 0:a -c copy -c:a:1 eac3 output.mkv
</code>```

-map 0 select all streams.

-map 0:a select all audio streams. This combines with -map 0 so now you have 1 video and 2 audio streams selected.

-c copy stream copy all streams.

-c:a:1 eac3 encode output audio stream #1 with eac3 encoder. This overrides -c copy for this particular stream.

Body:
ffmpeg -i input.mkv -map 0 -map 0:a -c copy -c:a:1 eac3 output.mkv

-map 0 select all streams.

-map 0:a select all audio streams. This combines with -map 0 so now you have 1 video and 2 audio streams selected.

-c copy stream copy all streams.

-c:a:1 eac3 encode output audio stream #1 with eac3 encoder. This overrides -c copy for this particular stream.


答:
So there are several flaws, all of them described as comments to the question post.

there is a loop missing that would yield more than one value

you print ans and not x, which logically is the generator object.

Is this code working for you?

```<code>test = [5, 5, 5, 4, 5, 6, 6, 5, 5, 7, 8, 0, 0]

def compress(items):
    for i, d in enumerate(items[:-1]):
        if d == items[i+1]:
            continue
        yield d
    yield items[-1]

for x in compress(test):
    print(x)
</code>```

Body:
So there are several flaws, all of them described as comments to the question post.

there is a loop missing that would yield more than one value

you print ans and not x, which logically is the generator object.

Is this code working for you?

test = [5, 5, 5, 4, 5, 6, 6, 5, 5, 7, 8, 0, 0]

def compress(items):
    for i, d in enumerate(items[:-1]):
        if d == items[i+1]:
            continue
        yield d
    yield items[-1]

for x in compress(test):
    print(x)


问:
Oracle SQL lead lag across different group
Suppose I have the below table. They key is just concat P1, P2, P3. I want to compare between key for each day. for example, from day 1 to day2, abc is removed and abe, aby is added.

```<code>P1  P2  P3  DAY KEY

a   b   c   1   abc
a   b   e   2   abe
a   b   y   2   aby
a   b   x   3   abx
a   b   c   3   abc
</code>```

Expected result set:

```<code>KEY OPERATION DAY

abc  ADD      1
abe  ADD      2
aby  ADD      2
abc  REMOVE   2
abx  ADD      3
abc  ADD      3
abe  REMOVE   3
aby  REMOVE   3
</code>```

And what if the day is not sequential. For example:

```<code>P1  P2  P3  DAY  KEY

a   b   c   1    abc
a   b   e   2    abe
a   b   y   2    aby
a   b   x   5    abx
a   b   c   5    abc
</code>```

And the expected result is:

```<code>KEY OPERATION DAY

abc  ADD      1
abe  ADD      2
aby  ADD      2
abc  REMOVE   2
abx  ADD      5
abc  ADD      5
abe  REMOVE   5
aby  REMOVE   5
</code>```

答:
You can do this without window functions, if you want:</p>

```<code>select key, 'add', day
from t
where not exists (select 1
                  from t t2
                  where t2.key = t.key and t2.day = t.day - 1
                 )
union all
select key, 'remove', day + 1
from t
where not exists (select 1
                  from t t2
                  where t2.key = t.key and t2.day = t.day + 1
                 )
</code>```

Body:
Suppose I have the below table. They key is just concat P1, P2, P3. I want to compare between key for each day. for example, from day 1 to day2, abc is removed and abe, aby is added.

P1  P2  P3  DAY KEY

a   b   c   1   abc
a   b   e   2   abe
a   b   y   2   aby
a   b   x   3   abx
a   b   c   3   abc

Expected result set:

KEY OPERATION DAY

abc  ADD      1
abe  ADD      2
aby  ADD      2
abc  REMOVE   2
abx  ADD      3
abc  ADD      3
abe  REMOVE   3
aby  REMOVE   3

And what if the day is not sequential. For example:

P1  P2  P3  DAY  KEY

a   b   c   1    abc
a   b   e   2    abe
a   b   y   2    aby
a   b   x   5    abx
a   b   c   5    abc

And the expected result is:

KEY OPERATION DAY

abc  ADD      1
abe  ADD      2
aby  ADD      2
abc  REMOVE   2
abx  ADD      5
abc  ADD      5
abe  REMOVE   5
aby  REMOVE   5

Body:
You can do this without window functions, if you want:

select key, 'add', day
from t
where not exists (select 1
                  from t t2
                  where t2.key = t.key and t2.day = t.day - 1
                 )
union all
select key, 'remove', day + 1
from t
where not exists (select 1
                  from t t2
                  where t2.key = t.key and t2.day = t.day + 1
                 )


问:
would it be possible to make a system that gives a role if they type in a certain channel using discord.py
Right so im trying to make a bot for a roleplay server and i want it so that when someone with the "No oc" role makes a character in character-subbmisons it gives them the "Waiting for approval" role is this possible?</p>

答:
You can use the on_message event:

@client.event
async def on_message(message):

    if message.content == 'Give Me The Role With ID 123456789': # text goes there
        role = message.guild.get_role(123456789) # role ID goes there
        await message.author.add_roles(role, reason='Bot Role')

```


问:
How to create two functions with the same name and different return type and runned based on boolean parameter
I have two functions with the same name but different return types. I want to run the function based on their third parameter. If the third parameter is true I want to run the first and If the parameter is false to run the second function. I was trying different things on my own because I couldn't find information online and I wasn't sure how is this called. Here is what I tried to do:

```<code>static int function(int a, int b, const bool=true);
static std::string function(int a, int b, const bool=false);
</code>```

I would be grateful if someone can explain how to do this or at least give me a link to some information.

答:
You can create a function template and add specializations for the different return types. Then you could use the bool argument as a template parameter:

```<code>template<bool>
auto function(int, int);

template<>
auto function<true>(int a, int b)
{
    // ...
    return int{};
}

template<>
auto function<false>(int a, int b)
{
    // ...
    return std::string{};
}
</code>```

The functions would then be called like this:

```<code>int a = function<true>(1,2);
std::string b = function<false>(1,2);
</code>```

Here's a demo.

Note the important caveat that the bool parameter must be known at compile time, and can't be a run time argument.

While this technique will work, do be aware that this will confuse a lot of c++ programmers. They usually expect a function to always return a particular type.

More relevant to your question; this is not actually going to make the code much more readable. Instead, having separate named functions is probably a more readable approach:

```<code>int int_function(int a, int b);
std::string str_function(int a, int b);
</code>```

which could be called like this:

```<code>int a = int_function(1,2);
std::string b = str_function(1,2);
</code>```

Body:
I have two functions with the same name but different return types. I want to run the function based on their third parameter. If the third parameter is true I want to run the first and If the parameter is false to run the second function. I was trying different things on my own because I couldn't find information online and I wasn't sure how is this called. Here is what I tried to do:

static int function(int a, int b, const bool=true);
static std::string function(int a, int b, const bool=false);

I would be grateful if someone can explain how to do this or at least give me a link to some information.

Body:
You can create a function template and add specializations for the different return types. Then you could use the bool argument as a template parameter:

template<bool>
auto function(int, int);

template<>
auto function<true>(int a, int b)
{
    // ...
    return int{};
}

template<>
auto function<false>(int a, int b)
{
    // ...
    return std::string{};
}

The functions would then be called like this:

int a = function<true>(1,2);
std::string b = function<false>(1,2);

Here's a demo.

Note the important caveat that the bool parameter must be known at compile time, and can't be a run time argument.

While this technique will work, do be aware that this will confuse a lot of c++ programmers. They usually expect a function to always return a particular type.

More relevant to your question; this is not actually going to make the code much more readable. Instead, having separate named functions is probably a more readable approach:

int int_function(int a, int b);
std::string str_function(int a, int b);

which could be called like this:

int a = int_function(1,2);
std::string b = str_function(1,2);


问:
Use a "case when in" expression where the list values are in a single field?
I'm using SQL Server and would like to check if todays day name is in a list of values in a single field/column.

An example of the column "start_days" contents is:

```<code>'Monday','Tuesday','Sunday'
'Thursday'
'Friday','Sunday'
'Tuesday','Sunday'
'Tuesday','Wednesday','Thursday','Friday'
</code>```

The code I am trying to run on this is:

```<code>case
  when datename(weekday,getdate()) in (start_days) then 1
  else 0
end as today_flag
</code>```

And the result is 0 for every row.
Am I doing something wrong here or is it just not possible to use a single field as a list of values in the statement?

答:
The right answer to the question is fixing your data modal. Storing multiple values like that will leads you to many issue and you're stuck on one right now.

Until that, you could use LIKE operaor to get the desired results as:

```<code>SELECT *, CASE WHEN
                 Value LIKE CONCAT('%', QUOTENAME(DATENAME(WEEKDAY,GETDATE()), ''''), '%')
               THEN 1
               ELSE 0
          END
FROM
(
  VALUES
  ('''Monday'',''Tuesday'',''Sunday'''),
  ('''Thursday'''),
  ('''Friday'',''Sunday'''),
  ('''Tuesday'',''Sunday'''),
  ('''Tuesday'',''Wednesday'',''Thursday'',''Friday''')
) T(Value)
</code>```

Here is a db<>fiddle where you can see how it's working online.

Body:
I'm using SQL Server and would like to check if todays day name is in a list of values in a single field/column.

An example of the column "start_days" contents is:

'Monday','Tuesday','Sunday'
'Thursday'
'Friday','Sunday'
'Tuesday','Sunday'
'Tuesday','Wednesday','Thursday','Friday'

The code I am trying to run on this is:

case
  when datename(weekday,getdate()) in (start_days) then 1
  else 0
end as today_flag

And the result is 0 for every row.
Am I doing something wrong here or is it just not possible to use a single field as a list of values in the statement?

Body:
The right answer to the question is fixing your data modal. Storing multiple values like that will leads you to many issue and you're stuck on one right now.

Until that, you could use LIKE operaor to get the desired results as:

SELECT *, CASE WHEN
                 Value LIKE CONCAT('%', QUOTENAME(DATENAME(WEEKDAY,GETDATE()), ''''), '%')
               THEN 1
               ELSE 0
          END
FROM
(
  VALUES
  ('''Monday'',''Tuesday'',''Sunday'''),
  ('''Thursday'''),
  ('''Friday'',''Sunday'''),
  ('''Tuesday'',''Sunday'''),
  ('''Tuesday'',''Wednesday'',''Thursday'',''Friday''')
) T(Value)

Here is a db<>fiddle where you can see how it's working online.


问:
During heavy javascript function css animation stops if I use translateX(100%)

Steps

Go on REPL: https://codesandbox.io/s/css-sidebar-animation-100-transform-wxchf?file=/App.svelte

click on "Toggle Sidebar" button

the animation is smooth, smoothly

uncomment line 28

comment line 29

click again on button

the animation stops when heavy() function is called (in toggleSidebar() function)

Questions

I don't understand why this happens?

If I change -200px to -100% what is going on that causes the animation to stop?

How can I fix the problem? What if I don’t know the sidebar width in advance? What if it is dynamic?

Code

.sidebar {
  animation: sidebar-slide-right 3s ease-out;
}

@keyframes sidebar-slide-right {
  0% {
    /* transform: translateX(-100%); */
    transform: translateX(-200px);
  }
  100% {
    transform: translateX(0);
  }
}
```

答:
I've spend some time testing your repl with performance time in web browser dev tools. My conclusions are:

In modern web browser we have

The Main thread

The Compositor thread

The second one is really nice because helps the main thread by taking some responsibilities on itself.

Typically, the main thread is responsible for:

Running your JavaScript.

Calculating your HTML elements’ CSS styles.

Laying out your page. Painting your elements into one or more bitmaps.

Handing these bitmaps over to the compositor thread.

Typically, the compositor thread is responsible for:

Drawing bitmaps to the screen via the GPU.

Asking the main thread to update bitmaps for visible or soon-to-be-visible parts of the page.

Figuring out which parts of the page are visible. Figuring out which
parts are soon-to-be-visible when you’re scrolling.

Moving parts of the page when you scroll.

Source: http://sking7.github.io/articles/572118798.html

CSS-based animations, and Web Animations where supported natively, are
typically handled on a thread known as the "compositor thread". This
is different from the browser's "main thread", where styling, layout,
painting, and JavaScript are executed. This means that if the browser
is running some expensive tasks on the main thread, these animations
can keep going without being interrupted.

Other changes to transforms and opacity can, in many cases, also be
handled by the compositor thread.

If any animation triggers paint, layout, or both, the "main thread"
will be required to do work. This is true for both CSS- and
JavaScript-based animations, and the overhead of layout or paint will
likely dwarf any work associated with CSS or JavaScript execution,
rendering the question moot.

Source: https://developers.google.com/web/fundamentals/design-and-ux/animations/animations-and-performance

So compositor is pretty nice when we have to deal with animations. Using px as measure unit is easy and can be done by the compositor thread but using % makes our browser to calculate every "step" of our animation so the main thread has to help us with it. By using await you block the main thread so your browser waits to get recalculated position. When you use absolute unit the compositor thread executes the animation so even if you block the main thread, your animation is running smoothly.

Replace your code with

```<code>  async function toggleSidebar() {
    sidebarVisible = !sidebarVisible;
    console.log("1");
    await sleep(800);
    console.log("2");
    heavy(40);
  }
</code>```

You can notice using % causes:

Animation runs

console.log 1

animation stops

console.log 2

animation runs

Using px:

console.log 1

Animation still runs

console.log 2

animation ends

Body:
I've spend some time testing your repl with performance time in web browser dev tools. My conclusions are:

In modern web browser we have

The Main thread

The Compositor thread

The second one is really nice because helps the main thread by taking some responsibilities on itself.

Typically, the main thread is responsible for:

Running your JavaScript.

Calculating your HTML elements’ CSS styles.

Laying out your page. Painting your elements into one or more bitmaps.

Handing these bitmaps over to the compositor thread.

Typically, the compositor thread is responsible for:

Drawing bitmaps to the screen via the GPU.

Asking the main thread to update bitmaps for visible or soon-to-be-visible parts of the page.

Figuring out which parts of the page are visible. Figuring out which
parts are soon-to-be-visible when you’re scrolling.

Moving parts of the page when you scroll.

Source: http://sking7.github.io/articles/572118798.html

CSS-based animations, and Web Animations where supported natively, are
typically handled on a thread known as the "compositor thread". This
is different from the browser's "main thread", where styling, layout,
painting, and JavaScript are executed. This means that if the browser
is running some expensive tasks on the main thread, these animations
can keep going without being interrupted.

Other changes to transforms and opacity can, in many cases, also be
handled by the compositor thread.

If any animation triggers paint, layout, or both, the "main thread"
will be required to do work. This is true for both CSS- and
JavaScript-based animations, and the overhead of layout or paint will
likely dwarf any work associated with CSS or JavaScript execution,
rendering the question moot.

Source: https://developers.google.com/web/fundamentals/design-and-ux/animations/animations-and-performance

So compositor is pretty nice when we have to deal with animations. Using px as measure unit is easy and can be done by the compositor thread but using % makes our browser to calculate every "step" of our animation so the main thread has to help us with it. By using await you block the main thread so your browser waits to get recalculated position. When you use absolute unit the compositor thread executes the animation so even if you block the main thread, your animation is running smoothly.

Replace your code with

  async function toggleSidebar() {
    sidebarVisible = !sidebarVisible;
    console.log("1");
    await sleep(800);
    console.log("2");
    heavy(40);
  }

You can notice using % causes:

Animation runs

console.log 1

animation stops

console.log 2

animation runs

Using px:

console.log 1

Animation still runs

console.log 2

animation ends


答:
you need to implement stack, and see if last element of list is same as value or not

```<code>test = [5, 5, 5, 4, 5, 6, 6, 5, 5, 7, 8, 0, 0]

def funct(lis):
    l = []
    for val in lis:
        if len(l) ==0:
            l.append(val)
            yield val
        if l[-1] != val:
            l.append(val)
            yield val

for result in funct(test):
    print(result)
</code>```

output

```<code>5
4
5
6
5
7
8
0
</code>```

way two, using comparison variable in O(N) time complexity and O(1) space complexity

```<code>def funct(lis):
    checker = None
    for val in lis:
        if checker != val:
            checker = val
            yield val
</code>```

Body:
i'm trying to compress a list using generator:

examples

[1, 1, 1, 1, 2, 2, 2, 1, 1, 1] == [1, 2, 1]

[5, 5, 5, 4, 5, 6, 6, 5, 5, 7, 8, 0, 0])) == [5, 4, 5, 6, 5, 7, 8, 0]

I tried to use a generator that checks if the 1st and 2nd element are equal then check 2nd and 3rd and so on until it is no longer equal "when it reaches 4" and then yield "5" then it would repeat the process starting with "4"

code

test = [5, 5, 5, 4, 5, 6, 6, 5, 5, 7, 8, 0, 0] # sample list
from typing import Iterable
def compress(items: list) -> Iterable:

    x = 0
    while items[x] == items[x + 1]:
        x += 1
    yield items[x]

ans = compress(test)
for x in ans:
    print(ans)

but i keep getting

generator object compress at 0x00000254D383C820.
why won't it loop?

if i try and use next() it only goes up to 5 and wont check the other numbers.

any assistance is greatly appreciated.

Body:
you need to implement stack, and see if last element of list is same as value or not

test = [5, 5, 5, 4, 5, 6, 6, 5, 5, 7, 8, 0, 0]

def funct(lis):
    l = []
    for val in lis:
        if len(l) ==0:
            l.append(val)
            yield val
        if l[-1] != val:
            l.append(val)
            yield val

for result in funct(test):
    print(result)

output

5
4
5
6
5
7
8
0

way two, using comparison variable in O(N) time complexity and O(1) space complexity

def funct(lis):
    checker = None
    for val in lis:
        if checker != val:
            checker = val
            yield val


问:
Node + Docker Compose: Development and production setup
I'm looking for a solution to have both a development and a production environment in my project using docker, docker-compose and nodejs.

How do I approach this?

Basically what I want is a command to start my docker production environment, and a command to start my development environment (which could use nodemon for example).

Here is my Dockerfile

```<code>FROM node:13-alpine

RUN mkdir /app

WORKDIR /app

COPY . /app

RUN npm install

RUN npm run build

EXPOSE 1234

CMD ["npm", "run", "prod"] # <--- Have a possibility to run something like "npm run dev" here instead
</code>```

docker-compose.yml

```<code>version: "3"
services:
    findus:
        build: .
        ports:
            - "1234:1234"
        links:
            - mongo
        container_name: myapp
    mongo:
        image: mongo
        restart: always
        ports:
            - "4444:4444"
</code>```

package.json

```<code>// ...
    "scripts": {
        "build": "tsc",
        "dev": "nodemon source/index.ts",
        "prod": "node build/index.js"
    },
// ...
</code>```

答:
You can make use of entrypoint and pass the command to the docker container. Then you can use docker-compose inharitance to launch compose for the environment that you want and append command to the entrypoint.

Dockerfile :

```<code>FROM node:13-alpine

RUN mkdir /app

WORKDIR /app

COPY . /app

RUN npm install

RUN npm run build

EXPOSE 1234

ENTRYPOINT ["npm", "run"]
</code>```

Main docker-compose.yml :

```<code>version: "3"
services:
    findus:
        build: .
        ports:
            - "1234:1234"
        links:
            - mongo
        container_name: myapp
    mongo:
        image: mongo
        restart: always
        ports:
            - "4444:4444"
</code>```

And then have two docker-compose files to append the command passed to the image entry point. For development - docker-compose.dev.yml :

```<code>version: "3"
services:
    findus:
        command: dev
</code>```

and docker-compose.prod.yml :

```<code>version: "3"
services:
    findus:
        command: prod
</code>```

Then to launch dev environment :

```<code>docker-compose  -f docker-compose.yml -f docker-compose.dev.yml up
</code>```

and for prod environment :

```<code>docker-compose  -f docker-compose.yml -f docker-compose.prod.yml up
</code>```

So the command will be appended to the ENTRYPOINT instruction.

Also this approach could work with enviroment variables if you wanted to pass the command as environment variable. You can find more information in the docs.

Body:
I'm looking for a solution to have both a development and a production environment in my project using docker, docker-compose and nodejs.

How do I approach this?

Basically what I want is a command to start my docker production environment, and a command to start my development environment (which could use nodemon for example).

Here is my Dockerfile

FROM node:13-alpine

RUN mkdir /app

WORKDIR /app

COPY . /app

RUN npm install

RUN npm run build

EXPOSE 1234

CMD ["npm", "run", "prod"] # <--- Have a possibility to run something like "npm run dev" here instead

docker-compose.yml

version: "3"
services:
    findus:
        build: .
        ports:
            - "1234:1234"
        links:
            - mongo
        container_name: myapp
    mongo:
        image: mongo
        restart: always
        ports:
            - "4444:4444"

package.json

// ...
    "scripts": {
        "build": "tsc",
        "dev": "nodemon source/index.ts",
        "prod": "node build/index.js"
    },
// ...

Body:
You can make use of entrypoint and pass the command to the docker container. Then you can use docker-compose inharitance to launch compose for the environment that you want and append command to the entrypoint.

Dockerfile :

FROM node:13-alpine

RUN mkdir /app

WORKDIR /app

COPY . /app

RUN npm install

RUN npm run build

EXPOSE 1234

ENTRYPOINT ["npm", "run"]

Main docker-compose.yml :

version: "3"
services:
    findus:
        build: .
        ports:
            - "1234:1234"
        links:
            - mongo
        container_name: myapp
    mongo:
        image: mongo
        restart: always
        ports:
            - "4444:4444"

And then have two docker-compose files to append the command passed to the image entry point. For development - docker-compose.dev.yml :

version: "3"
services:
    findus:
        command: dev

and docker-compose.prod.yml :

version: "3"
services:
    findus:
        command: prod

Then to launch dev environment :

docker-compose  -f docker-compose.yml -f docker-compose.dev.yml up

and for prod environment :

docker-compose  -f docker-compose.yml -f docker-compose.prod.yml up

So the command will be appended to the ENTRYPOINT instruction.

Also this approach could work with enviroment variables if you wanted to pass the command as environment variable. You can find more information in the docs.


问:
How to place a new file in a certian place on hard drive (python)
I am making a full python keylogger. It undergoes a simple processes. First store keystrokes inside a file on startup. Next, find the file and send the file across WiFi. Lastly, shutdown. For this to work I need to make a file for the keylogger to send the keystroke information to. I tried using:

```<code>open('myfile', 'w+')
</code>```

This will create my file but how do I place my file into a certain place?

Extra Information:

Python 3.7x

答:
You can add the path to the filename:

```<code>open('/users/myname/myfile.txt', 'w+')
open('C:\\Public\\myfile.txt', 'w+')
</code>```

Or, you can change your current directory:

```<code>import os
os.chdir('/tmp/')
open('myfile.txt', 'w+')
</code>```

Both should work! Happy Coding!

Body:
I am making a full python keylogger. It undergoes a simple processes. First store keystrokes inside a file on startup. Next, find the file and send the file across WiFi. Lastly, shutdown. For this to work I need to make a file for the keylogger to send the keystroke information to. I tried using:

open('myfile', 'w+')

This will create my file but how do I place my file into a certain place?

Extra Information:

Python 3.7x

Body:
You can add the path to the filename:

open('/users/myname/myfile.txt', 'w+')
open('C:\\Public\\myfile.txt', 'w+')

Or, you can change your current directory:

import os
os.chdir('/tmp/')
open('myfile.txt', 'w+')

Both should work! Happy Coding!


问:
IE6 - show swf animation
IE6 don`t show animation:

```<code>          <object width="456" height="315">
            <param name="movie" value="animacija.swf">
            <param name="wmode" value="transparent" />
            <embed src="animacija.swf" width="456" height="315">
            </embed>
          </object>
</code>```

"Your security settings do not allow websites to use ActiveX controls installed on your computer."

Other animation show normaly on other websites.

答: Are you running your HTML-file locally? That can be a problem. Try uploading the HTML & swf-file to the web and check if the problem still occcurs.</p>

Title: IE6 - show swf animation

Body:
IE6 don`t show animation:

          <object width="456" height="315">
            <param name="movie" value="animacija.swf">
            <param name="wmode" value="transparent" />
            <embed src="animacija.swf" width="456" height="315">
            </embed>
          </object>

"Your security settings do not allow websites to use ActiveX controls installed on your computer."

Other animation show normaly on other websites.


问:
is overriding's effect temporary or permanently?
I wrote these lines of code in one of my programs in a solution to change the equality comparison between two instances of a class from their reference to their value:

```<code>public interface IEquatable<Clock>
{

}
public bool Equals(Clock theObj)
{
    if (theObj == null)
    {
        return false;
    }
    if (theObj.ToString() == this.ToString())
    {
        return true;
    }
    else
    {
        return false;
    }
}

public override bool Equals(object obj)
{
   if (obj == null)
    {
        return false;
    }
    Clock clck = obj as Clock;
    if (clck == null)
    {
        return false;
    }
    else
    {
        return Equals(clck);
    }
}
public override int GetHashCode()
{
    return Hours;
}`
</code>```

and now when i try to compare two instances of a class using " Equals(T)" method in a different project in a different solution it compares their value not their reference.

does overriding a method in a project affect that method in other projects?

my complete code is:
    `using System;
    using System.Diagnostics.Contracts;
    using System.Runtime.InteropServices.WindowsRuntime;
    using System.Security.Cryptography.X509Certificates;

```<code>public class Clock
{
    public int Minutes;
    public int Hours;
    public interface IEquatable<Clock>
    {

    }
    public bool Equals(Clock theObj)
    {
        if (theObj == null)
        {
            return false;
        }
        if (theObj.ToString() == this.ToString())
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public override bool Equals(object obj)
    {
       if (obj == null)
       {
           return false;
       }
       Clock clck = obj as Clock;
       if (clck == null)
       {
           return false;
       }
       else
       {
           return Equals(clck);
       }
   }
   public override int GetHashCode()
   {
       return Hours;
   }
   public override string ToString()
   {
       if (Hours < 10)
       {
           if (Minutes < 10)
           {
               return "0" + Hours + ":0" + Minutes;
           }
           else
           {
               return "0" + Hours + ":" + Minutes;
           }
       }
       else
       {
           if (Minutes < 10)
           {
               return Hours + ":0" + Minutes;
           }
           else
           {
               return Hours + ":" + Minutes;
           }
       }
   }
   public Clock(int hours, int minutes)
   {
       while (minutes > 59 || minutes < 0)
       {
           if (minutes > 59)
           {
               minutes -= 60;
               hours++;
           }
           if (minutes < 0)
           {
               minutes += 60;
               hours--;
           }
       }

       while (hours > 23 || hours < 0)
       {
           if (hours > 23)
           {
               hours -= 24;
           }

           if (hours < 0)
           {
               hours += 24;
           }
       }
       Hours = hours;
       Minutes = minutes;
   }

   public Clock Add(int minutesToAdd)
   {
       var res = new Clock(Hours , Minutes + minutesToAdd);
       return res;
   }

   public Clock Subtract(int minutesToSubtract)
   {
       var res = new Clock(Hours , Minutes - minutesToSubtract);
       return res;
   }}
</code>```

thank you for your time!

答:
Logic of your Equals method is wrong! for classes without ToString method override, The output is something like this StackOverflowCodes.Clock, Which results in all objects being equal!
Please take a look at following code for more ideas:

```<code>public class Clock : IEquatable<Clock>
{
    public int Hours { get; set; }
    public int Minutes { get; set; }
    public int Seconds { get; set; }

    public bool Equals(Clock c)
    {
        if (c == null)
            return false;
        // Here is a somewhat correct logic for equality (sort of ...)
        //return c.Hours == Hours && c.Minutes == Minutes;
        return c.ToString() == this.ToString();
    }
    public override int GetHashCode() => Hours * 3600 + Minutes * 60 + Seconds;
    public override bool Equals(object obj)
    {
        var clock = obj as Clock;

        if (clock != null)
            return Equals(clock);
        return false;
    }

    public static void Main()
    {
        Clock c2 = new Clock { Hours = 12, Minutes = 01, Seconds = 59 };
        var c1 = new Clock { Hours = 12 };

        Console.WriteLine(c1.Equals(c2));
        Console.WriteLine(Equals(c1, c2));
        Console.WriteLine(c1 == c2);

        Console.WriteLine(c1.ToString());
        Console.WriteLine(c2.ToString());
    }
</code>```

And for your question, If you are referencing the project/solution which have your defined Clock type, Then you are using that custom logic you defined, Otherwise they should not have anything in common.

Body:
I wrote these lines of code in one of my programs in a solution to change the equality comparison between two instances of a class from their reference to their value:

public interface IEquatable<Clock>
{

}
public bool Equals(Clock theObj)
{
    if (theObj == null)
    {
        return false;
    }
    if (theObj.ToString() == this.ToString())
    {
        return true;
    }
    else
    {
        return false;
    }
}

public override bool Equals(object obj)
{
   if (obj == null)
    {
        return false;
    }
    Clock clck = obj as Clock;
    if (clck == null)
    {
        return false;
    }
    else
    {
        return Equals(clck);
    }
}
public override int GetHashCode()
{
    return Hours;
}`

and now when i try to compare two instances of a class using " Equals(T)" method in a different project in a different solution it compares their value not their reference.

does overriding a method in a project affect that method in other projects?

my complete code is:
    `using System;
    using System.Diagnostics.Contracts;
    using System.Runtime.InteropServices.WindowsRuntime;
    using System.Security.Cryptography.X509Certificates;

public class Clock
{
    public int Minutes;
    public int Hours;
    public interface IEquatable<Clock>
    {

    }
    public bool Equals(Clock theObj)
    {
        if (theObj == null)
        {
            return false;
        }
        if (theObj.ToString() == this.ToString())
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public override bool Equals(object obj)
    {
       if (obj == null)
       {
           return false;
       }
       Clock clck = obj as Clock;
       if (clck == null)
       {
           return false;
       }
       else
       {
           return Equals(clck);
       }
   }
   public override int GetHashCode()
   {
       return Hours;
   }
   public override string ToString()
   {
       if (Hours < 10)
       {
           if (Minutes < 10)
           {
               return "0" + Hours + ":0" + Minutes;
           }
           else
           {
               return "0" + Hours + ":" + Minutes;
           }
       }
       else
       {
           if (Minutes < 10)
           {
               return Hours + ":0" + Minutes;
           }
           else
           {
               return Hours + ":" + Minutes;
           }
       }
   }
   public Clock(int hours, int minutes)
   {
       while (minutes > 59 || minutes < 0)
       {
           if (minutes > 59)
           {
               minutes -= 60;
               hours++;
           }
           if (minutes < 0)
           {
               minutes += 60;
               hours--;
           }
       }

       while (hours > 23 || hours < 0)
       {
           if (hours > 23)
           {
               hours -= 24;
           }

           if (hours < 0)
           {
               hours += 24;
           }
       }
       Hours = hours;
       Minutes = minutes;
   }

   public Clock Add(int minutesToAdd)
   {
       var res = new Clock(Hours , Minutes + minutesToAdd);
       return res;
   }

   public Clock Subtract(int minutesToSubtract)
   {
       var res = new Clock(Hours , Minutes - minutesToSubtract);
       return res;
   }}

thank you for your time!

Body:
Logic of your Equals method is wrong! for classes without ToString method override, The output is something like this StackOverflowCodes.Clock, Which results in all objects being equal!
Please take a look at following code for more ideas:

public class Clock : IEquatable<Clock>
{
    public int Hours { get; set; }
    public int Minutes { get; set; }
    public int Seconds { get; set; }

    public bool Equals(Clock c)
    {
        if (c == null)
            return false;
        // Here is a somewhat correct logic for equality (sort of ...)
        //return c.Hours == Hours && c.Minutes == Minutes;
        return c.ToString() == this.ToString();
    }
    public override int GetHashCode() => Hours * 3600 + Minutes * 60 + Seconds;
    public override bool Equals(object obj)
    {
        var clock = obj as Clock;

        if (clock != null)
            return Equals(clock);
        return false;
    }

    public static void Main()
    {
        Clock c2 = new Clock { Hours = 12, Minutes = 01, Seconds = 59 };
        var c1 = new Clock { Hours = 12 };

        Console.WriteLine(c1.Equals(c2));
        Console.WriteLine(Equals(c1, c2));
        Console.WriteLine(c1 == c2);

        Console.WriteLine(c1.ToString());
        Console.WriteLine(c2.ToString());
    }

And for your question, If you are referencing the project/solution which have your defined Clock type, Then you are using that custom logic you defined, Otherwise they should not have anything in common.


问:
How to parse URLs in Google Apps Script?
I have a GAS project and I need to parse some URLs into their hostname and pathname properties as follows.

Code.gs

```<code>const url = new URL( 'http://www.example.com/cats', );
const { hostname,  pathname, } = url;
</code>```

Here are some docs on the above URL constructor method. [1] | [2]

The above code produces the following error.

Error message:

ReferenceError: URL is not defined (line 64, file "Code")

What am I missing? How can I parse my URLs using GAS?

答:
The URL interface is not part of ECMAScript, it's part of a Web API, more specifically of URL API. Google Apps Script doesn't support web APIsm by default.

From https://developers.google.com/apps-script/guides/v8-runtime

Modern ECMAScript syntax

You can use modern ECMAScript syntax in scripts that are powered by the V8 runtime. This syntax includes let, const, and many other popular features.

Related

Can I use HTML5 web workers in Google Apps scripts?

Body:
I have a GAS project and I need to parse some URLs into their hostname and pathname properties as follows.

Code.gs

const url = new URL( 'http://www.example.com/cats', );
const { hostname,  pathname, } = url;

Here are some docs on the above URL constructor method. [1] | [2]

The above code produces the following error.

Error message:

ReferenceError: URL is not defined (line 64, file "Code")

What am I missing? How can I parse my URLs using GAS?


问:
prevent insertion if regular expression is not met
I am studying triggers statements in MySQL and I need to prevent an insertion if the person's name has special characters.

I thought of doing something like this:

```<code>create trigger verifydata
    before insert
    on person
    for each row
    begin
        if(not new.name RLIKE '[A-Za-z]') then
            signal sqlstate '45000' set message_text = 'Verify name';
        end if;
    end;@
    delimiter ;

</code>```

But it does not work.

What is the correct way to do it, any recommendations?

答:
The most recent versions of MySQL support check constraints:

```<code>alter table person add constraint ck_person_name
    check (name not regexp '[^A-Za-z]');
</code>```

Then in most versions still in use, you can emulate it by creating a view:

```<code>create view v_person as
     select p.*
     from person p
     where p.name not regexp '[^A-Za-z]';
</code>```

Then insert into the view.  If the view logic filters out the insert, then the insert fails.

Body:
I am studying triggers statements in MySQL and I need to prevent an insertion if the person's name has special characters.

I thought of doing something like this:

create trigger verifydata
    before insert
    on person
    for each row
    begin
        if(not new.name RLIKE '[A-Za-z]') then
            signal sqlstate '45000' set message_text = 'Verify name';
        end if;
    end;@
    delimiter ;

But it does not work.

What is the correct way to do it, any recommendations?

Body:
The most recent versions of MySQL support check constraints:

alter table person add constraint ck_person_name
    check (name not regexp '[^A-Za-z]');

Then in most versions still in use, you can emulate it by creating a view:

create view v_person as
     select p.*
     from person p
     where p.name not regexp '[^A-Za-z]';

Then insert into the view.  If the view logic filters out the insert, then the insert fails.


问:
the getter 'text' was called on null flutter
I have this error in my Flutter app:

NoSuchMethodError: The getter 'text' was called on null.
  Receiver: null
  Tried calling: text
  See also:
  https://flutter.dev/docs/testing/errors

```<code>import 'package:flutter/material.dart';

void main() {
  runApp(
    NewApp()
  );
}

class NewApp extends StatefulWidget {
  NewApp({Key key}) : super(key: key);

  @override
  _NewAppState createState() => _NewAppState();
}

class _NewAppState extends State<NewApp> {
  TextEditingController textController;

  @override
  Widget build(BuildContext context) {
    return Container(
       child: Column(
         children: <Widget>[
           TextField(
            controller: textController,
          ),
          Text(
            textController.text
          )
         ],
       )
    );
  }
}
</code>```

答:
It looks like you have not initialized your TextEditingController. You can initialize it at the time of declaring it like this,

```<code>TextEditingController textController = TextEditingController();
</code>```

It is essential to initialize it before using it otherwise the instance textController remains null and textController.text is called on null.

Body:
I have this error in my Flutter app:

NoSuchMethodError: The getter 'text' was called on null.
  Receiver: null
  Tried calling: text
  See also:
  https://flutter.dev/docs/testing/errors

import 'package:flutter/material.dart';

void main() {
  runApp(
    NewApp()
  );
}

class NewApp extends StatefulWidget {
  NewApp({Key key}) : super(key: key);

  @override
  _NewAppState createState() => _NewAppState();
}

class _NewAppState extends State<NewApp> {
  TextEditingController textController;

  @override
  Widget build(BuildContext context) {
    return Container(
       child: Column(
         children: <Widget>[
           TextField(
            controller: textController,
          ),
          Text(
            textController.text
          )
         ],
       )
    );
  }
}

Body:
It looks like you have not initialized your TextEditingController. You can initialize it at the time of declaring it like this,

TextEditingController textController = TextEditingController();

It is essential to initialize it before using it otherwise the instance textController remains null and textController.text is called on null.


问:
how can i enter the elements of the array and every time we get the new element,we put it in the middle of array?
the thing is that i know how to put an element in the specific position of existing array,but i dont know how to get the elements that i want by user and put elements id the middle.</p>

```<code>int arr[100] = { 0 };
int i, x, pos, n = 10;

for (i = 0; i < 10; i++)
    arr[i] = i + 1;

for (i = 0; i < n; i++)
    printf("%d ", arr[i]);
printf("\n");

x = 50;
pos = 5;
n++;

for (i = n; i >= pos; i--)
    arr[i] = arr[i - 1];

arr[pos - 1] = x;

for (i = 0; i < n; i++)
    printf("%d ", arr[i]);
printf("\n");
</code>```

答:
You could use a std::list</p>

```<code>std::list<int> arr;
for (int i = 0; i < 10; i++)
    arr.push_back(i + 1);

for (const auto &el : arr)
    printf("%d ", el);
printf("\n");

const int x = 50;
const std::size_t pos = 5;

arr.insert(pos - 1, x);
arr.pop_back();

for (const auto &el : arr)
    printf("%d ", el);
printf("\n");
</code>```

Body:
the thing is that i know how to put an element in the specific position of existing array,but i dont know how to get the elements that i want by user and put elements id the middle.

int arr[100] = { 0 };
int i, x, pos, n = 10;

for (i = 0; i < 10; i++)
    arr[i] = i + 1;

for (i = 0; i < n; i++)
    printf("%d ", arr[i]);
printf("\n");

x = 50;
pos = 5;
n++;

for (i = n; i >= pos; i--)
    arr[i] = arr[i - 1];

arr[pos - 1] = x;

for (i = 0; i < n; i++)
    printf("%d ", arr[i]);
printf("\n");

Body:
You could use a std::list

std::list<int> arr;
for (int i = 0; i < 10; i++)
    arr.push_back(i + 1);

for (const auto &el : arr)
    printf("%d ", el);
printf("\n");

const int x = 50;
const std::size_t pos = 5;

arr.insert(pos - 1, x);
arr.pop_back();

for (const auto &el : arr)
    printf("%d ", el);
printf("\n");


问:
comboBox.SelectedItem problem
ComboBox is binding database

```<code>string str= comboBox1.SelectedItem.ToString();
</code>```

the line gives System.Data.DataRowView value for str but not giving selected item name.

答: If you want the text of the selected item, just use comboBox1.Text.

Title: comboBox.SelectedItem problem

Body:
ComboBox is binding database

string str= comboBox1.SelectedItem.ToString();

the line gives System.Data.DataRowView value for str but not giving selected item name.


答:
You are checking if your value contains only non-alphabetic characters, while you want to make sure it does not contain any. You need to reverse the logic here:

```<code>create trigger verifydata
before insert
on person
for each row
begin
    if(new.name rlike '[^A-Za-z]') then
        signal sqlstate '45000' set message_text = 'Verify name';
    end if;
end;
delimiter ;
</code>```

Note that if you are running MySQL 8.0.16 or higher, you can do this with a check constraint instead of a trigger:

```<code>alter table person add constraint check_person_name
check (name not rlike '[^A-Za-z]');
</code>```

Title: prevent insertion if regular expression is not met

Body:
You are checking if your value contains only non-alphabetic characters, while you want to make sure it does not contain any. You need to reverse the logic here:

create trigger verifydata
before insert
on person
for each row
begin
    if(new.name rlike '[^A-Za-z]') then
        signal sqlstate '45000' set message_text = 'Verify name';
    end if;
end;
delimiter ;

Note that if you are running MySQL 8.0.16 or higher, you can do this with a check constraint instead of a trigger:

alter table person add constraint check_person_name
check (name not rlike '[^A-Za-z]');


问:
Pandas access a specific value from a dictionary of columns
I've a dataframe that have a dictionary with this format (the column name is 'due'):

```<code>{'date': '2020-05-21', 'is_recurring': False, 'lang': 'en', 'string': 'May 21', 'timezone': None}
None
</code>```

I was trying to get the item 'date' with the following code:

```<code>print(df.due.apply(lambda x: x['date']))
</code>```

But I was getting the following error:

```<code>TypeError: 'NoneType' object is not subscriptable
</code>```

So I was trying to convert the None to NA in order to avoid this error (is the best practice?). For that I am using this:

```<code>df['due'] = np.where(df['due'] is None, np.nan, df['due'])
</code>```

However, the None rows continue to appear as None. What I am doing wrong?

Thanks!

答:
You may have NaNs in your column:

```<code>df
                                                 due
0  {'date': '2020-05-21', 'is_recurring': False, ...
1                                                NaN
</code>```

In this case pandas offers str.get (or .str[..] shorthand) as a "safe" way for indexing objects:

```<code>df['due'].str['date']

0    2020-05-21
1           NaN
Name: due, dtype: object
</code>```

Body:
I've a dataframe that have a dictionary with this format (the column name is 'due'):

{'date': '2020-05-21', 'is_recurring': False, 'lang': 'en', 'string': 'May 21', 'timezone': None}
None

I was trying to get the item 'date' with the following code:

print(df.due.apply(lambda x: x['date']))

But I was getting the following error:

TypeError: 'NoneType' object is not subscriptable

So I was trying to convert the None to NA in order to avoid this error (is the best practice?). For that I am using this:

df['due'] = np.where(df['due'] is None, np.nan, df['due'])

However, the None rows continue to appear as None. What I am doing wrong?

Thanks!

Body:
You may have NaNs in your column:

df
                                                 due
0  {'date': '2020-05-21', 'is_recurring': False, ...
1                                                NaN

In this case pandas offers str.get (or .str[..] shorthand) as a "safe" way for indexing objects:

df['due'].str['date']

0    2020-05-21
1           NaN
Name: due, dtype: object


问:
Calling Windows Form Method from its User Control
I have a User Control on My windows Form, and there is a button on my user control on click of which I want to call its form method.

Thanx

答:
What worked for me is using delegate</p>

```<code> public delegate void ClickMe (string message);
public partial class CustomControl : UserControl
{
    public event ClickMe CustomControlClickMe;
    public CustomControl()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        if (CustomControlClickMe != null)
            CustomControlClickMe("Hello");
    }

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        customControl1.CustomControlClickMe += new ClickMe(button2_Click);
    }

    void button2_Click(string message)
    {
        MessageBox.Show(message);
    }
</code>```

Body:
What worked for me is using delegate

 public delegate void ClickMe (string message);
public partial class CustomControl : UserControl
{
    public event ClickMe CustomControlClickMe;
    public CustomControl()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        if (CustomControlClickMe != null)
            CustomControlClickMe("Hello");
    }

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        customControl1.CustomControlClickMe += new ClickMe(button2_Click);
    }

    void button2_Click(string message)
    {
        MessageBox.Show(message);
    }


问:
MongoDB Authentication Database Purpose
My question is about the mongo shell --authenticationDatabase option.

I was confused by it for a bit thinking that the the database I created the user in was the admin database since that is where the user is actually defined after reading this documentation here: https://docs.mongodb.com/manual/core/security-users/#user-management-interface

I understand I was wrong; the authentication database is the database the user has a role for. My question then is what is the purpose of the option "--authenicationDatabase?" See my scenarios below.

The command below will connect to the myapp database and also authenticate against the myapp database

```<code>mongo -u "bob" -p "bobspassword" --authenticationDatabase "myapp" myapp
</code>```

The command below will connect to the myapp database and also authenticate against the myapp database by default. This seems to make the command above obsolete.

```<code>mongo -u "bob" -p "bobspassword" --authenticationDatabase "myapp" myapp
</code>```

The command below will authenticate against the myapp database but not connect to it. Why? Is it simply to test credentials?

```<code>mongo -u "bob" -p "bobspassword" --authenticationDatabase "myapp"
</code>```

This command would tell me "Error: Authentication failed." as well so I still wonder why I would need the previous command to find out my credentials are invalid.

```<code>mongo -u "bob" -p "bobspassword" myapp
</code>```

Lastly, is there a situation where I need to authenticate against one database and connect to a different one like the command below? I can only connect to databases for which I have a role defined so why wouldn't I authenticate against the database I was trying to connect to?

```<code>mongo -u "bob" -p "bobspassword" --authenticationDatabase "myapp" myotherapp
</code>```

Thank you for your insight!

答:
When adding a user, you create the user in a specific database. This database is the authentication database for the user.

In most cases, you would want to create users in the admin database. This is a privileged database. However, you are allowed to create user in other databases. If two users have the same name but are created in different databases, they are two separate users. IMHO, this authentication database mechanism provides a sort of namespace so that users with same name are allowed (think about user management in a big organization).

But this is just how Mongo organize users and store then in authentication databases. The authentication database has nothing to do with to which databases this user has privilege (access).

Back to your case, you created a user in 'myapp' database and also grant it access to 'myapp' database. That's why you need to first authenticate against 'myapp', which serves as authentication database, and then connect to 'myapp' for accessing data.

Title: MongoDB Authentication Database Purpose

Body:
My question is about the mongo shell --authenticationDatabase option.

I was confused by it for a bit thinking that the the database I created the user in was the admin database since that is where the user is actually defined after reading this documentation here: https://docs.mongodb.com/manual/core/security-users/#user-management-interface

I understand I was wrong; the authentication database is the database the user has a role for. My question then is what is the purpose of the option "--authenicationDatabase?" See my scenarios below.

The command below will connect to the myapp database and also authenticate against the myapp database

mongo -u "bob" -p "bobspassword" --authenticationDatabase "myapp" myapp

The command below will connect to the myapp database and also authenticate against the myapp database by default. This seems to make the command above obsolete.

mongo -u "bob" -p "bobspassword" --authenticationDatabase "myapp" myapp

The command below will authenticate against the myapp database but not connect to it. Why? Is it simply to test credentials?

mongo -u "bob" -p "bobspassword" --authenticationDatabase "myapp"

This command would tell me "Error: Authentication failed." as well so I still wonder why I would need the previous command to find out my credentials are invalid.

mongo -u "bob" -p "bobspassword" myapp

Lastly, is there a situation where I need to authenticate against one database and connect to a different one like the command below? I can only connect to databases for which I have a role defined so why wouldn't I authenticate against the database I was trying to connect to?

mongo -u "bob" -p "bobspassword" --authenticationDatabase "myapp" myotherapp

Thank you for your insight!


问:
Count decimal numbers in a string using the standard library
I have white-space separeted integers inside a string, e.g.:

```<code>std::string s = "1 2 33 444 0 5";
</code>```

The string is well-formed: just white-space separated numbers without any letters, new-lines, etc.

How to count the number of integers in the above string in an STL way? I am looking for something "short" that will use e.g. iterators or <algorithm>.

答:
std::count_if(s.begin(),s.end(), [](unsigned char c){ return std::isspace(c);}) + 1

Edit:

If there are multiple/varying spaces between chars, then you can change the lambda to:

```<code>    [](unsigned int c)
    {
        static bool prev = false;
        bool current = isspace(c);
        bool new_space = !prev && current;
        prev = current;

        return new_space;
    }
</code>```

Body:
I have white-space separeted integers inside a string, e.g.:

std::string s = "1 2 33 444 0 5";

The string is well-formed: just white-space separated numbers without any letters, new-lines, etc.

How to count the number of integers in the above string in an STL way? I am looking for something "short" that will use e.g. iterators or <algorithm>.

Body:
std::count_if(s.begin(),s.end(), [](unsigned char c){ return std::isspace(c);}) + 1

Edit:

If there are multiple/varying spaces between chars, then you can change the lambda to:

    [](unsigned int c)
    {
        static bool prev = false;
        bool current = isspace(c);
        bool new_space = !prev && current;
        prev = current;

        return new_space;
    }


答:
A simple way is to use string streams:

```<code>#include <iostream>
#include <sstream>

int main()
{
    int temp;
    int count = 0;
    std::string s = "1 2 33 444 0 5";

    std::stringstream ss(s);
    while(ss >> temp){
        count++;
    }
    std::cout << count; //test print
    return EXIT_SUCCESS;
}
</code>```

Note that this will only count parseabe values, for instance, if a non-numeric character is found (appart from spaces) it will stop counting. It also works for multiple spaces.

Title: Count decimal numbers in a string using the standard library

Body:
A simple way is to use string streams:

#include <iostream>
#include <sstream>

int main()
{
    int temp;
    int count = 0;
    std::string s = "1 2 33 444 0 5";

    std::stringstream ss(s);
    while(ss >> temp){
        count++;
    }
    std::cout << count; //test print
    return EXIT_SUCCESS;
}

Note that this will only count parseabe values, for instance, if a non-numeric character is found (appart from spaces) it will stop counting. It also works for multiple spaces.


问:
Should I be saving my data in a .csv file?
I am writing a small .py file that contains some classes to be imported later repetitively into other work. The mentioned .py file uses some small database (in order of KB) in the form of tables. Do you think it is better to store this data in the same .py file or is it better to keep it in a separate .csv file? What are the differences in terms of performance and convenience for later use? A point that I might have to mention is that this data is numerical and is not prone to any possible change in the future.
Single items are to be accessed from this data at a time.

答: It's better practice to write into a csv file as it improves readability of the entire code. It won't hurt you performance and will really benefit you.</p>


问:
Angular: Using a method to fill an @Input value
Why does the method getDayShifts(day) in a parent component's template gets called every time the mouse hovers over a child component?

abstract.class.ts

```<code>export abstract class DayView implements OnInit, OnDestroy, OnChanges {

  public ngOnInit(): void {
    this.dl.shifts
        .pipe(
            takeUntil(this.ngUnsubscribe),
            map( shifts => this.shifts = shifts),
            tap( shifts => this.filterShifts())
        )
        .subscribe();
  }

  public ngOnChanges(changes: SimpleChanges): void {
    this.filterShifts();
    this.afterChanges(changes);
    this.cdr.detectChanges();
  }

  public abstract afterChanges(changes: SimpleChanges)

  public getDayShifts( day: CalendarDay ): Array<Shift> {
    const s = this.views.getDayShifts(day.date, this.filteredShifts);
    return s;
  }

  /** ... */

}
</code>```

parent.component.ts

```<code>@Component({
    selector: 'day-month-view',
    templateUrl: './day-month-view.component.html',
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class DayMonthViewComponent extends DayView {
    public afterChanges(changes: SimpleChanges): void {}
}
</code>```

parent.component.html

```<code><div *ngFor="let week of weeks; index as _wi">
   <div *ngFor="let day of week; index as _di">

     <dropdown-btn
            [id]="'dd_'+_wi+'_'+_di"
            [isEnabled]="isEditable(day.date)"
            [options]="dayOptions"
THIS ONE => [objectData]="getDayShifts(day)"
            (selected)="onOptionClick($event)"><span class="day-date">{{day.date.getDate()}}</span></dropdown-btn>
     <shift-month
            [day]="day"
THIS ONE => [shifts]="getDayShifts(day)"></shift-month>
   </div>
</div>
</code>```

child.component.ts

```<code>@Component({
    selector: 'shift-month',
    templateUrl: './shift-month.component.html',
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class ShiftMonthComponent extends ShiftView {
    public afterInit() {
        const dayShifts = this.views.getDayShifts(this.day.date, this.shifts);
        this.filteredShifts = this.setViewMeta(dayShifts);
        this.cdr.markForCheck();
    }
}
</code>```

child.abstract.class.ts

```<code>export abstract class ShiftView implements OnInit, OnChanges, OnDestroy {

    public ngOnChanges(): void {
        this.afterInit();
    }

    public abstract afterInit()
}
</code>```

Will it always trigger a change for an @Input() if it is a method? I am somewhat lost.

答:
Yes, it happens because method can change value any time, so to make sure correct value is there, angular call it during each re-render. Thats why calling method inside template is bad practice.

Still if you want to do it use OnPush strategy inside component decorator. But with that you might need to trigger change detection manually at some places. Best will be if you can get rid of method call in template and instead pass a simple property.

Body:
Why does the method getDayShifts(day) in a parent component's template gets called every time the mouse hovers over a child component?

abstract.class.ts

export abstract class DayView implements OnInit, OnDestroy, OnChanges {

  public ngOnInit(): void {
    this.dl.shifts
        .pipe(
            takeUntil(this.ngUnsubscribe),
            map( shifts => this.shifts = shifts),
            tap( shifts => this.filterShifts())
        )
        .subscribe();
  }

  public ngOnChanges(changes: SimpleChanges): void {
    this.filterShifts();
    this.afterChanges(changes);
    this.cdr.detectChanges();
  }

  public abstract afterChanges(changes: SimpleChanges)

  public getDayShifts( day: CalendarDay ): Array<Shift> {
    const s = this.views.getDayShifts(day.date, this.filteredShifts);
    return s;
  }

  /** ... */

}

parent.component.ts

@Component({
    selector: 'day-month-view',
    templateUrl: './day-month-view.component.html',
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class DayMonthViewComponent extends DayView {
    public afterChanges(changes: SimpleChanges): void {}
}

parent.component.html

     <dropdown-btn
            [id]="'dd_'+_wi+'_'+_di"
            [isEnabled]="isEditable(day.date)"
            [options]="dayOptions"
THIS ONE => [objectData]="getDayShifts(day)"
            (selected)="onOptionClick($event)">{{day.date.getDate()}}</dropdown-btn>
     <shift-month
            [day]="day"
THIS ONE => [shifts]="getDayShifts(day)"></shift-month>

child.component.ts

@Component({
    selector: 'shift-month',
    templateUrl: './shift-month.component.html',
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class ShiftMonthComponent extends ShiftView {
    public afterInit() {
        const dayShifts = this.views.getDayShifts(this.day.date, this.shifts);
        this.filteredShifts = this.setViewMeta(dayShifts);
        this.cdr.markForCheck();
    }
}

child.abstract.class.ts

export abstract class ShiftView implements OnInit, OnChanges, OnDestroy {

    public ngOnChanges(): void {
        this.afterInit();
    }

    public abstract afterInit()
}

Will it always trigger a change for an @Input() if it is a method? I am somewhat lost.


问:
How can I tell a Salt Master to download a file to make it available to minions that don't have access to the internet?
I have some minions that don't have access to the internet, but I need to get a package installed from a website. So I need to have the master download the file and then have the minion pull from the master. Ideally the master would download any new versions of the file for the minions to consume.</p>

答:
Depending on what you want to download, the "easiest" way for me to do it would be to do some kind of orchestration:

First you target the minion running on your master (I'm assuming you have one) with a recipe to download the internet file and to place it somewhere where minion will have access to it ( http server? salt file sharing? Network drive whatever)

Then a recipe for all minion to retrieve the file and use it

the orchestration recipe would have to be located under /srv/salt/orch/file_download.sls for instance

```<code>Master Download file:
  salt.state:
    - tgt: master-minion
    - failhard: True
    - sls:
      - recipe_to_download_file

Minion use file:
  salt.state:
    - tgt: * # or anything suitable to taget your minions
    - failhard: True
    - sls:
      - install_file
</code>```

and launch it with
salt-run state.orchestrate orch.file_download

Body:
Depending on what you want to download, the "easiest" way for me to do it would be to do some kind of orchestration:

First you target the minion running on your master (I'm assuming you have one) with a recipe to download the internet file and to place it somewhere where minion will have access to it ( http server? salt file sharing? Network drive whatever)

Then a recipe for all minion to retrieve the file and use it

the orchestration recipe would have to be located under /srv/salt/orch/file_download.sls for instance

Master Download file:
  salt.state:
    - tgt: master-minion
    - failhard: True
    - sls:
      - recipe_to_download_file

Minion use file:
  salt.state:
    - tgt: * # or anything suitable to taget your minions
    - failhard: True
    - sls:
      - install_file

and launch it with
salt-run state.orchestrate orch.file_download