问:
Python code comparison with if validates False when it should be True
I have the following Python code below. I'm expecting the code to return True but when I run it, it seems to always return False. It seems to fail when checking if 361 is 361 but I can't work out why:

```<code>def comp(array1, array2):
    if array1 is None or array2 is None or len(array1) is 0 or len(array2) is 0 or len(array1) is not len(array2):
        return False

    aListSquared = [x * x for x in sorted(array1)]
    array2.sort()

    print(aListSquared)
    print(array2)

    for x in range(len(aListSquared)):
        print('{0}:{1}'.format(aListSquared[x], type(aListSquared[x])))
        print('{0}:{1}'.format(array2[x], type(array2[x])))

        if int(aListSquared[x]) is not int(array2[x]):
            return False

    return True

a1 = [121, 144, 19, 161, 19, 144, 19, 11]
a2 = [11 * 11, 121 * 121, 144 * 144, 19 * 19, 161 * 161, 19 * 19, 144 * 144, 19 * 19]
print(comp(a1, a2))

</code>```

Can anyone tell me what i'm doing wrong or why the validation doesn't seem to be working correctly?

Many Thanks

答:
In your lines

```<code>if array1 is None or array2 is None or len(array1) is 0 or len(array2) is 0 or len(array1) is not len(array2):
</code>```

and

```<code>if int(aListSquared[x]) is not int(array2[x]):
</code>```

you're using the is operator to compare two integers. That's not how the operator should be used in Python: The operator is to test for object identity, yet you only want to find out if the value is the same. In your case, you should just use == instead of is and != instead of is not respectively.

For further reading, see the Python documentation on Value comparisons and Identity comparisons, as well as "is" operator behaves unexpectedly with integers for example.

Body:
I have the following Python code below. I'm expecting the code to return True but when I run it, it seems to always return False. It seems to fail when checking if 361 is 361 but I can't work out why:

def comp(array1, array2):
    if array1 is None or array2 is None or len(array1) is 0 or len(array2) is 0 or len(array1) is not len(array2):
        return False

    aListSquared = [x * x for x in sorted(array1)]
    array2.sort()

    print(aListSquared)
    print(array2)

    for x in range(len(aListSquared)):
        print('{0}:{1}'.format(aListSquared[x], type(aListSquared[x])))
        print('{0}:{1}'.format(array2[x], type(array2[x])))

        if int(aListSquared[x]) is not int(array2[x]):
            return False

    return True

a1 = [121, 144, 19, 161, 19, 144, 19, 11]
a2 = [11 * 11, 121 * 121, 144 * 144, 19 * 19, 161 * 161, 19 * 19, 144 * 144, 19 * 19]
print(comp(a1, a2))

Can anyone tell me what i'm doing wrong or why the validation doesn't seem to be working correctly?

Many Thanks

Body:
In your lines

if array1 is None or array2 is None or len(array1) is 0 or len(array2) is 0 or len(array1) is not len(array2):

and

if int(aListSquared[x]) is not int(array2[x]):

you're using the is operator to compare two integers. That's not how the operator should be used in Python: The operator is to test for object identity, yet you only want to find out if the value is the same. In your case, you should just use == instead of is and != instead of is not respectively.

For further reading, see the Python documentation on Value comparisons and Identity comparisons, as well as "is" operator behaves unexpectedly with integers for example.


来源: stackexchange

问:
Reset_cooldown Discord.py
Im pretty new to discord.py, and python in general but im trying to learn. I dont know how to add the command.reset_cooldown to my code. As it says in the code below, i want !test to ignore the cooldown but i want !test 2 to have the cooldown. Can someone help me?</p>

```<code>@commands.cooldown(1, 30, commands.BucketType.user)
async def test(ctx, command=None):
    if command is None:
        await ctx.send('I want this to ignore cooldown')
    elif command.lower() == '2':
        await ctx.send('I want this to have a Cooldown')```
</code>```

答:
```<code>@commands.cooldown(1, 30, commands.BucketType.user)
async def test(ctx, command=None):
    if command is None:
        await ctx.send('I want this to ignore cooldown')
        test.reset_cooldown(ctx)
    elif command.lower() == '2':
        await ctx.send('I want this to have a Cooldown')
</code>```

Essentially, exactly what the guy above said, but without the await. Tried the his code and it didn't work, luckily I was able to find sources that pointed me in the right directions.

ContentLicense: CC BY-SA 4.0

Title: Reset_cooldown Discord.py

Body:
Im pretty new to discord.py, and python in general but im trying to learn. I dont know how to add the command.reset_cooldown to my code. As it says in the code below, i want !test to ignore the cooldown but i want !test 2 to have the cooldown. Can someone help me?

@commands.cooldown(1, 30, commands.BucketType.user)
async def test(ctx, command=None):
    if command is None:
        await ctx.send('I want this to ignore cooldown')
    elif command.lower() == '2':
        await ctx.send('I want this to have a Cooldown')```

Body:
@commands.cooldown(1, 30, commands.BucketType.user)
async def test(ctx, command=None):
    if command is None:
        await ctx.send('I want this to ignore cooldown')
        test.reset_cooldown(ctx)
    elif command.lower() == '2':
        await ctx.send('I want this to have a Cooldown')

Essentially, exactly what the guy above said, but without the await. Tried the his code and it didn't work, luckily I was able to find sources that pointed me in the right directions.


问:
Angular BehaviorSubject not updating in time
i followed a tutorial on how to create a full Angular + JWT Authentication ( here is the link in case of need Angular 8 - JWT Authentication Example & Tutorial  ).
so after setting up the whole project and when i tried to test it i had some problems .
When i log in i need to send the response of the api to the AuthGuard via an BehaviorSubject object so i can notify him that i am connected and i can go to the next page but the problem is that the BehaviorSubject object is not updating its value instantly so i need to do the log in process twice so it works fine , i didn't know how to solve this problem even though i followed completely the tutorial .
ill show you my files :

my authentication serivce :

```<code>@Injectable({
  providedIn: 'root'
 })
 export class AuthenticationService {

 private currentUserSubject: BehaviorSubject<Dinosaure>;
 public currentUser: Observable<Dinosaure>;

 constructor(private http: HttpClient) {
            this.currentUserSubject = new BehaviorSubject<Dinosaure>
                  (JSON.parse(localStorage.getItem('currentUser')));
            this.currentUser = this.currentUserSubject.asObservable();

                   }

        logIn(dinosaure) {
             return this.http.post<any>(`${environment.apiUrl}/dinosaure/login`, dinosaure)
               .pipe(map(res => {
                     localStorage.setItem('currentUser', JSON.stringify(res));
                 //this.currentSubject.next(res) does not update the new value the first time i log
       in and then it works fine the second time i log in
                     this.currentUserSubject.next(res);
                     return res;
                     }));
                }

              public get currentUserValue(): Dinosaure {

                  return this.currentUserSubject.value;
                  }
</code>```

this is my AuthGuard :

```<code>     @Injectable({
         providedIn: 'root'
           })
       export class AuthGuard implements CanActivate {
       constructor(private router: Router,
       private authenticationService: AuthenticationService,
             ) {
            }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {

        // this.authenticationService.currentUserValue returns null the first time i log in and then it's full when i login a second time
      const currentUser = this.authenticationService.currentUserValue;
     if (currentUser) {

    return true;
   }
this.router.navigate(['/']);
return false;
 }

 }
</code>```

my login function in the login component :

```<code>onClickLogin() {
if (this.loginForm.valid) {
  const dinosaure = this.loginForm.value;
  this.dinosaure = {
    ...this.dinosaure,
    login: dinosaure.login,
    password: dinosaure.password
  };

  this.as.logIn(this.dinosaure).subscribe(data => {
    this.router.navigate([this.returnUrl]);
  });
}
</code>```

}

答:
I realized on your project available here: github.com/slim-aouadi/test-appartoo-front that you have added AuthenticationService into multiple modules, but also you have added the property providedIn: 'root'.

You have to remove AuthenticationService from all the modules and that's all. Why? Because you are creating multiple instances.

Edited:

I found AuthenticationService added into the array providers of AppModule and LoginComponent.

AppModule.ts

... code omitted
  imports: [
    BrowserModule,
    RouteModuleRoutingModule,
    RouterModule,
    HttpClientModule,
    ReactiveFormsModule

  ],
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: BasicAuthInterceptor, multi: true },
    { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true },

    // provider used to create fake backend
    AuthenticationService // <==== Remove it
  ],

  bootstrap: [AppComponent]
})
export class AppModule { }
```

<p>LoginComponent.ts</p>

<pre class="lang-js prettyprint-override"><code>... code omitted
import { Dinosaure } from 'src/entities/dinosaure';
import { first } from 'rxjs/operators';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css'],
  providers: [AuthenticationService] // <==== Remove it
})
export class LoginComponent implements OnInit {
... code omitted
}
</code>```

You need to remove AuthenticationService because of this service has the 'provided in' property with 'root'.

From Angular 6 there is now a new, recommended, way to register a provider, directly inside the @Injectable() decorator, using the new providedIn attribute. It accepts 'root' as a value or any module of your application. When you use 'root', your injectable will be registered as a singleton in the application, and you don’t need to add it to the providers of the root module. Similarly, if you use providedIn: UsersModule, the injectable is registered as a provider of the UsersModule without adding it to the providers of the module." - https://blog.ninja-squad.com/2018/05/04/what-is-new-angular-6/

Body:
i followed a tutorial on how to create a full Angular + JWT Authentication ( here is the link in case of need Angular 8 - JWT Authentication Example & Tutorial  ).
so after setting up the whole project and when i tried to test it i had some problems .
When i log in i need to send the response of the api to the AuthGuard via an BehaviorSubject object so i can notify him that i am connected and i can go to the next page but the problem is that the BehaviorSubject object is not updating its value instantly so i need to do the log in process twice so it works fine , i didn't know how to solve this problem even though i followed completely the tutorial .
ill show you my files :

my authentication serivce :

@Injectable({
  providedIn: 'root'
 })
 export class AuthenticationService {

 private currentUserSubject: BehaviorSubject<Dinosaure>;
 public currentUser: Observable<Dinosaure>;

 constructor(private http: HttpClient) {
            this.currentUserSubject = new BehaviorSubject<Dinosaure>
                  (JSON.parse(localStorage.getItem('currentUser')));
            this.currentUser = this.currentUserSubject.asObservable();

                   }

        logIn(dinosaure) {
             return this.http.post<any>(`${environment.apiUrl}/dinosaure/login`, dinosaure)
               .pipe(map(res => {
                     localStorage.setItem('currentUser', JSON.stringify(res));
                 //this.currentSubject.next(res) does not update the new value the first time i log
       in and then it works fine the second time i log in
                     this.currentUserSubject.next(res);
                     return res;
                     }));
                }

              public get currentUserValue(): Dinosaure {

                  return this.currentUserSubject.value;
                  }

this is my AuthGuard :

     @Injectable({
         providedIn: 'root'
           })
       export class AuthGuard implements CanActivate {
       constructor(private router: Router,
       private authenticationService: AuthenticationService,
             ) {
            }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {

        // this.authenticationService.currentUserValue returns null the first time i log in and then it's full when i login a second time
      const currentUser = this.authenticationService.currentUserValue;
     if (currentUser) {

    return true;
   }
this.router.navigate(['/']);
return false;
 }

 }

my login function in the login component :

onClickLogin() {
if (this.loginForm.valid) {
  const dinosaure = this.loginForm.value;
  this.dinosaure = {
    ...this.dinosaure,
    login: dinosaure.login,
    password: dinosaure.password
  };

  this.as.logIn(this.dinosaure).subscribe(data => {
    this.router.navigate([this.returnUrl]);
  });
}

}

Body:
I realized on your project available here: github.com/slim-aouadi/test-appartoo-front that you have added AuthenticationService into multiple modules, but also you have added the property providedIn: 'root'.

You have to remove AuthenticationService from all the modules and that's all. Why? Because you are creating multiple instances.

Edited:

I found AuthenticationService added into the array providers of AppModule and LoginComponent.

AppModule.ts

... code omitted
  imports: [
    BrowserModule,
    RouteModuleRoutingModule,
    RouterModule,
    HttpClientModule,
    ReactiveFormsModule

  ],
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: BasicAuthInterceptor, multi: true },
    { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true },

    // provider used to create fake backend
    AuthenticationService // <==== Remove it
  ],

  bootstrap: [AppComponent]
})
export class AppModule { }

LoginComponent.ts

... code omitted
import { Dinosaure } from 'src/entities/dinosaure';
import { first } from 'rxjs/operators';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css'],
  providers: [AuthenticationService] // <==== Remove it
})
export class LoginComponent implements OnInit {
... code omitted
}

You need to remove AuthenticationService because of this service has the 'provided in' property with 'root'.

From Angular 6 there is now a new, recommended, way to register a provider, directly inside the @Injectable() decorator, using the new providedIn attribute. It accepts 'root' as a value or any module of your application. When you use 'root', your injectable will be registered as a singleton in the application, and you don’t need to add it to the providers of the root module. Similarly, if you use providedIn: UsersModule, the injectable is registered as a provider of the UsersModule without adding it to the providers of the module." - https://blog.ninja-squad.com/2018/05/04/what-is-new-angular-6/


问:
Extract data from sample sheet with another sheet telling what factor to multiply the data and when to extract
I have three source sheets that show expected performance of three types of cities for 24 months (Small, Medium and Large).

Typical view - this tab's called small city sample.

I have a 'city launch' sheet. Essentially it is a matrix that shows a timeline of possible city launches, and amount of specific city launches in a month (factor + timeline spreading of sample sheet).

For example. Jan-20 2 small cities in country A, 1 large city in country A, 1 medium city in Country B etc, with a total (sumifs) at the top.

I'm trying to figure out a macro that based on the amount of 'cities' launched in the specific month (from city launch tab), extracts from city tabs, multiples by the factors, then spreads and adds preceding data in to the consolidated tab.

The data in  is static, as they are the base.

The consolidated tab is essentially a detailed version of sample city tabs where the 'levers' are essentially in .

How could I attempt this?

答: I would look at writing a function in the Consolidated tab which takes in the "small", "medium" and "large" tables as arguments and then takes the city/size as an argument too. Then use the city/size argument to look at the relevant small/medium/large table and iterate over the headers to find the correct factor then carry out your arithmetic in the function</p>


问:
Sum values in double nested List of Dictionaries in C#
I have (for certain reasons not to get into now...) a List of the following structure:

```<code>List1<Dictionary1<string, List2<Dictionary2<string, string>>>>
</code>```

(I added the 1 and 2 naming for clarity).
I want to iterate over List1 and sum up Dictionary1, so that all values of identical keys in Dictionary2 will add up.

For example if each Dictionary1 item contains a Dictionary2:
{ "Price", 23},
{ "Customers", 3}

then I want to iterate over all List2 elements, and over all List1 elements, and have a final dictionary of the total sum of all prices and customers as a single key for each category:
{ "Price", 15235},
{ "Customers", 236}

I hope that's clear.. In other words, I want to sum up this double-nested list in a way that I'm left with all unique keys across all nested dictionaries and have the values summed up.

I believe it can be done with LINQ, but I'm not sure how to do that..

答:
This may be the ugliest thing I've ever written, and makes some assumptions on what you're doing, but I think this gets you what you want:

```<code>var query = from outerDictionary in x
            from listOfDictionaries in outerDictionary.Values
            from innerDictionary in listOfDictionaries
            from keyValuePairs in innerDictionary
            group keyValuePairs by keyValuePairs.Key into finalGroup
            select new
            {
                Key = finalGroup.Key,
                Sum = finalGroup.Sum(a => Convert.ToInt32(a.Value))
            };
</code>```

Where x is your main List.

Body:
I have (for certain reasons not to get into now...) a List of the following structure:

List1<Dictionary1<string, List2<Dictionary2<string, string>>>>

(I added the 1 and 2 naming for clarity).
I want to iterate over List1 and sum up Dictionary1, so that all values of identical keys in Dictionary2 will add up.

For example if each Dictionary1 item contains a Dictionary2:
{ "Price", 23},
{ "Customers", 3}

then I want to iterate over all List2 elements, and over all List1 elements, and have a final dictionary of the total sum of all prices and customers as a single key for each category:
{ "Price", 15235},
{ "Customers", 236}

I hope that's clear.. In other words, I want to sum up this double-nested list in a way that I'm left with all unique keys across all nested dictionaries and have the values summed up.

I believe it can be done with LINQ, but I'm not sure how to do that..

Body:
This may be the ugliest thing I've ever written, and makes some assumptions on what you're doing, but I think this gets you what you want:

var query = from outerDictionary in x
            from listOfDictionaries in outerDictionary.Values
            from innerDictionary in listOfDictionaries
            from keyValuePairs in innerDictionary
            group keyValuePairs by keyValuePairs.Key into finalGroup
            select new
            {
                Key = finalGroup.Key,
                Sum = finalGroup.Sum(a => Convert.ToInt32(a.Value))
            };

Where x is your main List.


问:
Decorating a function to create a class that splits keyword and positional arguments into two other methods
I have an abstract class that @abstractmethods its __init__ and __call__. In principle, the class definition is like this:

```<code>class Base(abc.ABC):
    @abc.abstractmethod
    def __init__(self, **params):
        pass

    @abc.abstractmethod
    def __call__(self, *input):
        pass
</code>```

I want to create a decorator that converts a function's keyword arguments into arguments into __init__ and positional arguments into __call__: so if

```<code>def func(a, b, *args, k=1, g=2, **kwargs):
    pass # it does something
</code>```

then I would like to wrap my func in a decorator that will output like along the lines of

class Func(Base):
    def __init__(self, k=1, g=2, **kwargs):
        inspected_kwargs = ... # arguments of init in dictionary form
        for argname, val in inspected_kwargs.items():
             setattr(self, argname, val)

    def __call__(self, a, b, *args):
        inspected_args = ... # arguments of call in tuple form
        return func(*inspected_args, **self.__dict__)

```

<p>I had a few attempts using <code>inspect</code> but I'm not sure how to inject the parameters from <code>inspect.Signature</code> object back to create a function. Also, I had some trouble because when local methods are added to a class that is inner to a function with simple attribute setting, the local functions are no longer in scope when the class is returned.</p>

<p>The question is: how to create a class inside a function whose methods are defined based on the signature of the function's input callable?</p>

<p>@edit
To provide more details on the idea:</p>

<pre class="lang-py prettyprint-override"><code>def decorator(function):
    class Inner(Base):
        pass
    # non-existent functions ahead, just to convey the idea
    # the exact way to do this is exactly the matter of this question
    sig = inspect.get_signature(function)
    init = create_from_signature(signature=sig.keyword_arguments(),
body="for name, val in sig.keyword_arguments():\nsetattr(self, name, val)")
    call = create_from_signature(signature=sig.positional(),
body="return partial(func, **self.__dict__)")
    Inner.__init__ = init
    Inner.__call__ = call
    # it would be nice if Inner class name would also depend on
    # func name:
    setattr(Inner, __name__, "_".join(function.__name__, "decorated"))
    return Inner

def users_function(a, b, k=5):
    # user's code; does whatever, for me it's a black box
    return a * b / k
</code>```

Expected behaviour:

```<code>decorator(users_function)(k=10)(1, 2) == users_function(1, 2, k=10)
</code>```

Why do I want to do this? Because then one can call the methods of Base on the outputted object, for which knowledge of only keyword arguments would be required:

```<code>my_obj = decorator(users_function)(k=10)
my_obj.basemethod() # basemethod is implementd in Base class
</code>```

答:
I am trying to understand exactly what your problem is so let's start with this example:

```<code>def decorator(function):

    def wrapper(*args, **kwargs):

        print(' [decorator] Printing before function [' + function.__name__ + '] execution')

        result = function(*args, **kwargs)

        print(' [decorator] Found args: ' + str(args))
        print(' [decorator] Found kwargs: ' + str(kwargs))

        print(' [decorator] Printing after function [' + function.__name__ + '] execution')

        return result

    return wrapper

@decorator
def MyFunction(*args, **kwargs):

    print('[MyFunction] Received args:' + str(args))
    print('[MyFunction] Received kwargs:' + str(kwargs))

MyFunction(1, 2, kwarg1=3, kwarg2=2)
</code>```

It will result in:

```<code> [decorator] Printing before function [MyFunction] execution
[MyFunction] Received args:(1, 2)
[MyFunction] Received kwargs:{'kwarg1': 3, 'kwarg2': 2}
 [decorator] Found args: (1, 2)
 [decorator] Found kwargs: {'kwarg1': 3, 'kwarg2': 2}
 [decorator] Printing after function [MyFunction] execution
</code>```

Where do you need to take your problem from here?

Body:
I have an abstract class that @abstractmethods its __init__ and __call__. In principle, the class definition is like this:

class Base(abc.ABC):
    @abc.abstractmethod
    def __init__(self, **params):
        pass

    @abc.abstractmethod
    def __call__(self, *input):
        pass

I want to create a decorator that converts a function's keyword arguments into arguments into __init__ and positional arguments into __call__: so if

def func(a, b, *args, k=1, g=2, **kwargs):
    pass # it does something

then I would like to wrap my func in a decorator that will output like along the lines of

class Func(Base):
    def __init__(self, k=1, g=2, **kwargs):
        inspected_kwargs = ... # arguments of init in dictionary form
        for argname, val in inspected_kwargs.items():
             setattr(self, argname, val)

    def __call__(self, a, b, *args):
        inspected_args = ... # arguments of call in tuple form
        return func(*inspected_args, **self.__dict__)

I had a few attempts using inspect but I'm not sure how to inject the parameters from inspect.Signature object back to create a function. Also, I had some trouble because when local methods are added to a class that is inner to a function with simple attribute setting, the local functions are no longer in scope when the class is returned.

The question is: how to create a class inside a function whose methods are defined based on the signature of the function's input callable?

@edit
To provide more details on the idea:

def decorator(function):
    class Inner(Base):
        pass
    # non-existent functions ahead, just to convey the idea
    # the exact way to do this is exactly the matter of this question
    sig = inspect.get_signature(function)
    init = create_from_signature(signature=sig.keyword_arguments(),
body="for name, val in sig.keyword_arguments():\nsetattr(self, name, val)")
    call = create_from_signature(signature=sig.positional(),
body="return partial(func, **self.__dict__)")
    Inner.__init__ = init
    Inner.__call__ = call
    # it would be nice if Inner class name would also depend on
    # func name:
    setattr(Inner, __name__, "_".join(function.__name__, "decorated"))
    return Inner

def users_function(a, b, k=5):
    # user's code; does whatever, for me it's a black box
    return a * b / k

Expected behaviour:

decorator(users_function)(k=10)(1, 2) == users_function(1, 2, k=10)

Why do I want to do this? Because then one can call the methods of Base on the outputted object, for which knowledge of only keyword arguments would be required:

my_obj = decorator(users_function)(k=10)
my_obj.basemethod() # basemethod is implementd in Base class

Body:
I am trying to understand exactly what your problem is so let's start with this example:

def decorator(function):

    def wrapper(*args, **kwargs):

        print(' [decorator] Printing before function [' + function.__name__ + '] execution')

        result = function(*args, **kwargs)

        print(' [decorator] Found args: ' + str(args))
        print(' [decorator] Found kwargs: ' + str(kwargs))

        print(' [decorator] Printing after function [' + function.__name__ + '] execution')

        return result

    return wrapper

@decorator
def MyFunction(*args, **kwargs):

    print('[MyFunction] Received args:' + str(args))
    print('[MyFunction] Received kwargs:' + str(kwargs))

MyFunction(1, 2, kwarg1=3, kwarg2=2)

It will result in:

 [decorator] Printing before function [MyFunction] execution
[MyFunction] Received args:(1, 2)
[MyFunction] Received kwargs:{'kwarg1': 3, 'kwarg2': 2}
 [decorator] Found args: (1, 2)
 [decorator] Found kwargs: {'kwarg1': 3, 'kwarg2': 2}
 [decorator] Printing after function [MyFunction] execution

Where do you need to take your problem from here?


问:
How can I find the count of semicolon separated values?
I have a list of all email ids which I have copied from the 'To' field, from an email I received in MS Outlook. These values (email ids) are separated by a semicolon. I have copied this big list of email ids into Excel. Now I want to find the number of email ids in this list; basically by counting the number of semi colons.

One way I can do this is by writing C code. i.e. store the big list as string buffer, and keep comparing the chars to ";" in a while(char == ';') loop.
But I want to do it quickly.

Is there any quick way to find that out using either:

1.) Regular expression (I use powergrep for processing the regexps)

2.) In excel itself (any excel macro/plugin for that?)

3.) DOS script method

4.) Any other quick way of getting it done?

答:
Bash/Cygwin One-Liner

```<code>$ echo "user@domain.tld;user@domain.tld;user@domain.tld" | sed -e 's/;/\n/g' | wc -l
3
</code>```

If you already have Cygwin installed it's effectively instant.  If not, cygwin is worth installing IMHO.  It basically provides a Linux bash prompt overlaid over your Windows system.

As an aside, stuff like this is why I prefer *nix over Windows for work stuff, I can't live on a windows box without Cygwin since bash scripts are so much more powerful than batch scripts.

OwnerDisplayName: goldenmean

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Svante

Body:
Bash/Cygwin One-Liner

$ echo "user@domain.tld;user@domain.tld;user@domain.tld" | sed -e 's/;/\n/g' | wc -l
3

If you already have Cygwin installed it's effectively instant.  If not, cygwin is worth installing IMHO.  It basically provides a Linux bash prompt overlaid over your Windows system.

As an aside, stuff like this is why I prefer *nix over Windows for work stuff, I can't live on a windows box without Cygwin since bash scripts are so much more powerful than batch scripts.

OwnerDisplayName: cynoclast


问:
problem in submitting form to cgi file
I coded a CMS for a client everything is ok except client said:

Use his previous shopping cart and embed that into the new design. The previous shopping cart file is shopper.cgi and I want to submit my form to that shopper.cgi

When I do this the file open dialog opens asking me to save the file or open the file.

Can someone suggest how can I make my form submit to shopper.cgi? I am running wamp server than ks

答:
Your web server isn't configured to interpret/execute .cgi files. If you are running apache, add an AddHandler cgi-script clause in your .htaccess or server config:</p>

```<code>AddHandler cgi-script .cgi
</code>```

ContentLicense: CC BY-SA 3.0

Title: problem in submitting form to cgi file

Body:
Your web server isn't configured to interpret/execute .cgi files. If you are running apache, add an AddHandler cgi-script clause in your .htaccess or server config:

AddHandler cgi-script .cgi


问:
Why does the class deduction guide fail when using a typedef?
In a piece of the code I currently write I make use of a class deduction guide. You can find the excerpt of the code stripped down to a simple (but meaningless example) below:
I've got a class User, which derives its first template parameter from the constructor's first argument, and the second one from the size of the parameter pack provided as second argument:

#include <cstddef>
#include <type_traits>

/// First constructor parameter, which can be used in order to derive the boolean
template <int, bool switcher> struct P1 {};

/// Class which depends on the boolean flag (from first parameter) and the amount of elements provided.
template <bool switcher, size_t amountKids> struct User {
  template <int p1, int... pn> explicit constexpr User(P1<p1, switcher> &child,
      P1<pn, switcher>... parents) noexcept {}
};

/// Deduction guide
template <bool f, int p1, int... pn> User(P1<p1, f> &child, P1<pn, f> ...) ->User<f, sizeof...(pn) + 1>;

int main() {
  P1<1, true> child;
  User sa{child, P1<1, true>{}};
  User sa2{child, child, child};
}
```

<p>This works fine (compiles). When I make a tiny modification by replacing the parameter pack's type by a type that depends on the template parameter <code>switcher</code> however, the deduction fails: </p>

<pre class="lang-cpp prettyprint-override"><code>#include <cstddef>
#include <type_traits>

/// First constructor parameter, which can be used in order to derive the boolean
template <int, bool switcher> struct P1 {};

/// In the real example, conditional_type holds a different type, depending on the #bool
template <bool, typename T> struct conditional_type { using type = T; };
template <bool switcher, typename T> using conditional_type_t = typename conditional_type<switcher, T>::type;

template <bool switcher, size_t amountKids> struct User {
  template <int p1, int... pn> explicit constexpr User(P1<p1, switcher> &child,
      conditional_type_t<switcher, P1<pn, switcher>>... parents) noexcept {}
};

template <bool f, int p1, int... pn> User(P1<p1, f> &child, conditional_type_t<f, P1<pn, f>>...) ->User<f, sizeof...(pn) + 1>;

int main() {
  conditional_type_t<true, P1<1, true>> child2;
  P1<1, true> child;
  static_assert(std::is_same_v<decltype(child), decltype(child2)>);

  User sa{child, P1<1, true>{}}; //< fails: 2 arguments provided, expecting one, can't derive amountKids
  User sa2{child, child, child}; //< fails:
}
</code>```

Why is that?

Both variants of the code can be found here.

答:
Your deduction guide in the second example is equivalent to what we get substituting the alias:

```<code>template <bool f, int p1, int... pn>
User(P1<p1, f> &child, typename conditional_type<f, P1<pn, f>>::type ...)
    -> User<f, sizeof...(pn) + 1>;
</code>```

In any syntax typename A::B where A is a dependent type, the type A is a non-deduced context. Since pn only appears in a non-deduced context, it can never be deduced, so that deduction guide can never be used.

For a similar reason, the constructor of User can never be used with more than one argument, even if template arguments for User are explicitly specified.

Body:
In a piece of the code I currently write I make use of a class deduction guide. You can find the excerpt of the code stripped down to a simple (but meaningless example) below:
I've got a class User, which derives its first template parameter from the constructor's first argument, and the second one from the size of the parameter pack provided as second argument:

#include <cstddef>
#include <type_traits>

/// First constructor parameter, which can be used in order to derive the boolean
template <int, bool switcher> struct P1 {};

/// Class which depends on the boolean flag (from first parameter) and the amount of elements provided.
template <bool switcher, size_t amountKids> struct User {
  template <int p1, int... pn> explicit constexpr User(P1<p1, switcher> &child,
      P1<pn, switcher>... parents) noexcept {}
};

/// Deduction guide
template <bool f, int p1, int... pn> User(P1<p1, f> &child, P1<pn, f> ...) ->User<f, sizeof...(pn) + 1>;

int main() {
  P1<1, true> child;
  User sa{child, P1<1, true>{}};
  User sa2{child, child, child};
}

This works fine (compiles). When I make a tiny modification by replacing the parameter pack's type by a type that depends on the template parameter switcher however, the deduction fails:

#include <cstddef>
#include <type_traits>

/// First constructor parameter, which can be used in order to derive the boolean
template <int, bool switcher> struct P1 {};

/// In the real example, conditional_type holds a different type, depending on the #bool
template <bool, typename T> struct conditional_type { using type = T; };
template <bool switcher, typename T> using conditional_type_t = typename conditional_type<switcher, T>::type;

template <bool switcher, size_t amountKids> struct User {
  template <int p1, int... pn> explicit constexpr User(P1<p1, switcher> &child,
      conditional_type_t<switcher, P1<pn, switcher>>... parents) noexcept {}
};

template <bool f, int p1, int... pn> User(P1<p1, f> &child, conditional_type_t<f, P1<pn, f>>...) ->User<f, sizeof...(pn) + 1>;

int main() {
  conditional_type_t<true, P1<1, true>> child2;
  P1<1, true> child;
  static_assert(std::is_same_v<decltype(child), decltype(child2)>);

  User sa{child, P1<1, true>{}}; //< fails: 2 arguments provided, expecting one, can't derive amountKids
  User sa2{child, child, child}; //< fails:
}

Why is that?

Both variants of the code can be found here.

Body:
Your deduction guide in the second example is equivalent to what we get substituting the alias:

template <bool f, int p1, int... pn>
User(P1<p1, f> &child, typename conditional_type<f, P1<pn, f>>::type ...)
    -> User<f, sizeof...(pn) + 1>;

In any syntax typename A::B where A is a dependent type, the type A is a non-deduced context. Since pn only appears in a non-deduced context, it can never be deduced, so that deduction guide can never be used.

For a similar reason, the constructor of User can never be used with more than one argument, even if template arguments for User are explicitly specified.


问:
How to change cursor style in Amchart's stacked LineSeries
I know how to change them in ColumnSeries and PieSeries, via:

series.slices.template.cursorOverStyle = am4core.MouseCursorStyle.pointer

or

series.columns.template.cursorOverStyle = am4core.MouseCursorStyle.pointer

But I cannot make it work in stacked LineSeries.

答:
You need to set this on the LineSeries' segments template. This also requires enabling interactions on it as they are disabled by default:

```<code>series.segments.template.interactionsEnabled = true;
series.segments.template.cursorOverStyle = am4core.MouseCursorStyle.pointer;
</code>```

Demo:

var chart = am4core.create("chartdiv", am4charts.XYChart);

chart.data = [{
  "year": "1994",
  "cars": 1587,
  "motorcycles": 650,
  "bicycles": 121
}, {
  "year": "1995",
  "cars": 1567,
  "motorcycles": 683,
  "bicycles": 146
}, {
  "year": "1996",
  "cars": 1617,
  "motorcycles": 691,
  "bicycles": 138
}, {
  "year": "1997",
  "cars": 1630,
  "motorcycles": 642,
  "bicycles": 127
}, {
  "year": "1998",
  "cars": 1660,
  "motorcycles": 699,
  "bicycles": 105
}, {
  "year": "1999",
  "cars": 1683,
  "motorcycles": 721,
  "bicycles": 109
}, {
  "year": "2000",
  "cars": 1691,
  "motorcycles": 737,
  "bicycles": 112
}, {
  "year": "2001",
  "cars": 1298,
  "motorcycles": 680,
  "bicycles": 101
}, {
  "year": "2002",
  "cars": 1275,
  "motorcycles": 664,
  "bicycles": 97
}, {
  "year": "2003",
  "cars": 1246,
  "motorcycles": 648,
  "bicycles": 93
}, {
  "year": "2004",
  "cars": 1318,
  "motorcycles": 697,
  "bicycles": 111
}, {
  "year": "2005",
  "cars": 1213,
  "motorcycles": 633,
  "bicycles": 87
}, {
  "year": "2006",
  "cars": 1199,
  "motorcycles": 621,
  "bicycles": 79
}, {
  "year": "2007",
  "cars": 1110,
  "motorcycles": 210,
  "bicycles": 81
}, {
  "year": "2008",
  "cars": 1165,
  "motorcycles": 232,
  "bicycles": 75
}, {
  "year": "2009",
  "cars": 1145,
  "motorcycles": 219,
  "bicycles": 88
}, {
  "year": "2010",
  "cars": 1163,
  "motorcycles": 201,
  "bicycles": 82
}, {
  "year": "2011",
  "cars": 1180,
  "motorcycles": 285,
  "bicycles": 87
}, {
  "year": "2012",
  "cars": 1159,
  "motorcycles": 277,
  "bicycles": 71
}];

var categoryAxis = chart.xAxes.push(new am4charts.CategoryAxis());
categoryAxis.dataFields.category = "year"

var valueAxis = chart.yAxes.push(new am4charts.ValueAxis());

var series = chart.series.push(new am4charts.LineSeries());
series.dataFields.categoryX = "year";
series.name = "cars";
series.dataFields.valueY = "cars";
series.tooltipText = "[#000]{valueY.value}[/]";
series.fillOpacity = 0.6;
series.strokeWidth = 2;
series.stacked = true;
series.segments.template.interactionsEnabled = true;
series.segments.template.cursorOverStyle = am4core.MouseCursorStyle.pointer;

var series2 = chart.series.push(new am4charts.LineSeries());
series2.name = "motorcycles";
series2.dataFields.categoryX = "year";
series2.dataFields.valueY = "motorcycles";
series2.tooltipText = "[#000]{valueY.value}[/]";
series2.fillOpacity = 0.6;
series2.stacked = true;
series2.strokeWidth = 2;
series2.segments.template.interactionsEnabled = true;
series2.segments.template.cursorOverStyle = am4core.MouseCursorStyle.pointer;

var series3 = chart.series.push(new am4charts.LineSeries());
series3.name = "bicycles";
series3.dataFields.categoryX = "year";
series3.dataFields.valueY = "bicycles";
series3.tooltipText = "[#000]{valueY.value}[/]";
series3.fillOpacity = 0.6;
series3.stacked = true;
series3.strokeWidth = 2;
series3.segments.template.interactionsEnabled = true;
series3.segments.template.cursorOverStyle = am4core.MouseCursorStyle.pointer;

chart.cursor = new am4charts.XYCursor();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://www.amcharts.com/lib/4/core.js"></script>
<script src="https://www.amcharts.com/lib/4/charts.js"></script>
<div id="chartdiv" style="width: 100%; height: 300px;"></div></code>```

Body:
You need to set this on the LineSeries' segments template. This also requires enabling interactions on it as they are disabled by default:

series.segments.template.interactionsEnabled = true;
series.segments.template.cursorOverStyle = am4core.MouseCursorStyle.pointer;

Demo:

var chart = am4core.create("chartdiv", am4charts.XYChart);

chart.data = [{
  "year": "1994",
  "cars": 1587,
  "motorcycles": 650,
  "bicycles": 121
}, {
  "year": "1995",
  "cars": 1567,
  "motorcycles": 683,
  "bicycles": 146
}, {
  "year": "1996",
  "cars": 1617,
  "motorcycles": 691,
  "bicycles": 138
}, {
  "year": "1997",
  "cars": 1630,
  "motorcycles": 642,
  "bicycles": 127
}, {
  "year": "1998",
  "cars": 1660,
  "motorcycles": 699,
  "bicycles": 105
}, {
  "year": "1999",
  "cars": 1683,
  "motorcycles": 721,
  "bicycles": 109
}, {
  "year": "2000",
  "cars": 1691,
  "motorcycles": 737,
  "bicycles": 112
}, {
  "year": "2001",
  "cars": 1298,
  "motorcycles": 680,
  "bicycles": 101
}, {
  "year": "2002",
  "cars": 1275,
  "motorcycles": 664,
  "bicycles": 97
}, {
  "year": "2003",
  "cars": 1246,
  "motorcycles": 648,
  "bicycles": 93
}, {
  "year": "2004",
  "cars": 1318,
  "motorcycles": 697,
  "bicycles": 111
}, {
  "year": "2005",
  "cars": 1213,
  "motorcycles": 633,
  "bicycles": 87
}, {
  "year": "2006",
  "cars": 1199,
  "motorcycles": 621,
  "bicycles": 79
}, {
  "year": "2007",
  "cars": 1110,
  "motorcycles": 210,
  "bicycles": 81
}, {
  "year": "2008",
  "cars": 1165,
  "motorcycles": 232,
  "bicycles": 75
}, {
  "year": "2009",
  "cars": 1145,
  "motorcycles": 219,
  "bicycles": 88
}, {
  "year": "2010",
  "cars": 1163,
  "motorcycles": 201,
  "bicycles": 82
}, {
  "year": "2011",
  "cars": 1180,
  "motorcycles": 285,
  "bicycles": 87
}, {
  "year": "2012",
  "cars": 1159,
  "motorcycles": 277,
  "bicycles": 71
}];

var categoryAxis = chart.xAxes.push(new am4charts.CategoryAxis());
categoryAxis.dataFields.category = "year"

var valueAxis = chart.yAxes.push(new am4charts.ValueAxis());

var series = chart.series.push(new am4charts.LineSeries());
series.dataFields.categoryX = "year";
series.name = "cars";
series.dataFields.valueY = "cars";
series.tooltipText = "[#000]{valueY.value}[/]";
series.fillOpacity = 0.6;
series.strokeWidth = 2;
series.stacked = true;
series.segments.template.interactionsEnabled = true;
series.segments.template.cursorOverStyle = am4core.MouseCursorStyle.pointer;

var series2 = chart.series.push(new am4charts.LineSeries());
series2.name = "motorcycles";
series2.dataFields.categoryX = "year";
series2.dataFields.valueY = "motorcycles";
series2.tooltipText = "[#000]{valueY.value}[/]";
series2.fillOpacity = 0.6;
series2.stacked = true;
series2.strokeWidth = 2;
series2.segments.template.interactionsEnabled = true;
series2.segments.template.cursorOverStyle = am4core.MouseCursorStyle.pointer;

var series3 = chart.series.push(new am4charts.LineSeries());
series3.name = "bicycles";
series3.dataFields.categoryX = "year";
series3.dataFields.valueY = "bicycles";
series3.tooltipText = "[#000]{valueY.value}[/]";
series3.fillOpacity = 0.6;
series3.stacked = true;
series3.strokeWidth = 2;
series3.segments.template.interactionsEnabled = true;
series3.segments.template.cursorOverStyle = am4core.MouseCursorStyle.pointer;

chart.cursor = new am4charts.XYCursor();

<script src="https://www.amcharts.com/lib/4/core.js"></script>
<script src="https://www.amcharts.com/lib/4/charts.js"></script>
<div id="chartdiv" style="width: 100%; height: 300px;"></div>


问:
How to replace Boolean value with adjecent row value from same dataframe
I got a Boolean value after comparing row value. I want to replace the Boolean value with the adjacent row value from the same dataframe.

```<code>import pandas as pd
import numpy as np
import glob
import os
    stock_files = glob.glob("E:/Python full3files/*.csv")
    dd= pd.concat((pd.read_csv(file,header= None, prefix= 'col', usecols=[1,5,6,7])
              for file in stock_files),ignore_index= True)
    ss= dd.loc[dd.col1 =="RELIANCE",:]
    ss['Daily'] = pd.to_datetime(ss['col7']).dt.day
    ss['Daily Day'] =  ss.Daily> ss.Daily.shift(1)
    #ss['Daily Day'] = ss.where(ss['Daily']> ss['Daily'].shift(1), ss['col5'].shift(1))
    print(ss)
</code>```

答: df[df[Daily Day==True]]=df[Col6]</p>

Body:
I got a Boolean value after comparing row value. I want to replace the Boolean value with the adjacent row value from the same dataframe.

import pandas as pd
import numpy as np
import glob
import os
    stock_files = glob.glob("E:/Python full3files/*.csv")
    dd= pd.concat((pd.read_csv(file,header= None, prefix= 'col', usecols=[1,5,6,7])
              for file in stock_files),ignore_index= True)
    ss= dd.loc[dd.col1 =="RELIANCE",:]
    ss['Daily'] = pd.to_datetime(ss['col7']).dt.day
    ss['Daily Day'] =  ss.Daily> ss.Daily.shift(1)
    #ss['Daily Day'] = ss.where(ss['Daily']> ss['Daily'].shift(1), ss['col5'].shift(1))
    print(ss)

Body: df[df[Daily Day==True]]=df[Col6]


问:
How to match only one alphabetical word
This is the second part of a longer regex I need to write, and somehow the "harder" half of the regex I have written works just fine. What I'm trying to achieve is a match for only alphabetic characters in one word. However, what I need to handle / desired output would be like this:

```<code>"abc"     // matches
"ABC"     // matches
"abc123"  // does not match
"abc[]"   // does not match
"abc abc" // does not match
</code>```

What I've tried so far that gets close is this:

\b[A-Za-z]+\b

However, this somehow matches "abc[]" and also matches double words like "abc abc". Any ideas on how to achieve this? Something to note, I'm using go for this problem, which doesn't seem to support capture groups very well.

答:
If I understand your use case correctly, I think your regex is as simple as the following conditions:

Any character A through Z, case insensitive, one or more times.

Boundaries at the start and end of the line.

^[a-zA-Z]+$

https://regex101.com/r/lilPqT/1

Note on RegEx101.com that you can test your cases using Golang, and the full regex for Go is:

`(?m)^[a-zA-Z]+$`

https://regex101.com/r/lilPqT/1/codegen?language=golang

Title: How to match only one alphabetical word

Body:
This is the second part of a longer regex I need to write, and somehow the "harder" half of the regex I have written works just fine. What I'm trying to achieve is a match for only alphabetic characters in one word. However, what I need to handle / desired output would be like this:

"abc"     // matches
"ABC"     // matches
"abc123"  // does not match
"abc[]"   // does not match
"abc abc" // does not match

What I've tried so far that gets close is this:

\b[A-Za-z]+\b

However, this somehow matches "abc[]" and also matches double words like "abc abc". Any ideas on how to achieve this? Something to note, I'm using go for this problem, which doesn't seem to support capture groups very well.


问:
Cooperation in Twisted - yield the execution context
Below is my testbed

```<code>from twisted.internet import defer, task

@defer.inlineCallbacks
def foo():
    yield
    print 'after yield in foo'

@defer.inlineCallbacks
def main(reactor):
    d = foo()
    yield
    print 'after yield in main'
    yield d

task.react(main)
</code>```

I exepect that the yield statement will make the function to "yield the exeuction context" (whatever that means in Twisted) and let another deferred to take over the execution. For that particular example I expect that main() starts the execution, calls foo(), which being wrapped with inlineCallbacks is turned into a deferred, then yields the execution letting foo() to eventually start. Then foo() in its turn yields the execution too, so ultimately the order of printed lines should be

```<code>after yield in main
after yield in foo
</code>```

For some reason the output is

```<code>after yield in foo
after yield in main
</code>```

What is the right way to implement cooperative multi-tasking in Twisted and let the execution context go to another deferred in line?

答:
I exepect that the yield statement will make the function to "yield the exeuction context" (whatever that means in Twisted) and let another deferred to take over the execution.

From your observations, I take it you have been disabused of this expectation by now.  To be perfectly clear, this is not what yield does in a generator function decorated by inlineCallbacks.

What yield does in such a function is pass a value out to a trampoline.  If the value is a Deferred, the trampoline suspends execution of the generator until the Deferred fires.  If the value is not a Deferred, or when the Deferred fires with a value, the generator is resumed with that value sent in to it.

So, since yield is the same as yield None and None is not a Deferred, these yield expressions are just an expensive way to say None.

This also gives you some idea of how to achieve what you say you're after.  To suspend execution, yield a Deferred that does not fire until you want execution to resume.

What is the right way to implement cooperative multi-tasking in Twisted and let the execution context go to another deferred in line?

There are many possibly correct ways to do this.  The specifics depend more on your specific application requirements.

Unfortunately, there are some easily explained cheesy answers which might seem correct but which will probably ultimately lead to poor performance and costly maintenance.  For example, you can suspend for "a reactor iteration" (to the extent such a thing exists, which may be less so than you believe).  To do this, yield twisted.internet.task.deferLater(reactor, 0.0, lambda: None).  This expression makes a Deferred that fires no sooner than "zero seconds" from now but also with the constraint that it doesn't fire right now.

However, this lets the whole reactor implementation have a chance at doing work before your generator is resumed - even if there is no other work to do.  Thus, you're paying a large CPU cost for the possibility of being cooperative.  Furthermore, it makes the function difficult to test by introducing time-based scheduling interactions.

An alternative that Twisted offers to try to cope with some of these difficulties is twisted.internet.task.cooperate which drops inlineCallbacks in favor of bare generators.  These actually do use yield to offer suspend-points but do so in a way that doesn't give the whole reactor a chance to run before resuming.  This addresses some CPU concerns and possibly some maintenance difficulties, though ultimately it still introduces some time-based dependencies.  However, it is at least possible to operate on the bare generators without involving cooperate which mitigates this difficulty to some extent (compare this with inlineCallbacks where idiomatically written code destroys the underlying generator and only offers a function that returns a Deferred up for testing).

Body:
Below is my testbed

from twisted.internet import defer, task

@defer.inlineCallbacks
def foo():
    yield
    print 'after yield in foo'

@defer.inlineCallbacks
def main(reactor):
    d = foo()
    yield
    print 'after yield in main'
    yield d

task.react(main)

I exepect that the yield statement will make the function to "yield the exeuction context" (whatever that means in Twisted) and let another deferred to take over the execution. For that particular example I expect that main() starts the execution, calls foo(), which being wrapped with inlineCallbacks is turned into a deferred, then yields the execution letting foo() to eventually start. Then foo() in its turn yields the execution too, so ultimately the order of printed lines should be

after yield in main
after yield in foo

For some reason the output is

after yield in foo
after yield in main

What is the right way to implement cooperative multi-tasking in Twisted and let the execution context go to another deferred in line?


问:
Question about customizing spring security 2.0.4
Hi all I have the following requirement: The user will login to the system using olny his/her password and redirected to different pages depending his/her role (roles are DENTIST,DOCTOR,PHARMASIST).Are there any resources on how to use spring sequirity with  one-field login form and multiple default-target-urls? Any help would be really appriciated because googling the subject wasn't very useful... Thanx in advance</p>

答:
What about using this approach:

Create a controller with mapping "/login-successful" and redirect successful logins to it. In this controller you identify the role of the user and then redirect him/her to the appropriate page.


问:
What is the best way to import a component from another module, in AngularJS?
I have 2 sub-modules in my AngularJS (v1.7) app, let's call them A and B. I'm trying to import a component (with html template and controller) from module B (componentB), to be used inside the template of a component in module A (componentA).

After reading Reuse AngularJS Component in another Module (Dependency Injection), I first tried to do this by specifying componentB as a dependency of componentA and then using it inside componentA's template.

componentA.js

```<code>angular.module('A', ['componentB']).component('componentA', {...});
</code>```

componentA.html

```<code><div>
   <componentB></componentB>
</div>
</code>```

Unfortunately this did not work, even though componentB is correctly defined and being successfully used in module B. I also tried to specify module B as a dependency of module A, by modifying app.js as shown below:

```<code>angular.module('A', ['B'])
.config(...
</code>```

In both cases, I'm getting an

Uncaught Error: [$injector:modulerr]

I'm having a hard time finding similar questions/articles that relate to AngularJS as opposed to the newer Angular. I'm also pretty rusty with AngularJS so any help would be appreciated, thanks in advance.

答:
It is pretty straight forward:

```<code>angular.module("moduleB",[])
.component("componentB", {
     template: "<div>This is Component B from Module B</div>"
});

angular.module("moduleA",["moduleB"])
</code>```

```<code><div ng-app="moduleA">
    <component-b></component-b>
</div>
</code>```

The moduleA imports components from moduleB by declaring moduleB as a dependency.

Module Creation vs Retrieval

Only the first module declaration should have dependencies specified.

ERRONEOUS

```<code>angular.module('moduleA', [])
.controller('ctrl', /* ... */)

angular.module('moduleA', ['moduleB'])
.service('serviceA', /* ... */)
</code>```

Declaring dependencies again will cause the controller to be unregistered.

Better

```<code>angular.module('moduleA', ['moduleB'])

angular.module('moduleA')
.controller('ctrl', /* ... */)

angular.module('moduleA')
.service('serviceA', /* ... */)
</code>```

For more information, see

AngularJS Developer Guide - Module Creation vs Retrieval

AngularJS angular.module API Reference

Body:
I have 2 sub-modules in my AngularJS (v1.7) app, let's call them A and B. I'm trying to import a component (with html template and controller) from module B (componentB), to be used inside the template of a component in module A (componentA).

After reading Reuse AngularJS Component in another Module (Dependency Injection), I first tried to do this by specifying componentB as a dependency of componentA and then using it inside componentA's template.

componentA.js

angular.module('A', ['componentB']).component('componentA', {...});

componentA.html

   <componentB></componentB>

Unfortunately this did not work, even though componentB is correctly defined and being successfully used in module B. I also tried to specify module B as a dependency of module A, by modifying app.js as shown below:

angular.module('A', ['B'])
.config(...

In both cases, I'm getting an

Uncaught Error: [$injector:modulerr]

I'm having a hard time finding similar questions/articles that relate to AngularJS as opposed to the newer Angular. I'm also pretty rusty with AngularJS so any help would be appreciated, thanks in advance.

Body:
It is pretty straight forward:

angular.module("moduleB",[])
.component("componentB", {
     template: "<div>This is Component B from Module B</div>"
});

angular.module("moduleA",["moduleB"])

<div ng-app="moduleA">
    <component-b></component-b>
</div>

The moduleA imports components from moduleB by declaring moduleB as a dependency.

Module Creation vs Retrieval

Only the first module declaration should have dependencies specified.

ERRONEOUS

angular.module('moduleA', [])
.controller('ctrl', /* ... */)

angular.module('moduleA', ['moduleB'])
.service('serviceA', /* ... */)

Declaring dependencies again will cause the controller to be unregistered.

Better

angular.module('moduleA', ['moduleB'])

angular.module('moduleA')
.controller('ctrl', /* ... */)

angular.module('moduleA')
.service('serviceA', /* ... */)

For more information, see

AngularJS Developer Guide - Module Creation vs Retrieval

AngularJS angular.module API Reference


问:
Smart pointer concepts ownership and lifetime
There are two concepts (ownership, lifetime) that are important when using C++ smart pointers (unique, shared, weak). I try to understand those concepts and how they influence smart pointer (or raw pointer) usage.

I read two rules:

Always use smart pointers to manage ownership/lifetime of dynamic
objects.

Don't use smart pointers when not managing ownership/lifetime.

An example:

```<code>class Object
{
   public:
      Object* child(int i) { return mChildren[i]; }
      // More search and access functions returning pointers here

   private:
      vector<Object*> mChildren;
};
</code>```

I want to rewrite this using smart pointers. Lets ignore child() first. Easy game. A parent owns its children. So make mChildren a vector of unique_ptr.

According to the above rules, some people argue child(i) should continue returning a raw pointer.

But isn't this risky? Someone could do stupid things like deleting the returned object getting a hard to debug crash... which could be avoided using a weak_ptr or a shared_ptr as a return value.

Can't one say that copying a pointer always means to temporarily share the ownership and/or to assert the lifetime of the object?

Is it worth using smart pointers for children only if I do not get a safer API as well?

答:
You could return a const std::unique_ptr<Object>& which would allow you to have same semantics of a raw pointer to call methods on it while preventing deletion.

Using std::unique_ptr with raw pointer makes sense when you know that the ownership will survive any raw pointer and you are sure that people won't try to delete the pointer directly. So that's different from using a std::weak_ptr and std::shared_ptr because they won't allow you to use dangling pointers at all.

There's always room to make something wrong, so the answer really depends on the specific situation, where this code is going to be used and such.

Body:
There are two concepts (ownership, lifetime) that are important when using C++ smart pointers (unique, shared, weak). I try to understand those concepts and how they influence smart pointer (or raw pointer) usage.

I read two rules:

Always use smart pointers to manage ownership/lifetime of dynamic
objects.

Don't use smart pointers when not managing ownership/lifetime.

An example:

class Object
{
   public:
      Object* child(int i) { return mChildren[i]; }
      // More search and access functions returning pointers here

   private:
      vector<Object*> mChildren;
};

I want to rewrite this using smart pointers. Lets ignore child() first. Easy game. A parent owns its children. So make mChildren a vector of unique_ptr.

According to the above rules, some people argue child(i) should continue returning a raw pointer.

But isn't this risky? Someone could do stupid things like deleting the returned object getting a hard to debug crash... which could be avoided using a weak_ptr or a shared_ptr as a return value.

Can't one say that copying a pointer always means to temporarily share the ownership and/or to assert the lifetime of the object?

Is it worth using smart pointers for children only if I do not get a safer API as well?


问:
How to search a nested dictionary and not care about top level key
So I am using lunr.js in my Jekyll application to implement a search feature and the results return correctly. The aim is to then display the list of results in the browser.

Here I get the results, then pass them to a func which handles the DOM manipulation.

var results = idx.search(searchTerm); // Get lunr to perform a search
displaySearchResults(results, window.store);
```

<p>The log of <code>console.log(window.store);</code> is the following:</p>

<pre class="lang-js prettyprint-override"><code>"python-2019-03-23-welcome-to-jekyll-html": Object { title: "test", category: "Python", url: "/python/2019/03/23/welcome-to-jekyll.html" }
</code>```

The first key python-2019-03-23-welcome-to-jekyll-html doesn't matter as that will change depending on the number of posts. How can I get the values of Object{}?

Any advice would be appreciated. I'm fairly new to JS, so if this is badly worded, let me know.

答:
You grab the first key of the window.store and then you can get the values you want</p>

```<code>const { title, category, url } = window.store[Object.keys(window.store)[0]];
</code>```

Body:
So I am using lunr.js in my Jekyll application to implement a search feature and the results return correctly. The aim is to then display the list of results in the browser.

Here I get the results, then pass them to a func which handles the DOM manipulation.

var results = idx.search(searchTerm); // Get lunr to perform a search
displaySearchResults(results, window.store);

The log of console.log(window.store); is the following:

"python-2019-03-23-welcome-to-jekyll-html": Object { title: "test", category: "Python", url: "/python/2019/03/23/welcome-to-jekyll.html" }

The first key python-2019-03-23-welcome-to-jekyll-html doesn't matter as that will change depending on the number of posts. How can I get the values of Object{}?

Any advice would be appreciated. I'm fairly new to JS, so if this is badly worded, let me know.

Body:
You grab the first key of the window.store and then you can get the values you want

const { title, category, url } = window.store[Object.keys(window.store)[0]];


问:
python pandas to_sql with sqlalchemy : how to speed up exporting to MS SQL?
I have a dataframe with ca 155,000 rows and 12 columns.
If I export it to csv with dataframe.to_csv , the output is an 11MB file (which is produced instantly).

If, however, I export to a Microsoft SQL Server with the to_sql method, it takes between 5 and 6 minutes!
No columns are text: only int, float, bool and dates. I have seen cases where ODBC drivers set nvarchar(max) and this slows down the data transfer, but it cannot be the case here.

Any suggestions on how to speed up the export process? Taking 6 minutes to export 11 MBs of data makes the ODBC connection practically unusable.

Thanks!

My code is:

```<code>import pandas as pd
from sqlalchemy import create_engine, MetaData, Table, select
ServerName = "myserver"
Database = "mydatabase"
TableName = "mytable"

engine = create_engine('mssql+pyodbc://' + ServerName + '/' + Database)
conn = engine.connect()

metadata = MetaData(conn)

my_data_frame.to_sql(TableName,engine)
</code>```

答:
I was running out of time and memory (more than 18GB allocated for a DataFrame loaded from 120MB CSV) with this line:

```<code>df.to_sql('my_table', engine, if_exists='replace', method='multi', dtype={"text_field": db.String(64), "text_field2": db.String(128), "intfield1": db.Integer(), "intfield2": db.Integer(), "floatfield": db.Float()})
</code>```

Here is the code that helped me to import and track progress of insertions at the same time:

```<code>import sqlalchemy as db
engine = db.create_engine('mysql://user:password@localhost:3306/database_name', echo=False)
connection = engine.connect()
metadata = db.MetaData()

my_table = db.Table('my_table', metadata,
              db.Column('text_field', db.String(64), index=True),
              db.Column('text_field2', db.String(128), index=True),
              db.Column('intfield1', db.Integer()),
              db.Column('intfield2', db.Integer()),
              db.Column('floatfield', db.Float())
             )
metadata.create_all(engine)
kw_dict = df.reset_index().sort_values(by="intfield2", ascending=False).to_dict(orient="records")

batch_size=10000
for batch_start in range(0, len(kw_dict), batch_size):
    print("Inserting {}-{}".format(batch_start, batch_start + batch_size))
    connection.execute(my_table.insert(), kw_dict[batch_start:batch_start + batch_size])
</code>```

Body:
I have a dataframe with ca 155,000 rows and 12 columns.
If I export it to csv with dataframe.to_csv , the output is an 11MB file (which is produced instantly).

If, however, I export to a Microsoft SQL Server with the to_sql method, it takes between 5 and 6 minutes!
No columns are text: only int, float, bool and dates. I have seen cases where ODBC drivers set nvarchar(max) and this slows down the data transfer, but it cannot be the case here.

Any suggestions on how to speed up the export process? Taking 6 minutes to export 11 MBs of data makes the ODBC connection practically unusable.

Thanks!

My code is:

import pandas as pd
from sqlalchemy import create_engine, MetaData, Table, select
ServerName = "myserver"
Database = "mydatabase"
TableName = "mytable"

engine = create_engine('mssql+pyodbc://' + ServerName + '/' + Database)
conn = engine.connect()

metadata = MetaData(conn)

my_data_frame.to_sql(TableName,engine)

Body:
I was running out of time and memory (more than 18GB allocated for a DataFrame loaded from 120MB CSV) with this line:

df.to_sql('my_table', engine, if_exists='replace', method='multi', dtype={"text_field": db.String(64), "text_field2": db.String(128), "intfield1": db.Integer(), "intfield2": db.Integer(), "floatfield": db.Float()})

Here is the code that helped me to import and track progress of insertions at the same time:

import sqlalchemy as db
engine = db.create_engine('mysql://user:password@localhost:3306/database_name', echo=False)
connection = engine.connect()
metadata = db.MetaData()

my_table = db.Table('my_table', metadata,
              db.Column('text_field', db.String(64), index=True),
              db.Column('text_field2', db.String(128), index=True),
              db.Column('intfield1', db.Integer()),
              db.Column('intfield2', db.Integer()),
              db.Column('floatfield', db.Float())
             )
metadata.create_all(engine)
kw_dict = df.reset_index().sort_values(by="intfield2", ascending=False).to_dict(orient="records")

batch_size=10000
for batch_start in range(0, len(kw_dict), batch_size):
    print("Inserting {}-{}".format(batch_start, batch_start + batch_size))
    connection.execute(my_table.insert(), kw_dict[batch_start:batch_start + batch_size])


问:
How do I connect to Oracle Exadata from Python?
I have tried connecting exadata from python using cx_Oracle, but faced issue stating

cx_Oracle.DatabaseError: DPI - 1047: Cannot locate a 64bit Oracle client library.

I am trying to install a 64bit cx_Oracle, but I need to know can I connect from python to exadata.

答:
Follow the cx_Oracle Linux installation instructions.  The piece you are missing is access to Oracle Client libraries.  As noted in the other answer, using Instant Client is the way to go.  You'll need the "Basic" or "Basic Light" package for Linux x86-64.  If you don't know your character set requirement, then use "Basic".  You can use the latest 19c version.  This will let you connect to Oracle DB 11.2 and newer.

If you have root access (?) you may find the RPM packages easier.  If you want to use ZIP files, unzip the package, set your LD_LIBRARY_PATH environment variable to the directory, and run Python.

In your cx_Oracle scripts you use the same database credentials and connection string that you would use in SQL*Plus.


问:
ckeditor with drupal custom form
I created my own module form which include address textarea

```<code>    $form['address'] = array(
    '#input_format' => '1',
    '#rows' => '5',
    '#weight' => '4',
    '#type' => 'textarea',
    '#title' => t('Address'),

);
</code>```

when i run the form i got the following help below it

CKEditor: the ID for excluding or including this element is customers/edit/5.edit-address.

so i got the element ID and entered it in the include setting of the ckeditor

but still the editor doesn't appear on that field, am I missing something ?

答:
use a #type of "text_format" with a #base_type of "textarea" and it should work. like this:</p>

```<code>    $form['address'] = array(
      '#input_format' => '1',
      '#rows' => '5',
      '#weight' => '4',
      '#type' => 'text_format',
      '#base_type' => 'textarea',
      '#title' => t('Address'),

  );
</code>```

Title: ckeditor with drupal custom form

Body:
I created my own module form which include address textarea

    $form['address'] = array(
    '#input_format' => '1',
    '#rows' => '5',
    '#weight' => '4',
    '#type' => 'textarea',
    '#title' => t('Address'),

);

when i run the form i got the following help below it

CKEditor: the ID for excluding or including this element is customers/edit/5.edit-address.

so i got the element ID and entered it in the include setting of the ckeditor

but still the editor doesn't appear on that field, am I missing something ?

Body:
use a #type of "text_format" with a #base_type of "textarea" and it should work. like this:

    $form['address'] = array(
      '#input_format' => '1',
      '#rows' => '5',
      '#weight' => '4',
      '#type' => 'text_format',
      '#base_type' => 'textarea',
      '#title' => t('Address'),

  );


问:
Does including ncurses.h in C programming also include stdio.h?
I was studying up on ncurses.h because I am trying to learn a bit of design aspects for c, and stumbled across a statement saying that stdio.h is inside of ncurses

```<code>  #include <ncurses.h>        /*ncurses.h includes stdio.h*/
</code>```

Is this true? If so, can someone explain to me why, and if that means I don't have to ever include it again?

Also, does this cause any issues because I am not exactly defining it in a regular sense

答:
It does indeed include stdio.h, and yes this does mean that you don't need to include stdio.h again.
This works because the compiler will insert the contents of the #include'd header files at the point in your code that the #include directive was placed. This means that not only was ncurses.h included in your code at the location you specified, but stdio.h was already included in that file at the appropriate location prior to it being placed into your code.

Subsequent includes of stdio.h will have no effect on your program due to the use of include guards.

If you're using anything from stdio.h in your own code I would consider it good practice to add the #include <stdio.h> directive to your own source files. My reasoning is that it communicates directly to the next developer reading your code that stdio functionality is used here without relying on implicit information.

Body:
I was studying up on ncurses.h because I am trying to learn a bit of design aspects for c, and stumbled across a statement saying that stdio.h is inside of ncurses

  #include <ncurses.h>        /*ncurses.h includes stdio.h*/

Is this true? If so, can someone explain to me why, and if that means I don't have to ever include it again?

Also, does this cause any issues because I am not exactly defining it in a regular sense


问:
jQuery event after a PDF loads?
I have a modal dialog that allows users to generate a customized PDF. After they click a "Start" button, the page redirects with window.location to a controller, which then creates the PDF and returns it.

Because of how long it takes the PDF to return, I want to display a modal "Generating PDF" dialog that automatically closes once the PDF is complete and is returned.

The problem is I can't figure out how/when to execute that final function to close the "Generating PDF" dialog. Since the controller returns an application/pdf type, there is no document object event to attach to, right? What is the best way to do this?

答:
This is how I would do it

User clicks the link to create the pdf

An AJAX request is sent to server to generate pdf

Server adds the pdf creation to background job and returns the
status as added

Client receives the status, shows the model or animation and start pinging the
server every 3 seconds for status

Server returns the status after (n) seconds as completed/failed and a link to the
pdf

Client hides the model/animation, stops the ping and open the link in new tab which will
download the pdf

Title: jQuery event after a PDF loads?


问:
Practice Linux Shell Scripting
My homework assignment is to write a shell script to read a "log.txt" and display its comments line by line. Each line should be prefixed by its line number.

Script I have so far:

```<code>path="/home/user/log.txt"
while i=read -r line
do
   echo "$line"
done < "$log_file"
</code>```

Input file:

```<code>How are you
Where are you
</code>```

Expected output:

```<code>1. How are you
2. Where are you
</code>```

答:
in python 3.8 this worked

count = 0
  with open("log.txt") as file_in:
      lines = []
      for line in file_in:
          lines.append(line)
          print('{} {}'.format(count, line))
          count +=1

Title: Practice Linux Shell Scripting

Body:
My homework assignment is to write a shell script to read a "log.txt" and display its comments line by line. Each line should be prefixed by its line number.

Script I have so far:

path="/home/user/log.txt"
while i=read -r line
do
   echo "$line"
done < "$log_file"

Input file:

How are you
Where are you

Expected output:

1. How are you
2. Where are you


问:
How to automate InternetExplorer with clojure-clr?
I'd like to use IE to open a web-page and retrieve its content from clojure-clr. I tried to translate the following C#-snippet to clojure, but could not load the DLL necessary to use SHDocVw (I don't have my clojure-code at hand right now):

```<code>using SHDocVw;
public void OpenBrowser(string url)
{
object o = null;
SHDocVw.InternetExplorer ie = new
SHDocVw.InternetExplorerClass();
IWebBrowserApp wb = (IWebBrowserApp) ie;
wb.Visible = true;
//Do anything else with the window here that you wish
wb.Navigate(url, ref o, ref o, ref o, ref o);
}
</code>```

How would I go about accessing IE from clojure?

答: You need to load the dll explicitly in your clojure script, by calling Assembly.Load. This is true if you want to use anything that is not in System or in clojure.core (as those are loaded automatically).</p>

Body:
I'd like to use IE to open a web-page and retrieve its content from clojure-clr. I tried to translate the following C#-snippet to clojure, but could not load the DLL necessary to use SHDocVw (I don't have my clojure-code at hand right now):

using SHDocVw;
public void OpenBrowser(string url)
{
object o = null;
SHDocVw.InternetExplorer ie = new
SHDocVw.InternetExplorerClass();
IWebBrowserApp wb = (IWebBrowserApp) ie;
wb.Visible = true;
//Do anything else with the window here that you wish
wb.Navigate(url, ref o, ref o, ref o, ref o);
}

How would I go about accessing IE from clojure?


问:
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file Javascript
I'am trying to init a class with the following syntax:

const slider = new Slider()

I get this mistake:

You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file

My Webpack Configurations look like this:

```<code>                         module: {
                           rules: [
                             {
                               test: /\.html$/,
                               loader: 'html-loader',
                               options: {
                                       attrs: false,
                               },
                            },
                            {
                              test: /\.js$/,
                              exclude: /(node_modules|bower_components)/,
                              use: {
                                  loader: 'babel-loader',
                                  options: {
                                    presets: ['@babel/preset-env'],
                                  },
                              },
                            },
                          ],
                        },
</code>```

what am I doing wrong?

答: You probably missing a loader for css but there is no way to be sure without seeing the name of the file </p>

Body:
I'am trying to init a class with the following syntax:

const slider = new Slider()

I get this mistake:

You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file

My Webpack Configurations look like this:

                         module: {
                           rules: [
                             {
                               test: /\.html$/,
                               loader: 'html-loader',
                               options: {
                                       attrs: false,
                               },
                            },
                            {
                              test: /\.js$/,
                              exclude: /(node_modules|bower_components)/,
                              use: {
                                  loader: 'babel-loader',
                                  options: {
                                    presets: ['@babel/preset-env'],
                                  },
                              },
                            },
                          ],
                        },

what am I doing wrong?


问:
How do I target my random colour variable in my IF statement?
I have a question that is leading from the chosen best answer from my previous post:
How can I use randomisation to specify different object parameters to a single iteration in a loop? I'm new to stack and wasn't sure of the best way to reference that post.

I have the code written as advised from the post above, however, now I'm attempting to have a method run different lines of code based off the colour of the 'brick' that is interacted with via my 'ball' object:

```<code>public Color brickColour;

public GameObj( int x, int y, int w, int h, Color c ){
        topX   = x;
        topY = y;
        width  = w;
        height = h;
        colour = c;
}

public void initialiseGame(){
    Random random = new Random();
    int yellowBrick = random.nextInt(5);
    for (int i = 0; i < 5; i++) {
        brickColour = i == yellowBrick ? Color.YELLOWGREEN : Color.BLUE;
        GameObj brick = new GameObj(i*100, 100, BRICK_WIDTH, BRICK_HEIGHT, brickColour);
        brick.moveX(75);
        brick.visible = true;
        bricks.add(brick);
        System.out.println("Model:: Create Brick =" + brick);
    }
}

public synchronized void updateGame(){
           for(GameObj brick: bricks){
                if (ball.hitBy(brick)){
                    if(brickColour.equals(Color.YELLOWGREEN)){
                        ball.changeDirectionY();
                        addToScore(HIT_BRICK);
                        brick.visible = false;
                        Debug.trace("Model::Brick Hit YELLOWGREEN = " + brick);
                        startGame();
                    }else {
                        ball.changeDirectionY();
                        addToScore(HIT_BRICK);
                        brick.visible = false;
                        Debug.trace("Model::Brick Hit = " + brick);
                    }
                }
            }
}
</code>```

I have tested the program and when the YELLOWGREEN 'brick' is hit, it's still running the else statement. I then printed the brickColour variable and got "0x0000ffff", though, even using that as a string in the color.equals() parameters, it didnt work. How exactly can I target the yellowgreen brick object?

答:
Your problem lies in this:

```<code>brickColour = i == yellowBrick ? Color.YELLOWGREEN : Color.BLUE;
</code>```

You have defined a global variable here and are using whatever the most recent set of this is. You should make this a local variable and not re-use it between methods.

```<code>for (int i = 0; i < 5; i++) {
    Color brickColour = i == yellowBrick ? Color.YELLOWGREEN : Color.BLUE;
    GameObj brick = new GameObj(i*100, 100, BRICK_WIDTH, BRICK_HEIGHT, brickColour);
    // omitted for answer
}
</code>```

Then when doing your check:

```<code>for(GameObj brick: bricks){
    if (ball.hitBy(brick)){
        if(brick.brickColour == Color.YELLOWGREEN) {
             // yellow logic
        } else {
             // blue logic
        }
    }
}
</code>```

Of course, using the colour itself is a rather poor design decision to begin with. Instead, you would want to have a property of the GameObj that declares its brick type, and have the colour determined by the brick type. But that's tangential to this discussion.

The lesson here is to make your variables scoped only to what is necessary. Don't use a global if you don't need to, use locals wherever you can.

Body:
I have a question that is leading from the chosen best answer from my previous post:
How can I use randomisation to specify different object parameters to a single iteration in a loop? I'm new to stack and wasn't sure of the best way to reference that post.

I have the code written as advised from the post above, however, now I'm attempting to have a method run different lines of code based off the colour of the 'brick' that is interacted with via my 'ball' object:

public Color brickColour;

public GameObj( int x, int y, int w, int h, Color c ){
        topX   = x;
        topY = y;
        width  = w;
        height = h;
        colour = c;
}

public void initialiseGame(){
    Random random = new Random();
    int yellowBrick = random.nextInt(5);
    for (int i = 0; i < 5; i++) {
        brickColour = i == yellowBrick ? Color.YELLOWGREEN : Color.BLUE;
        GameObj brick = new GameObj(i*100, 100, BRICK_WIDTH, BRICK_HEIGHT, brickColour);
        brick.moveX(75);
        brick.visible = true;
        bricks.add(brick);
        System.out.println("Model:: Create Brick =" + brick);
    }
}

public synchronized void updateGame(){
           for(GameObj brick: bricks){
                if (ball.hitBy(brick)){
                    if(brickColour.equals(Color.YELLOWGREEN)){
                        ball.changeDirectionY();
                        addToScore(HIT_BRICK);
                        brick.visible = false;
                        Debug.trace("Model::Brick Hit YELLOWGREEN = " + brick);
                        startGame();
                    }else {
                        ball.changeDirectionY();
                        addToScore(HIT_BRICK);
                        brick.visible = false;
                        Debug.trace("Model::Brick Hit = " + brick);
                    }
                }
            }
}

I have tested the program and when the YELLOWGREEN 'brick' is hit, it's still running the else statement. I then printed the brickColour variable and got "0x0000ffff", though, even using that as a string in the color.equals() parameters, it didnt work. How exactly can I target the yellowgreen brick object?

Body:
Your problem lies in this:

brickColour = i == yellowBrick ? Color.YELLOWGREEN : Color.BLUE;

You have defined a global variable here and are using whatever the most recent set of this is. You should make this a local variable and not re-use it between methods.

for (int i = 0; i < 5; i++) {
    Color brickColour = i == yellowBrick ? Color.YELLOWGREEN : Color.BLUE;
    GameObj brick = new GameObj(i*100, 100, BRICK_WIDTH, BRICK_HEIGHT, brickColour);
    // omitted for answer
}

Then when doing your check:

for(GameObj brick: bricks){
    if (ball.hitBy(brick)){
        if(brick.brickColour == Color.YELLOWGREEN) {
             // yellow logic
        } else {
             // blue logic
        }
    }
}

Of course, using the colour itself is a rather poor design decision to begin with. Instead, you would want to have a property of the GameObj that declares its brick type, and have the colour determined by the brick type. But that's tangential to this discussion.

The lesson here is to make your variables scoped only to what is necessary. Don't use a global if you don't need to, use locals wherever you can.


问:
Jupyter notebook signal only works in main thread
whenever I run python in jupyter, it gives me this:
ValueError: signal only works in main thread

答:
Only worked when downgraded to tornado 5.1.1,

Then :
pip install pip --upgrade,

pip install --upgrade notebook,

I have python 3.6.8 and MAC


问:
How to send email in loop?
I'm trying to send an email to selected recipient(s) based on if a cell in Excel meets specific criteria, in this instance "yes".

The code will only send to the first user in the range that it sees the "yes" criteria being met.

Sub Read_Emails()

    ' SET Outlook APPLICATION OBJECT.

    Dim objOutlook As Object
    Set objOutlook = CreateObject("Outlook.Application")

    ' CREATE EMAIL OBJECT.
    Dim objEmail As Object
    Set objEmail = objOutlook.CreateItem(olMailItem)

    For Each cell In Columns("N").Cells.SpecialCells(xlCellTypeConstants)
        If cell.Value Like "?*@?*.?*" And _
          LCase(Cells(cell.Row, "R").Value) = "yes" Then

            With objEmail
                .To = cell.Value
                .CC = ""
                .Subject = "Subject here"
                .BodyFormat = olFormatHTML
                .HTMLBody = "Hello," & "
" & "Message here."
                .Send
            End With
        End If
    Next cell

    Set objEmail = Nothing
    Set objOutlook = Nothing

End Sub
```

答:
I was able to troubleshoot this myself using https://www.rondebruin.nl/win/s1/outlook/bmail5.htm.

Code below for those interested in similar problem:

```<code>Dim OutApp As Object
Dim OutMail As Object
Dim cell As Range

Application.ScreenUpdating = False
Set OutApp = CreateObject("Outlook.Application")

On Error GoTo cleanup
For Each cell In Columns("L").Cells.SpecialCells(xlCellTypeConstants)
    If cell.Value Like "?*@?*.?*" And _
       LCase(Cells(cell.Row, "P").Value) = "yes" Then

        Set OutMail = OutApp.CreateItem(0)
        On Error Resume Next
        With OutMail
            .To = cell.Value
            .Subject = "Subject here"
            .Body = "Hello " & Cells(cell.Row, "K").Value & "," _
              & vbNewLine & vbNewLine & _
                    "Message here."
            'You can add files also like this
            '.Attachments.Add ("C:\test.txt")
            .Send  'Or use Display
        End With
        On Error GoTo 0
        Set OutMail = Nothing
    End If
Next cell

cleanup:
Set OutApp = Nothing
Application.ScreenUpdating = True
End Sub
</code>```

Title: How to send email in loop?

Body:
I was able to troubleshoot this myself using https://www.rondebruin.nl/win/s1/outlook/bmail5.htm.

Code below for those interested in similar problem:

Dim OutApp As Object
Dim OutMail As Object
Dim cell As Range

Application.ScreenUpdating = False
Set OutApp = CreateObject("Outlook.Application")

On Error GoTo cleanup
For Each cell In Columns("L").Cells.SpecialCells(xlCellTypeConstants)
    If cell.Value Like "?*@?*.?*" And _
       LCase(Cells(cell.Row, "P").Value) = "yes" Then

        Set OutMail = OutApp.CreateItem(0)
        On Error Resume Next
        With OutMail
            .To = cell.Value
            .Subject = "Subject here"
            .Body = "Hello " & Cells(cell.Row, "K").Value & "," _
              & vbNewLine & vbNewLine & _
                    "Message here."
            'You can add files also like this
            '.Attachments.Add ("C:\test.txt")
            .Send  'Or use Display
        End With
        On Error GoTo 0
        Set OutMail = Nothing
    End If
Next cell

cleanup:
Set OutApp = Nothing
Application.ScreenUpdating = True
End Sub


问:
List iteration crashes R
I'd like to do a list iteration in Rcpp, but this code crashes R:

```<code>Rcpp::cppFunction('List foo(List bc) {

              for (List::iterator i = bc.begin(); i != bc.end(); ++i) i[0] = i[1];

              return(bc);

            }'
)
</code>```

If we take the following foo(list(a = c(1, 2, 3, 4), b = c(4, 3, 2, 1))), R will crash. The example above is just a dummy one - replace first element with second in every sublist (e.g. we should get c(2, 2, 3, 4) for a and for b c(3, 3, 2, 1)).

Could anyone help? I'm really new to both R and Rcpp and just going through the literature but have no idea about why the iterator doesn't work.

答:
The problem is with i[0] and i[1].  Iterators are kinda-sorta-like pointers, you need to instantiate them first.  Here is a variant of your code that works:

Code

```<code>#include <Rcpp.h>

// [[Rcpp::export]]
Rcpp::List foo(Rcpp::List bc) {
  for (Rcpp::List::iterator i = bc.begin(); i != bc.end(); ++i) {
    SEXP a = *i;
    Rcpp::print(a);
  }

  return(bc);
}

/*** R
ll <- list(a = c(1, 2, 3, 4), b = c(4, 3, 2, 1))
foo(ll)
*/
</code>```

Output

```<code>edd@rob:~/git/stackoverflow/60291024(master)$ Rscript -e 'Rcpp::sourceCpp("question.cpp")'

R> ll <- list(a = c(1, 2, 3, 4), b = c(4, 3, 2, 1))

R> foo(ll)
[1] 1 2 3 4
[1] 4 3 2 1
$a
[1] 1 2 3 4

$b
[1] 4 3 2 1

edd@rob:~/git/stackoverflow/60291024(master)$
</code>```

Title: List iteration crashes R

Body:
I'd like to do a list iteration in Rcpp, but this code crashes R:

Rcpp::cppFunction('List foo(List bc) {

              for (List::iterator i = bc.begin(); i != bc.end(); ++i) i[0] = i[1];

              return(bc);

            }'
)

If we take the following foo(list(a = c(1, 2, 3, 4), b = c(4, 3, 2, 1))), R will crash. The example above is just a dummy one - replace first element with second in every sublist (e.g. we should get c(2, 2, 3, 4) for a and for b c(3, 3, 2, 1)).

Could anyone help? I'm really new to both R and Rcpp and just going through the literature but have no idea about why the iterator doesn't work.

Body:
The problem is with i[0] and i[1].  Iterators are kinda-sorta-like pointers, you need to instantiate them first.  Here is a variant of your code that works:

Code

#include <Rcpp.h>

// [[Rcpp::export]]
Rcpp::List foo(Rcpp::List bc) {
  for (Rcpp::List::iterator i = bc.begin(); i != bc.end(); ++i) {
    SEXP a = *i;
    Rcpp::print(a);
  }

  return(bc);
}

/*** R
ll <- list(a = c(1, 2, 3, 4), b = c(4, 3, 2, 1))
foo(ll)
*/

Output

edd@rob:~/git/stackoverflow/60291024(master)$ Rscript -e 'Rcpp::sourceCpp("question.cpp")'

R> ll <- list(a = c(1, 2, 3, 4), b = c(4, 3, 2, 1))

R> foo(ll)
[1] 1 2 3 4
[1] 4 3 2 1
$a
[1] 1 2 3 4

$b
[1] 4 3 2 1

edd@rob:~/git/stackoverflow/60291024(master)$


问:
Vue mapState non reactive
I try to get the state from the store using the mapState function, But I can't use the generated code that returns the values into my template code ...

```<code><template>
         // Some code
                <template v-if="!isLoggedIn">
                    // Some code
                </template>
                <template v-else>
                    // Some code
                    {{ currentUser.name }}
                </template>

        // Some code
</template>

<script>
    import { mapState } from "vuex";

    export default {
        // Some code
        computed: {
          ...mapState({auth : ['currentUser', 'isLoggedIn','customers']})
        }
    }
</script>
</code>```

instead the following code work

```<code><script>
    import { mapState } from "vuex";

    export default {
        // Some code
        computed: {
          currentUser() {
                return this.$store.state.auth.currentUser
            },
            isLoggedIn() {
                return this.$store.state.auth.isLoggedIn
            },
        }
    }
</script>
</code>```

Warning message

[Vue warn]: Property or method "isLoggedIn" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.

Thanks in advance

答:
The right syntax to access non-root properties is the following (using arrow functions) :

```<code>computed: {
...mapState({
  currentUser: state => state.auth.currentUser,
  isLoggedIn: state => state.auth.isLoggedIn,
  customers: state => state.auth.customers
})}
</code>```

Check the documentation.

Title: Vue mapState non reactive

Body:
I try to get the state from the store using the mapState function, But I can't use the generated code that returns the values into my template code ...

<template>
         // Some code
                <template v-if="!isLoggedIn">
                    // Some code
                </template>
                <template v-else>
                    // Some code
                    {{ currentUser.name }}
                </template>

        // Some code
</template>

instead the following code work

Warning message

[Vue warn]: Property or method "isLoggedIn" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.

Thanks in advance

Body:
The right syntax to access non-root properties is the following (using arrow functions) :

computed: {
...mapState({
  currentUser: state => state.auth.currentUser,
  isLoggedIn: state => state.auth.isLoggedIn,
  customers: state => state.auth.customers
})}

Check the documentation.