问:
How to test if a c-string contains characters outside certain ascii range?
So, let say I have simple code below:

```<code>int main() {
    char string1[256]="TEST1";
    char string2[256]="TESTOK"; //Also could be "TEST OK"

    if(//string doesn't contain "A-Z" || doesn't contain "SPACE")
    {
        //do something
    }

    return 0;
}
</code>```

Where the if statement is, all I would want to do is have string1 go into the if statement, because it contains something other than ASCII characters A-Z or a SPACE. However, in both examples of string2, I would want them to bypass the if statement because it contains A-Z or may have a SPACE, which all would be ok and should mean the char string doesn't go into the if statement.

I can not find a simple way to do this with c, to test for this. I have considered just looping through all the characters and testing if the ASCII value is of a certain value range or equals 32 for the space. However, that seems overly complicated. Also, I purposely set the 256 larger than the amount of characters in the string, so I worry about NULL characters messing things up possibly too.

Anyways, is there a simple way to do a test like this in C? Thanks for any help.

答:
ASCII characters A-Z or a SPACE.

Source code's encoding may not be ASCII - this is rare, yet serves as an opportunity to distinguish between source code, say in EBCIDIC encoding and the contents of a string, read from external input, which is to be interpreted as ASCII data.

Note: regardless of encoding, the null character has the value '\0'.

This is a time when code should use 32, 65 and 90.  #define ASCII_A 'A' does  not work because the 'A' is interpreted in the source code's encoding, which may differ from ASCII.

```<code>#define ASCII_SPACE 32
#define ASCII_A 65
#define ASCII_Z 90
</code>```

Also no need to test for the null character in the loop.

```<code>// return true if `s` contains only ASCII A-Z or space and then the null character
bool test_ASCII_AZ_space(const char *s) {
  while ((*s >= ASCII_A && *s <= ASCII_Z) || (*s == ASCII_SPACE)) {
    s++;
  }
  return *s == '\0';
}
</code>```

To employ portability this using strspn() as suggested by @pmg requires that the pattern string is formed using ASCII values.  Also no need to use strlen() to run down the string again, just check if the value returned by strspn() indexes to the null character.

```<code>const char okchar[] = { 32, 65, 66, 67, 68, 69,
  70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
  80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, '\0' };

if (input[strspn(input, okchar)] == '\0') {
  /* ok */;
}
</code>```

Body:
So, let say I have simple code below:

int main() {
    char string1[256]="TEST1";
    char string2[256]="TESTOK"; //Also could be "TEST OK"

    if(//string doesn't contain "A-Z" || doesn't contain "SPACE")
    {
        //do something
    }

    return 0;
}

Where the if statement is, all I would want to do is have string1 go into the if statement, because it contains something other than ASCII characters A-Z or a SPACE. However, in both examples of string2, I would want them to bypass the if statement because it contains A-Z or may have a SPACE, which all would be ok and should mean the char string doesn't go into the if statement.

I can not find a simple way to do this with c, to test for this. I have considered just looping through all the characters and testing if the ASCII value is of a certain value range or equals 32 for the space. However, that seems overly complicated. Also, I purposely set the 256 larger than the amount of characters in the string, so I worry about NULL characters messing things up possibly too.

Anyways, is there a simple way to do a test like this in C? Thanks for any help.

Body:
ASCII characters A-Z or a SPACE.

Source code's encoding may not be ASCII - this is rare, yet serves as an opportunity to distinguish between source code, say in EBCIDIC encoding and the contents of a string, read from external input, which is to be interpreted as ASCII data.

Note: regardless of encoding, the null character has the value '\0'.

This is a time when code should use 32, 65 and 90.  #define ASCII_A 'A' does  not work because the 'A' is interpreted in the source code's encoding, which may differ from ASCII.

#define ASCII_SPACE 32
#define ASCII_A 65
#define ASCII_Z 90

Also no need to test for the null character in the loop.

// return true if `s` contains only ASCII A-Z or space and then the null character
bool test_ASCII_AZ_space(const char *s) {
  while ((*s >= ASCII_A && *s <= ASCII_Z) || (*s == ASCII_SPACE)) {
    s++;
  }
  return *s == '\0';
}

To employ portability this using strspn() as suggested by @pmg requires that the pattern string is formed using ASCII values.  Also no need to use strlen() to run down the string again, just check if the value returned by strspn() indexes to the null character.

const char okchar[] = { 32, 65, 66, 67, 68, 69,
  70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
  80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, '\0' };

if (input[strspn(input, okchar)] == '\0') {
  /* ok */;
}


来源: stackexchange

问:
How to profile time spent in memory access in C/C++ applications?
Total Time spent by a function in an application can be broadly divided in to two components:

Time spent on actual computation (Tcomp)

Time spent on memory accesses (Tmem)

Typically profilers provide an estimate of the total time spent by a function. Is it possible to get an estimate of the time spent in terms of the above two components (Tcomp and Tmem)?

答:
Brendan Gregg in his recent blog post CPU Utilization is Wrong suggests to use instructions per cycle PMC. In short if IPC is < 1.0 than the app can be considered memory bound. Otherwise it can be considered instruction bound. Here is a relevant excerpt from his post:

If your IPC is < 1.0, you are likely memory stalled, and software
  tuning strategies include reducing memory I/O, and improving CPU
  caching and memory locality, especially on NUMA systems. Hardware
  tuning includes using processors with larger CPU caches, and faster
  memory, busses, and interconnects.

If your IPC is > 1.0, you are likely instruction bound. Look for ways
  to reduce code execution: eliminate unnecessary work, cache
  operations, etc. CPU flame graphs are a great tool for this
  investigation. For hardware tuning, try a faster clock rate, and more
  cores/hyperthreads.

For my above rules, I split on an IPC of 1.0. Where did I get that
  from? I made it up, based on my prior work with PMCs. Here's how you
  can get a value that's custom for your system and runtime: write two
  dummy workloads, one that is CPU bound, and one memory bound. Measure
  their IPC, then calculate their mid point.

Here are some examples of dummy workloads generated by stress tool and thier IPCs.

Memory bound test, IPC is low (0,02):

```<code>$ perf stat stress --vm 4 -t 3
stress: info: [4520] dispatching hogs: 0 cpu, 0 io, 4 vm, 0 hdd
stress: info: [4520] successful run completed in 3s

 Performance counter stats for 'stress --vm 4 -t 3':

      10767,074968      task-clock:u (msec)       #    3,560 CPUs utilized
                 0      context-switches:u        #    0,000 K/sec
                 0      cpu-migrations:u          #    0,000 K/sec
         4 555 919      page-faults:u             #    0,423 M/sec
     4 290 929 426      cycles:u                  #    0,399 GHz
        67 779 143      instructions:u            #    0,02  insn per cycle
        18 074 114      branches:u                #    1,679 M/sec
             5 398      branch-misses:u           #    0,03% of all branches

       3,024851934 seconds time elapsed
</code>```

CPU bound test, IPC is high (1,44):

```<code>$ perf stat stress --cpu 4 -t 3
stress: info: [4465] dispatching hogs: 4 cpu, 0 io, 0 vm, 0 hdd
stress: info: [4465] successful run completed in 3s

 Performance counter stats for 'stress --cpu 4 -t 3':

      11419,683671      task-clock:u (msec)       #    3,805 CPUs utilized
                 0      context-switches:u        #    0,000 K/sec
                 0      cpu-migrations:u          #    0,000 K/sec
               108      page-faults:u             #    0,009 K/sec
    30 562 187 954      cycles:u                  #    2,676 GHz
    43 995 290 836      instructions:u            #    1,44  insn per cycle
    13 043 425 872      branches:u                # 1142,188 M/sec
        26 312 747      branch-misses:u           #    0,20% of all branches

       3,001218526 seconds time elapsed
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Brendan Gregg in his recent blog post CPU Utilization is Wrong suggests to use instructions per cycle PMC. In short if IPC is < 1.0 than the app can be considered memory bound. Otherwise it can be considered instruction bound. Here is a relevant excerpt from his post:

If your IPC is < 1.0, you are likely memory stalled, and software
  tuning strategies include reducing memory I/O, and improving CPU
  caching and memory locality, especially on NUMA systems. Hardware
  tuning includes using processors with larger CPU caches, and faster
  memory, busses, and interconnects.

If your IPC is > 1.0, you are likely instruction bound. Look for ways
  to reduce code execution: eliminate unnecessary work, cache
  operations, etc. CPU flame graphs are a great tool for this
  investigation. For hardware tuning, try a faster clock rate, and more
  cores/hyperthreads.

For my above rules, I split on an IPC of 1.0. Where did I get that
  from? I made it up, based on my prior work with PMCs. Here's how you
  can get a value that's custom for your system and runtime: write two
  dummy workloads, one that is CPU bound, and one memory bound. Measure
  their IPC, then calculate their mid point.

Here are some examples of dummy workloads generated by stress tool and thier IPCs.

Memory bound test, IPC is low (0,02):

$ perf stat stress --vm 4 -t 3
stress: info: [4520] dispatching hogs: 0 cpu, 0 io, 4 vm, 0 hdd
stress: info: [4520] successful run completed in 3s

 Performance counter stats for 'stress --vm 4 -t 3':

      10767,074968      task-clock:u (msec)       #    3,560 CPUs utilized
                 0      context-switches:u        #    0,000 K/sec
                 0      cpu-migrations:u          #    0,000 K/sec
         4 555 919      page-faults:u             #    0,423 M/sec
     4 290 929 426      cycles:u                  #    0,399 GHz
        67 779 143      instructions:u            #    0,02  insn per cycle
        18 074 114      branches:u                #    1,679 M/sec
             5 398      branch-misses:u           #    0,03% of all branches

       3,024851934 seconds time elapsed

CPU bound test, IPC is high (1,44):

$ perf stat stress --cpu 4 -t 3
stress: info: [4465] dispatching hogs: 4 cpu, 0 io, 0 vm, 0 hdd
stress: info: [4465] successful run completed in 3s

 Performance counter stats for 'stress --cpu 4 -t 3':

      11419,683671      task-clock:u (msec)       #    3,805 CPUs utilized
                 0      context-switches:u        #    0,000 K/sec
                 0      cpu-migrations:u          #    0,000 K/sec
               108      page-faults:u             #    0,009 K/sec
    30 562 187 954      cycles:u                  #    2,676 GHz
    43 995 290 836      instructions:u            #    1,44  insn per cycle
    13 043 425 872      branches:u                # 1142,188 M/sec
        26 312 747      branch-misses:u           #    0,20% of all branches

       3,001218526 seconds time elapsed


问:
PostScript immediate or deferred execution
I'm trying to wrap my head around the immediate and deferred execution.
From what I understand is that the interpreter maintains a flag that knows if it in deferred execution or not.

Deferred execution of a procedure could be because a name lookup returned a procedure.

Now I'm trying to find out what types, actions or operations control this interpreter flag.

For example this piece of code below has an immediately evaluated name at the end which returns an procedure. But this procedure is pushed, while it it is executable (xcheck):

```<code>/setdata
{
  /a 1 def
  /b 0 def

 /foo
   a 0 ne
   b 0 ne
   and
 def

 { foo false and }
} def

//setdata
</code>```

I know there is a special rule:

Procedures appearing directly (either as part of a program being read
  from a file or as part of some larger procedure in memory) are usually
  part of a definition or of a construct, such as a conditional, that
  operates on the procedure explicitly. But procedures obtained
  indirectly—for example, as a result of looking up a name—are usually
  intended to be executed. A PostScript program can override these
  semantics when necessary.

I understand that if you encounter a procedure directly that you have to push it (even if it is executable). (The immediately evaluated name returns a procedure, which is encountered directly, so it should be pushed to the OS.)

Now if I'm thinking in code to implement this logic in an interpreter I can think of something like this:

If I have a literalname lookup, set the interpreter's DeferredFlag = true;
Now how do I know when the deferred execution ends? I can hardcode if I encounter the "def" name, but there might be others.

(+ What in case procedures are nested in a procedure that is executing. etc...)

I can't find a way to control that DeferredFlag in the interpreter to know the current execution mode.

Hope the question is clear.

Update:

Some extra code samples I try to debug without success.

code 1:

```<code>/foo { 2 3 add } def
foo
% result: 5
</code>```

code 2:

```<code>/foo { 2 3 add } def
//foo
% result: { 2 3 add }
</code>```

code 3:

```<code>/foo { 2 3 add } def
/bar { foo } def
bar
% result: 5
</code>```

code 4:

```<code>/foo { 2 3 add } def
/bar { //foo } def
bar
% result: { 2 3 add }
</code>```

答:
I had many of the same questions and confusions when trying to understand the interpreter. IMO the term deferred execution is not very useful. Additionally, I think the term immediately evaluated is also not very useful. You don't need a DeferredFlag.

There are two separate but related piece involved here: the interpreter loop, and the token operator.

token handles the part of "deferred execution" which collects all the tokens of an executable array into a single object. So if a file or string starts with a procedure body, then calling token on it yields the whole procedure body.

```<code>{ execution is deferred until the closing }
</code>```

It looks like a comment, but that is a line of postscript code which will run without errors even if none of the words deferred, closing, the etc. are defined. If you call exec on it, however, or define it as a name an call that, then it will execute and the contents had better be defined.

The interpreter loop always grabs the top object from the exec stack and semantically, executable arrays, files, and strings all behave the same. The interpreter treats it as a source and gets the first element. The name case is a little different, because it's not a source per se. (I am introducing this concept of my own hoping that it helps/works.) In C-ish pseudocode:

```<code>main_loop(){
    while( ! quit ){
        eval();
    }
}

eval(){
    object = pop( exec_stack );
    if( !executable_flag( object ) )  push( op_stack, object );
    else switch( type_of( object ) ){
        case array: array_handler( object ); break;
        case string: string_handler( object ); break;
        case file: file_handler( object ); break;
        case name: name_handler( object ); break;
        default: push( op_stack, object );
    }
}
</code>```

In the name case, look up the name and execute if executable.

```<code>name_handler( object ) {
    object = load( object );
    push( executable_flag( object ) ? exec_stack : op_stack, object );
}
</code>```

In the other three, you must also check if it is an array.

```<code>array_handler( object ){
    switch( length( object ){
    default:
        push( exec_stack, getinterval( object, 1, length( object ) - 1 ) );
        /* fall-thru */
    case 1:
        object = get( object, 0 );
        push( executable_flag( object ) && type_of( object ) != array ?
              exec_stack : op_stack, object );
    case 0:
        /* do nothing */
    }

}
</code>```

Only if executable_flag( object ) && type_of( object ) != array then you push to the exec stack.

For the other question, immediately-evaluated names, I prefer to call them immediately-loaded names. The token operator calls load on it before returning. Easy to handle if done in the right place. It has no real interaction with the "deferred-execution" part.

Edit:

I ran your sample through my debugger with tracing. This shows a running picture of the op_stack after each token is executed. The element on the left is the object returned by token. Notice that token has already consumed all the //s.

```<code>$ cat test.ps
(db5.ps) run currentfile cvx traceon debug

/foo { 2 3 add } def
foo
% result: 5

/foo { 2 3 add } def
//foo
% result: { 2 3 add }

/foo { 2 3 add } def
/bar { foo } def
bar
% result: 5

/foo { 2 3 add } def
/bar { //foo } def
bar
% result: { 2 3 add }

$ gsnd -DNOSAFER test.ps
GPL Ghostscript 9.19 (2016-03-23)
Copyright (C) 2016 Artifex Software, Inc.  All rights reserved.
This software comes with NO WARRANTY: see the file PUBLIC for details.
 %|-
/foo  %|- /foo
{2 3 add}  %|- /foo {2 3 add}
def  %|-
foo  %|- 5
/foo  %|- 5 /foo
{2 3 add}  %|- 5 /foo {2 3 add}
def  %|- 5
{2 3 add}  %|- 5 {2 3 add}
/foo  %|- 5 {2 3 add} /foo
{2 3 add}  %|- 5 {2 3 add} /foo {2 3 add}
def  %|- 5 {2 3 add}
/bar  %|- 5 {2 3 add} /bar
{foo}  %|- 5 {2 3 add} /bar {foo}
def  %|- 5 {2 3 add}
bar  %|- 5 {2 3 add} 5
/foo  %|- 5 {2 3 add} 5 /foo
{2 3 add}  %|- 5 {2 3 add} 5 /foo {2 3 add}
def  %|- 5 {2 3 add} 5
/bar  %|- 5 {2 3 add} 5 /bar
{{2 3 add}}  %|- 5 {2 3 add} 5 /bar {{2 3 add}}
def  %|- 5 {2 3 add} 5
bar GS<4>
GS<4>pstack
{2 3 add}
5
{2 3 add}
5
GS<4>
</code>```

Body:
I'm trying to wrap my head around the immediate and deferred execution.
From what I understand is that the interpreter maintains a flag that knows if it in deferred execution or not.

Deferred execution of a procedure could be because a name lookup returned a procedure.

Now I'm trying to find out what types, actions or operations control this interpreter flag.

For example this piece of code below has an immediately evaluated name at the end which returns an procedure. But this procedure is pushed, while it it is executable (xcheck):

/setdata
{
  /a 1 def
  /b 0 def

 /foo
   a 0 ne
   b 0 ne
   and
 def

 { foo false and }
} def

//setdata

I know there is a special rule:

Procedures appearing directly (either as part of a program being read
  from a file or as part of some larger procedure in memory) are usually
  part of a definition or of a construct, such as a conditional, that
  operates on the procedure explicitly. But procedures obtained
  indirectly—for example, as a result of looking up a name—are usually
  intended to be executed. A PostScript program can override these
  semantics when necessary.

I understand that if you encounter a procedure directly that you have to push it (even if it is executable). (The immediately evaluated name returns a procedure, which is encountered directly, so it should be pushed to the OS.)

Now if I'm thinking in code to implement this logic in an interpreter I can think of something like this:

If I have a literalname lookup, set the interpreter's DeferredFlag = true;
Now how do I know when the deferred execution ends? I can hardcode if I encounter the "def" name, but there might be others.

(+ What in case procedures are nested in a procedure that is executing. etc...)

I can't find a way to control that DeferredFlag in the interpreter to know the current execution mode.

Hope the question is clear.

Update:

Some extra code samples I try to debug without success.

code 1:

/foo { 2 3 add } def
foo
% result: 5

code 2:

/foo { 2 3 add } def
//foo
% result: { 2 3 add }

code 3:

/foo { 2 3 add } def
/bar { foo } def
bar
% result: 5

code 4:

/foo { 2 3 add } def
/bar { //foo } def
bar
% result: { 2 3 add }

Body:
I had many of the same questions and confusions when trying to understand the interpreter. IMO the term deferred execution is not very useful. Additionally, I think the term immediately evaluated is also not very useful. You don't need a DeferredFlag.

There are two separate but related piece involved here: the interpreter loop, and the token operator.

token handles the part of "deferred execution" which collects all the tokens of an executable array into a single object. So if a file or string starts with a procedure body, then calling token on it yields the whole procedure body.

{ execution is deferred until the closing }

It looks like a comment, but that is a line of postscript code which will run without errors even if none of the words deferred, closing, the etc. are defined. If you call exec on it, however, or define it as a name an call that, then it will execute and the contents had better be defined.

The interpreter loop always grabs the top object from the exec stack and semantically, executable arrays, files, and strings all behave the same. The interpreter treats it as a source and gets the first element. The name case is a little different, because it's not a source per se. (I am introducing this concept of my own hoping that it helps/works.) In C-ish pseudocode:

main_loop(){
    while( ! quit ){
        eval();
    }
}

eval(){
    object = pop( exec_stack );
    if( !executable_flag( object ) )  push( op_stack, object );
    else switch( type_of( object ) ){
        case array: array_handler( object ); break;
        case string: string_handler( object ); break;
        case file: file_handler( object ); break;
        case name: name_handler( object ); break;
        default: push( op_stack, object );
    }
}

In the name case, look up the name and execute if executable.

name_handler( object ) {
    object = load( object );
    push( executable_flag( object ) ? exec_stack : op_stack, object );
}

In the other three, you must also check if it is an array.

array_handler( object ){
    switch( length( object ){
    default:
        push( exec_stack, getinterval( object, 1, length( object ) - 1 ) );
        /* fall-thru */
    case 1:
        object = get( object, 0 );
        push( executable_flag( object ) && type_of( object ) != array ?
              exec_stack : op_stack, object );
    case 0:
        /* do nothing */
    }

}

Only if executable_flag( object ) && type_of( object ) != array then you push to the exec stack.

For the other question, immediately-evaluated names, I prefer to call them immediately-loaded names. The token operator calls load on it before returning. Easy to handle if done in the right place. It has no real interaction with the "deferred-execution" part.

Edit:

I ran your sample through my debugger with tracing. This shows a running picture of the op_stack after each token is executed. The element on the left is the object returned by token. Notice that token has already consumed all the //s.

$ cat test.ps
(db5.ps) run currentfile cvx traceon debug

/foo { 2 3 add } def
foo
% result: 5

/foo { 2 3 add } def
//foo
% result: { 2 3 add }

/foo { 2 3 add } def
/bar { foo } def
bar
% result: 5

/foo { 2 3 add } def
/bar { //foo } def
bar
% result: { 2 3 add }

$ gsnd -DNOSAFER test.ps
GPL Ghostscript 9.19 (2016-03-23)
Copyright (C) 2016 Artifex Software, Inc.  All rights reserved.
This software comes with NO WARRANTY: see the file PUBLIC for details.
 %|-
/foo  %|- /foo
{2 3 add}  %|- /foo {2 3 add}
def  %|-
foo  %|- 5
/foo  %|- 5 /foo
{2 3 add}  %|- 5 /foo {2 3 add}
def  %|- 5
{2 3 add}  %|- 5 {2 3 add}
/foo  %|- 5 {2 3 add} /foo
{2 3 add}  %|- 5 {2 3 add} /foo {2 3 add}
def  %|- 5 {2 3 add}
/bar  %|- 5 {2 3 add} /bar
{foo}  %|- 5 {2 3 add} /bar {foo}
def  %|- 5 {2 3 add}
bar  %|- 5 {2 3 add} 5
/foo  %|- 5 {2 3 add} 5 /foo
{2 3 add}  %|- 5 {2 3 add} 5 /foo {2 3 add}
def  %|- 5 {2 3 add} 5
/bar  %|- 5 {2 3 add} 5 /bar
{{2 3 add}}  %|- 5 {2 3 add} 5 /bar {{2 3 add}}
def  %|- 5 {2 3 add} 5
bar GS<4>
GS<4>pstack
{2 3 add}
5
{2 3 add}
5
GS<4>


问:
Dynamically creating Buttons and setting onClickListener
I have problem with handling dynamically created Buttons on Android. I'm creating N buttons and I have to do the same method when button is clicked but I have to know which button is clicked.

```<code>for (int i = 0; i < NO_BUTTONS; i++){
        Button btn = new Button(this);
        btn.setId(2000+i);

        ...

        btn.setOnClickListener((OnClickListener) this);
        buttonList.addView(btn);
        list.add(btn);
</code>```

Cucurrently I'm adding ID to every button and I'm using the method below to see which button was clicked. (line btn.setId(2000+i); and btn.setOnClickListener((OnClickListener) this);). This method is also implemented in the activity.

```<code>@Override
public void onClick(View v) {
    switch (v.getId()){
        case 2000: selectButton(0);
        break;

        ...

        case 2007: selectButton(7);
        break;
    }
 }
</code>```

This doesn't look good to me so i'm asking is there some better way to do this? or how to send some information to onclick event? any suggestions?

答: "This doesn't look good to me" why not? doesn't it work? You could also create a static member variable holding a list of all added buttons, and then look for the clicked button in that list instead.</p>

Body:
I have problem with handling dynamically created Buttons on Android. I'm creating N buttons and I have to do the same method when button is clicked but I have to know which button is clicked.

for (int i = 0; i < NO_BUTTONS; i++){
        Button btn = new Button(this);
        btn.setId(2000+i);

        ...

        btn.setOnClickListener((OnClickListener) this);
        buttonList.addView(btn);
        list.add(btn);

Cucurrently I'm adding ID to every button and I'm using the method below to see which button was clicked. (line btn.setId(2000+i); and btn.setOnClickListener((OnClickListener) this);). This method is also implemented in the activity.

@Override
public void onClick(View v) {
    switch (v.getId()){
        case 2000: selectButton(0);
        break;

        ...

        case 2007: selectButton(7);
        break;
    }
 }

This doesn't look good to me so i'm asking is there some better way to do this? or how to send some information to onclick event? any suggestions?

ContentLicense: CC BY-SA 2.5


问:
Confusion about Printing string arrays in C
This is probably a beginner question but it has been confusing me.  I understand that in c an array is itself a pointer to the first element of the array.  So consider the following example

```<code>char *words[LENGTH];
words[0] = "zero";
words[1] = "one";
words[2] = "two";
printf("%s\n",*words);
</code>```

What ends up printing is zero.  However, my understanding is that words is a pointer to the first element of the words array which is a char pointer => words is a pointer to a pointer to a char.  Therefore *words would be a pointer to char.  Therefore I would expect a memory address to be printed here and not an actual string.  What am I misunderstanding here?

答: Your understanding of what you have done up to the printf is spot on - as you've written it, *words is in fact a pointer to a char. The %s format specifier is for printing strings, so it assumes that whatever pointer you pass it is actually an array of chars that ends with a '\0' char - the format c uses for storing strings. With that information, printf knows that it should just print all of the characters in the array until it finds that '\0' - which is exactly what it has done in this case. If you do want to print the address of that pointer, the correct format specifier is (as mentioned in Stargateur's answer) %p.

Body:
This is probably a beginner question but it has been confusing me.  I understand that in c an array is itself a pointer to the first element of the array.  So consider the following example

char *words[LENGTH];
words[0] = "zero";
words[1] = "one";
words[2] = "two";
printf("%s\n",*words);

What ends up printing is zero.  However, my understanding is that words is a pointer to the first element of the words array which is a char pointer => words is a pointer to a pointer to a char.  Therefore *words would be a pointer to char.  Therefore I would expect a memory address to be printed here and not an actual string.  What am I misunderstanding here?


问:
Given final block not properly padded, encryption issue
I'm newbie in cipher, i always get this err

There is a service: http://aesencryption.net/
So i encrypted text in order to put service result in my test cases

```<code>key: passwd
original: mysecret
bytes: 128 (*don't know what it means but anyway..)
encrypted: EaDf/5rVXY3qMeQx1JmPCw==
</code>```

And i have this scala code

```<code>import javax.crypto.Cipher
import javax.crypto.spec.SecretKeySpec

import com.github.kondaurovdev.snippets.helper.{CryptoHelper, TryHelper}
import org.apache.commons.codec.binary.Base64

object Crypter {

  def apply(secret: String): Either[String, Crypter] = {
    for (
      s <- CryptoHelper.getSecretKey(secret).left.map(err => s"Can't get secretKeySpec: $err").right
    ) yield new Crypter(s)
  }

}

class Crypter(secretKey: SecretKeySpec) {

  def encrypt(input: String): Either[String, String] = {

    TryHelper.tryBlock({
      val cipher = Cipher.getInstance("AES/ECB/PKCS5Padding")
      cipher.init(Cipher.ENCRYPT_MODE, secretKey)
      val encrypted = cipher.doFinal(input.getBytes("UTF-8"))
      Base64.encodeBase64String(encrypted)
    }, "Can't encrypt text")

  }

  //input = base64 encoded string
  def decrypt(input: String): Either[String, String] = {

    for (
      res <- {
        TryHelper.tryBlock({
          val cipher = Cipher.getInstance("AES/ECB/PKCS5Padding")
          cipher.init(Cipher.DECRYPT_MODE, secretKey)
          val decrypted = cipher.doFinal(Base64.decodeBase64(input))
          new String(decrypted)
        }, "Error while decrypting")
      }.right
    ) yield res

  }

}

object CryptoHelper {

  def getSecretKey(myKey: String): Either[String, SecretKeySpec] = {
    TryHelper.tryBlock({
      var key = myKey.getBytes("UTF-8")
      val sha = MessageDigest.getInstance("SHA-1")
      key = sha.digest(key)
      key = util.Arrays.copyOf(key, 16) // use only first 128 bit
      new SecretKeySpec(key, "AES")
    }, "Can't build secretKey")
  }

}

object TryHelper {

  def tryBlock[R, E <: Throwable](block: => R, errPrefix: String = "", handle: errorPF = handlePF): Either[String, R] = {
    tryToEither(block).left.map(err => {
      var msg = err.getMessage
      if (errPrefix.nonEmpty) msg = s"$errPrefix: $msg"
      msg
    })
  }

}
</code>```

And i have this test cases:

```<code>import com.github.kondaurovdev.snippets.Crypter
import org.specs2.mutable.Specification

class CrypterSpec extends Specification {

  "Crypter" should {

    val crypter = Crypter("passwd")

    "decrypt" in {

      "case 1" in {
        crypter.right.flatMap(_.decrypt("eRKUj0EIXgyqzNFwHWYSLw==")) must beRight("asd")
      }

    }

    "encrypt" in {

      "case 1" in {
        crypter.right.flatMap(_.encrypt("asd")) must beRight("eRKUj0EIXgyqzNFwHWYSLw==")
      }

    }

  }

}
</code>```

But these tests don't pass..

```<code>> snippets/testOnly snippets.CrypterSpec
[info] CrypterSpec
[info]
[info] Crypter should
[info]   decrypt
[error]     x case 1
[error]      'Left(Error while decrypting: Given final block not properly padded)' is not Right (CrypterSpec.scala:15)
[info]
[info]   encrypt
[error]     x case 1
[error]      'Right(bVkPlx7E0OjhCWFyIHzM5Q==)' is Right but 'bVkPlx7E0OjhCWFyIHzM5Q==' is not equal to 'eRKUj0EIXgyqzNFwHWYSLw==' (CrypterSpec.scala:23)
[error] Actual:   bVkPlx7E0OjhCWFyIHzM5Q==
[error] Expected: eRKUj0EIXgyqzNFwHWYSLw==
[info]
[info]
[info]
[info] Total for specification CrypterSpec
[info] Finished in 6 minutes 3 seconds, 588 ms
[info] 2 examples, 2 failures, 0 error
[info]
[error] Failed: Total 2, Failed 2, Errors 0, Passed 0
[error] Failed tests:
[error]         snippets.CrypterSpec
[error] (snippets/test:testOnly) sbt.TestsFailedException: Tests unsuccessful
[error] Total time: 366 s, completed Jun 3, 2017 11:24:16 PM
</code>```

答:
Since I'm not a scala programmer I converted your code to what I thought was equivalent Java code. My results for encrypting "asd" match yours -- the output was bVkPlx7E0OjhCWFyIHzM5Q==. Therefore I conclude that your expectation that the output should be eRKUj0EIXgyqzNFwHWYSLw== is what's incorrect.

If you are using the website you referenced for test results, note that they probably are not using the same function to map a string into an AES key as you are. The recommended algorithms to convert low-entropy strings into symmetric keys include pbkdf2, bcrypt, scrypt, and the like. These are specifically designed for this scenario.

Body:
I'm newbie in cipher, i always get this err

There is a service: http://aesencryption.net/
So i encrypted text in order to put service result in my test cases

key: passwd
original: mysecret
bytes: 128 (*don't know what it means but anyway..)
encrypted: EaDf/5rVXY3qMeQx1JmPCw==

And i have this scala code

import javax.crypto.Cipher
import javax.crypto.spec.SecretKeySpec

import com.github.kondaurovdev.snippets.helper.{CryptoHelper, TryHelper}
import org.apache.commons.codec.binary.Base64

object Crypter {

  def apply(secret: String): Either[String, Crypter] = {
    for (
      s <- CryptoHelper.getSecretKey(secret).left.map(err => s"Can't get secretKeySpec: $err").right
    ) yield new Crypter(s)
  }

}

class Crypter(secretKey: SecretKeySpec) {

  def encrypt(input: String): Either[String, String] = {

    TryHelper.tryBlock({
      val cipher = Cipher.getInstance("AES/ECB/PKCS5Padding")
      cipher.init(Cipher.ENCRYPT_MODE, secretKey)
      val encrypted = cipher.doFinal(input.getBytes("UTF-8"))
      Base64.encodeBase64String(encrypted)
    }, "Can't encrypt text")

  }

  //input = base64 encoded string
  def decrypt(input: String): Either[String, String] = {

    for (
      res <- {
        TryHelper.tryBlock({
          val cipher = Cipher.getInstance("AES/ECB/PKCS5Padding")
          cipher.init(Cipher.DECRYPT_MODE, secretKey)
          val decrypted = cipher.doFinal(Base64.decodeBase64(input))
          new String(decrypted)
        }, "Error while decrypting")
      }.right
    ) yield res

  }

}

object CryptoHelper {

  def getSecretKey(myKey: String): Either[String, SecretKeySpec] = {
    TryHelper.tryBlock({
      var key = myKey.getBytes("UTF-8")
      val sha = MessageDigest.getInstance("SHA-1")
      key = sha.digest(key)
      key = util.Arrays.copyOf(key, 16) // use only first 128 bit
      new SecretKeySpec(key, "AES")
    }, "Can't build secretKey")
  }

}

object TryHelper {

  def tryBlock[R, E <: Throwable](block: => R, errPrefix: String = "", handle: errorPF = handlePF): Either[String, R] = {
    tryToEither(block).left.map(err => {
      var msg = err.getMessage
      if (errPrefix.nonEmpty) msg = s"$errPrefix: $msg"
      msg
    })
  }

}

And i have this test cases:

import com.github.kondaurovdev.snippets.Crypter
import org.specs2.mutable.Specification

class CrypterSpec extends Specification {

  "Crypter" should {

    val crypter = Crypter("passwd")

    "decrypt" in {

      "case 1" in {
        crypter.right.flatMap(_.decrypt("eRKUj0EIXgyqzNFwHWYSLw==")) must beRight("asd")
      }

    }

    "encrypt" in {

      "case 1" in {
        crypter.right.flatMap(_.encrypt("asd")) must beRight("eRKUj0EIXgyqzNFwHWYSLw==")
      }

    }

  }

}

But these tests don't pass..

> snippets/testOnly snippets.CrypterSpec
[info] CrypterSpec
[info]
[info] Crypter should
[info]   decrypt
[error]     x case 1
[error]      'Left(Error while decrypting: Given final block not properly padded)' is not Right (CrypterSpec.scala:15)
[info]
[info]   encrypt
[error]     x case 1
[error]      'Right(bVkPlx7E0OjhCWFyIHzM5Q==)' is Right but 'bVkPlx7E0OjhCWFyIHzM5Q==' is not equal to 'eRKUj0EIXgyqzNFwHWYSLw==' (CrypterSpec.scala:23)
[error] Actual:   bVkPlx7E0OjhCWFyIHzM5Q==
[error] Expected: eRKUj0EIXgyqzNFwHWYSLw==
[info]
[info]
[info]
[info] Total for specification CrypterSpec
[info] Finished in 6 minutes 3 seconds, 588 ms
[info] 2 examples, 2 failures, 0 error
[info]
[error] Failed: Total 2, Failed 2, Errors 0, Passed 0
[error] Failed tests:
[error]         snippets.CrypterSpec
[error] (snippets/test:testOnly) sbt.TestsFailedException: Tests unsuccessful
[error] Total time: 366 s, completed Jun 3, 2017 11:24:16 PM


问:
Load text file content using ajax
I have a HTML and CSS tab where i want to load the text content under each tab using ajax request from a .txt file. It means when we click on any tab then it loads the text content from .txt file. Content will be loaded first time a tabs get activated. First tab is already activated and text content loaded and showing under first tab but my issue is but when i click on second or third tab then it doesn't load the text content.
Code is live here: http://testweb.epizy.com/ajax-load/index.html

答:
Looking at your source code, I see that your JavaScript is supposed to run when the "checked" attribute of buttons 2 and 3 is set, but the checked attribute is meant for the default option in a radio selection--not for the currently selected option. When you change the tab the first button will still have the checked attribute because it is always the default. See this link for some more info on that.

I'd change your javascript to something like this:

```<code><script>
    $(document).ready(function() {
        if ($("#one").is(":checked")){
            $.ajax({
                url : "tab1.txt",
                dataType: "text",
                async:false,
                success : function (data) {
                    $(".tab1").html(data);
                }
            });
        };
    });
    function loadOne() {
        $.ajax({
            url : "tab1.txt",
            dataType: "text",
            async:false,
            success : function (data) {
                $(".tab1").html(data);
            }
        });
    }
    function loadTwo() {
        $.ajax({
            url : "tab2.txt",
            dataType: "text",
            async:false,
            success : function (data) {
                $(".tab2").html(data);
            }
        });
    }
    function loadThree() {
        $.ajax({
            url : "tab3.txt",
            dataType: "text",
            async:false,
            success : function (data) {
                $(".tab3").html(data);
            }
        });
    }
</script>
</code>```

And then adding an onclick event to the three buttons (not positive if this would go on the <input> or the ), so add onclick=loadOne() for the first button, loadTwo() for the second, and loadThree() for the third.

My code is probably a little redundant, I'm a bit of a beginner, but hopefully this helps.

Title: Load text file content using ajax

Body:
Looking at your source code, I see that your JavaScript is supposed to run when the "checked" attribute of buttons 2 and 3 is set, but the checked attribute is meant for the default option in a radio selection--not for the currently selected option. When you change the tab the first button will still have the checked attribute because it is always the default. See this link for some more info on that.

I'd change your javascript to something like this:

<script>
    $(document).ready(function() {
        if ($("#one").is(":checked")){
            $.ajax({
                url : "tab1.txt",
                dataType: "text",
                async:false,
                success : function (data) {
                    $(".tab1").html(data);
                }
            });
        };
    });
    function loadOne() {
        $.ajax({
            url : "tab1.txt",
            dataType: "text",
            async:false,
            success : function (data) {
                $(".tab1").html(data);
            }
        });
    }
    function loadTwo() {
        $.ajax({
            url : "tab2.txt",
            dataType: "text",
            async:false,
            success : function (data) {
                $(".tab2").html(data);
            }
        });
    }
    function loadThree() {
        $.ajax({
            url : "tab3.txt",
            dataType: "text",
            async:false,
            success : function (data) {
                $(".tab3").html(data);
            }
        });
    }
</script>

And then adding an onclick event to the three buttons (not positive if this would go on the <input> or the <label>), so add onclick=loadOne() for the first button, loadTwo() for the second, and loadThree() for the third.

My code is probably a little redundant, I'm a bit of a beginner, but hopefully this helps.


问:
How do i get right row in history table
I have table with price history:

```<code>| StrartDat | ProductID | Price | EndDate|
</code>```

Table of products:

```<code>| ProductID | Name | quantity|...|
</code>```

And table of orders:

```<code>| OrderID |ProductID | date|...|
</code>```

Now i am trying to get list of orders but i get two rows for one product with its old price and new one (where enddate is null)

How can i escape such situation and get order with a price that a product had at date of order.

I tried this constrains but it doesn't take a orders that are linked with price where enddate is null

```<code>  Where EndDate > OrderCustm.Date AND StartDate <= OrderCustm.Date
</code>```

答:
If I understand correctly, you can just add an explicit NULL condition:

```<code>Where StartDate <= OrderCustm.Date AND
      (EndDate > OrderCustm.Date OR EndDate IS NULL)
</code>```

Title: How do i get right row in history table

Body:
I have table with price history:

| StrartDat | ProductID | Price | EndDate|

Table of products:

| ProductID | Name | quantity|...|

And table of orders:

| OrderID |ProductID | date|...|

Now i am trying to get list of orders but i get two rows for one product with its old price and new one (where enddate is null)

How can i escape such situation and get order with a price that a product had at date of order.

I tried this constrains but it doesn't take a orders that are linked with price where enddate is null

  Where EndDate > OrderCustm.Date AND StartDate <= OrderCustm.Date

Body:
If I understand correctly, you can just add an explicit NULL condition:

Where StartDate <= OrderCustm.Date AND
      (EndDate > OrderCustm.Date OR EndDate IS NULL)


问:
OrderBy In A HasAndBelongsToMany Relation
Hi can I get help from an expert in ActiveRecord?

I am looking for a solution for a HasAndBelongsToMany relation. I currently have the following

```<code>    [HasAndBelongsToMany(Table = "SupplierRecordUrls",ColumnKey = "SupplierID", ColumnRef = "RecordUrlID", Lazy = true, OrderBy="??")]
    public virtual IList<RecordUrl> RecordUrls
    {
        get;
        set;
    }
</code>```

How do I order the above relation by a column in "RecordUrl", for example ... "Name Asc". I have tried referencing a column directly in the class RecordUrl but I receive a "cannot find column "xxxxxx" error.

Any help is much appreciated.

答:
You can find a OrderBy in a HABTM relation here.

Add Sort to your relation definition, create a Comparer that implements IComparer and that will do the trick.

In your code, that will give somthing like this :

```<code>[HasAndBelongsToMany(Table = "SupplierRecordUrls",ColumnKey = "SupplierID", ColumnRef = "RecordUrlID", Lazy = true, Sort="MyProject.RecordUrlNameComparer, MyProject.RecordUrl")]
public virtual IList<RecordUrl> RecordUrls
{
    get;
    set;
}
</code>```

With :

```<code>public class RecordUrlNameComparer: IComparer<RecordUrl>
{
    Int32 System.Collections.Generic.IComparer<RecordUrl>.Compare( RecordUrl x, RecordUrl y )
    {
        return new System.Collections.Comparer( System.Globalization.CultureInfo.CurrentCulture ).Compare( x.Name, y.Name );
    }
} // public class RecordUrlNameComparer: IComparer<RecordUrl>
</code>```

I let you read the article :)

Edit :

Your error is now : Could not instantiate comparator class [MyProject.RecordUrl.RecordUrlComparer, MyProject.RecordUrl] for collection MyProject.Supplier.RecordUrls

What I would do :

Create the Comparer as an inner class of RecordUrls.

Change the Sort to : Sort = "MyProject.Supplier.RecordUrl$RecordUrlComparer, MyProject.Supplier.RecordUrl"

If it still doesn't work, you still get the "couldn't instantiate" error, try making the Comparer class static. I'm not sure how it is used, but if it's a static call, that may do the trick :)

Body:
Hi can I get help from an expert in ActiveRecord?

I am looking for a solution for a HasAndBelongsToMany relation. I currently have the following

    [HasAndBelongsToMany(Table = "SupplierRecordUrls",ColumnKey = "SupplierID", ColumnRef = "RecordUrlID", Lazy = true, OrderBy="??")]
    public virtual IList<RecordUrl> RecordUrls
    {
        get;
        set;
    }

How do I order the above relation by a column in "RecordUrl", for example ... "Name Asc". I have tried referencing a column directly in the class RecordUrl but I receive a "cannot find column "xxxxxx" error.

Any help is much appreciated.

Body:
You can find a OrderBy in a HABTM relation here.

Add Sort to your relation definition, create a Comparer that implements IComparer and that will do the trick.

In your code, that will give somthing like this :

[HasAndBelongsToMany(Table = "SupplierRecordUrls",ColumnKey = "SupplierID", ColumnRef = "RecordUrlID", Lazy = true, Sort="MyProject.RecordUrlNameComparer, MyProject.RecordUrl")]
public virtual IList<RecordUrl> RecordUrls
{
    get;
    set;
}

With :

public class RecordUrlNameComparer: IComparer<RecordUrl>
{
    Int32 System.Collections.Generic.IComparer<RecordUrl>.Compare( RecordUrl x, RecordUrl y )
    {
        return new System.Collections.Comparer( System.Globalization.CultureInfo.CurrentCulture ).Compare( x.Name, y.Name );
    }
} // public class RecordUrlNameComparer: IComparer<RecordUrl>

I let you read the article :)

Edit :

Your error is now : Could not instantiate comparator class [MyProject.RecordUrl.RecordUrlComparer, MyProject.RecordUrl] for collection MyProject.Supplier.RecordUrls

What I would do :

Create the Comparer as an inner class of RecordUrls.

Change the Sort to : Sort = "MyProject.Supplier.RecordUrl$RecordUrlComparer, MyProject.Supplier.RecordUrl"

If it still doesn't work, you still get the "couldn't instantiate" error, try making the Comparer class static. I'm not sure how it is used, but if it's a static call, that may do the trick :)


问:
efficiency of inverting a matrix in numpy with Cholesky decomposition
I have a symmetric positive-definite matrix (e.g. Covariance matrix), and I want to calculate its inverse. In math, I know that it is more efficient to use Cholesky decomposition to invert the matrix, especially if your matrix is big. But I was not sure how does "numpy.lianlg.inv()" works. Say I have the following code:

```<code>import numpy as np

X = np.arange(10000).reshape(100,100)
X = X + X.T - np.diag(X.diagonal()) #  symmetry
X = np.dot(X,X.T) # positive-definite

# simple inversion:
inverse1 = np.linalg.inv(X)

# Cholesky decomposition inversion:
c = np.linalg.inv(np.linalg.cholesky(X))
inverse2 = np.dot(c.T,c)
</code>```

Which one is more efficient (inverse1 or inverse2)? If the second one is more efficient, why is numpy.linalg.inv() not using this instead?

答:
With the following setup:

```<code>import numpy as np

N = 100
X = np.linspace(0, 1, N*N).reshape(N, N)
X = 0.5*(X + X.T) + np.eye(N) * N
</code>```

I get the following timings with IPython's %timeit:

```<code>In [28]: %timeit np.linalg.inv(X)
255 µs ± 30.9 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [29]: %timeit c = np.linalg.inv(np.linalg.cholesky(X)); np.dot(c.T,c)
414 µs ± 15.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
</code>```

Body:
I have a symmetric positive-definite matrix (e.g. Covariance matrix), and I want to calculate its inverse. In math, I know that it is more efficient to use Cholesky decomposition to invert the matrix, especially if your matrix is big. But I was not sure how does "numpy.lianlg.inv()" works. Say I have the following code:

import numpy as np

X = np.arange(10000).reshape(100,100)
X = X + X.T - np.diag(X.diagonal()) #  symmetry
X = np.dot(X,X.T) # positive-definite

# simple inversion:
inverse1 = np.linalg.inv(X)

# Cholesky decomposition inversion:
c = np.linalg.inv(np.linalg.cholesky(X))
inverse2 = np.dot(c.T,c)

Which one is more efficient (inverse1 or inverse2)? If the second one is more efficient, why is numpy.linalg.inv() not using this instead?

Body:
With the following setup:

import numpy as np

N = 100
X = np.linspace(0, 1, N*N).reshape(N, N)
X = 0.5*(X + X.T) + np.eye(N) * N

I get the following timings with IPython's %timeit:

In [28]: %timeit np.linalg.inv(X)
255 µs ± 30.9 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [29]: %timeit c = np.linalg.inv(np.linalg.cholesky(X)); np.dot(c.T,c)
414 µs ± 15.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)


问:
Cannot read property 'props' of undefined error
I'm trying to child to parent communication so, i'm using props. There's have a little problem. I get an error when I use the StatusChanged() function.

There is my parent (App.JS) file:

```<code>class App extends Component {

  constructor(props) {
    super(props);
    this.state = { trackingStatus: true };
  }

  trackingStatusUpdate(data)
  {
      console.log(data);
  }

  render() {
    return (
      <div className="App">
        <Switcher trackingStatus={this.state.trackingStatus} trackingStatusUpdate={this.trackingStatusUpdate} />
      </div>
    );
  }
}
</code>```

And There is my child (Switcher.JS) file:

```<code>class Switcher extends Component {

    constructor(props) {
        super(props);
        this.state = {
            trackingStatus: this.props.trackingStatus
        };
    }

    statusChanged()
    {
        this.props.trackingStatusUpdate(this.state.trackingStatus);
    }

    render() {
        return (
            <div>
                <h3>Tracking Mode</h3>
                <label className="switch">
                  <input type="checkbox" defaultChecked={this.state.trackingStatus} onChange={this.statusChanged}  id="switch"  />
                  <div className="slider round"></div>
                </label>
            </div>
        );
    }

}

Switcher.defaultProps = {
    trackingStatus: true
}
</code>```

What is the problem?

Thank you.

答:
You need to bind the trackingStatusUpdate() and statusChanged() class methods…

```<code>class App extends Component{
  constructor(props){
    super(props);
    this.state = {trackingStatus: true};

    this.trackingStatusUpdate = this.trackingStatusUpdate.bind(this);
  }

  ...
}

class Switcher extends Component{
  constructor(props){
    super(props);
    this.state = {trackingStatus: this.props.trackingStatus};

    this.statusChanged = this.statusChanged.bind(this);
  }

  ...
}
</code>```

Body:
I'm trying to child to parent communication so, i'm using props. There's have a little problem. I get an error when I use the StatusChanged() function.

There is my parent (App.JS) file:

class App extends Component {

  constructor(props) {
    super(props);
    this.state = { trackingStatus: true };
  }

  trackingStatusUpdate(data)
  {
      console.log(data);
  }

  render() {
    return (

        <Switcher trackingStatus={this.state.trackingStatus} trackingStatusUpdate={this.trackingStatusUpdate} />

    );
  }
}

And There is my child (Switcher.JS) file:

class Switcher extends Component {

    constructor(props) {
        super(props);
        this.state = {
            trackingStatus: this.props.trackingStatus
        };
    }

    statusChanged()
    {
        this.props.trackingStatusUpdate(this.state.trackingStatus);
    }

    render() {
        return (

Tracking Mode

                  <input type="checkbox" defaultChecked={this.state.trackingStatus} onChange={this.statusChanged}  id="switch"  />

        );
    }

}

Switcher.defaultProps = {
    trackingStatus: true
}

What is the problem?

Thank you.

Body:
You need to bind the trackingStatusUpdate() and statusChanged() class methods…

class App extends Component{
  constructor(props){
    super(props);
    this.state = {trackingStatus: true};

    this.trackingStatusUpdate = this.trackingStatusUpdate.bind(this);
  }

  ...
}

class Switcher extends Component{
  constructor(props){
    super(props);
    this.state = {trackingStatus: this.props.trackingStatus};

    this.statusChanged = this.statusChanged.bind(this);
  }

  ...
}


问:
Cookie Saves as two different urls
On my website, when users sign up or login, my site sometimes saves the cookie to "mywebsiteurl.com" and sometimes saves it to "www.mywebsiteurl.com".  In doing this, my code only works half the time.  Is there a way I can fix this issue from happening?</p>

答:
Set cookie in your PHP for your root domain and setcookie() will automatically make it available for all subdomains:

```<code>setcookie('cookiename', 'cookievalue', $someTimeToExpire, '/', 'mywebsiteurl.com');
</code>```

Title: Cookie Saves as two different urls

Body:
Set cookie in your PHP for your root domain and setcookie() will automatically make it available for all subdomains:

setcookie('cookiename', 'cookievalue', $someTimeToExpire, '/', 'mywebsiteurl.com');


问:
How to implement Interactive user guides?
I'm trying to build an interactive user guide for an application. Basically when its the users first time using the application they will be offered a tour of the site. It'll be pretty much done with a series of modal pop up boxes and focusing on elements.

My problem is i can't find a way to get control of the cursor to move it to certain locations of the page, is there a way to achieve this with JS, Jquery or CSS? Or is there any plugins available?

答: You can have a look at Bootstrap Tour or Joyride Plugin</p>


答:
char *words[LENGTH]; defines an array of char*, i.e. char**. *words equals to words[0] which refers to "zero".

It is not safe to create such char* array. For example, the following code compiles OK, but its behavior is undefined.

```<code>char *words[1];
words[0] = "zero";
words[1] = "one";
words[2] = "two";
printf("%s\n", words[2]);
</code>```

Title: Confusion about Printing string arrays in C

Body:
char *words[LENGTH]; defines an array of char*, i.e. char**. *words equals to words[0] which refers to "zero".

It is not safe to create such char* array. For example, the following code compiles OK, but its behavior is undefined.

char *words[1];
words[0] = "zero";
words[1] = "one";
words[2] = "two";
printf("%s\n", words[2]);


问:
Java minesweeper game problem. hiding mines when the game begins?
I've been able to successfully initiate a minefield when the game begins with 10 mines randomly scattered over the field. However, I'm having problems hiding these mines from the user when the game begins. As you know, the point of minesweeper is to find where the mines are WITHOUT being able to see them. I need help figuring out how to hide the mines.

Below is the code I have written for my Grid class which initiates the grid and includes a method which fills it with mines. How can I hide these mines and only reveal them when they are clicked on? Thanks for the help!

```<code>public class Grid {

 private int[][] grid;
 private boolean isHidden;
 private  int rows;
 private final int columns;
 private final int mines;

 public Grid() {
  this.rows = 8;
  this.columns = 8;
  this.mines = 10;
  this.grid = new int[rows][columns];

 }

 public int[][] getGrid() {
  return grid;
 }

 public int getRows() {
  return rows;
 }

 public int getColumns() {
  return columns;
  }

 public void fillGrid() {
  Random ranGen = new Random();

  for(int i = 0; i < this.mines; ) {
   int row = ranGen.nextInt(this.rows - 1);
   int column = ranGen.nextInt(this.columns - 1);

   if(grid[row][column] != MinesweeperGUI.MINE) {
    grid[row][column] = MinesweeperGUI.MINE;
    i++;
   }
  }
    }
</code>```

答: Why doesn't your grid matrix contains elements of the class GridElement? This GridElement class could have an property "bool visibile". An grid matrix of int's isn't so good. Think more OO.</p>

Body:
I've been able to successfully initiate a minefield when the game begins with 10 mines randomly scattered over the field. However, I'm having problems hiding these mines from the user when the game begins. As you know, the point of minesweeper is to find where the mines are WITHOUT being able to see them. I need help figuring out how to hide the mines.

Below is the code I have written for my Grid class which initiates the grid and includes a method which fills it with mines. How can I hide these mines and only reveal them when they are clicked on? Thanks for the help!

public class Grid {

 private int[][] grid;
 private boolean isHidden;
 private  int rows;
 private final int columns;
 private final int mines;

 public Grid() {
  this.rows = 8;
  this.columns = 8;
  this.mines = 10;
  this.grid = new int[rows][columns];

 }

 public int[][] getGrid() {
  return grid;
 }

 public int getRows() {
  return rows;
 }

 public int getColumns() {
  return columns;
  }

 public void fillGrid() {
  Random ranGen = new Random();

  for(int i = 0; i < this.mines; ) {
   int row = ranGen.nextInt(this.rows - 1);
   int column = ranGen.nextInt(this.columns - 1);

   if(grid[row][column] != MinesweeperGUI.MINE) {
    grid[row][column] = MinesweeperGUI.MINE;
    i++;
   }
  }
    }


问:
Invalid operands to binary expression error...when creating ratio
```<code>double profit_ratio = ((double) definitive_seller_profit) / ((double)definitive_buyer_profit);

        if(definitive_buyer_profit > definitive_seller_profit){

            if(definitive_buyer_move < 0 && definitive_seller_move < 0 && profit_ratio >= 0.50){ // give seller a chance if it's on the way and at least 50% profit ratio

                if((definitive_buyer_move < definitive_seller_move)){
                    *n = to_fuel_or_not_to_fuel(b, definitive_seller_move, fuel_ratio);
                } else {
                    *n = to_fuel_or_not_to_fuel(b, definitive_buyer_move, fuel_ratio);
                }
            }

            } else if(definitive_buyer_move > 0 && definitive_seller_move > 0 &&  && profit_ratio >= 0.50){

                if(definitive_buyer_move > definitive_seller_move){

                    *n = to_fuel_or_not_to_fuel(b, definitive_seller_move, fuel_ratio);
                }
                else {
                    *n = to_fuel_or_not_to_fuel(b, definitive_buyer_move, fuel_ratio);
                }

            } else{

                *n = to_fuel_or_not_to_fuel(b, definitive_buyer_move, fuel_ratio);

            }

        }
</code>```

So I'm getting invalid operands to binary expression ('void*'and 'double') in line:

else if(definitive_buyer_move > 0 && definitive_seller_move > 0 &&  && profit_ratio >= 0.50)

And I'm also getting...undeclared label 'profit_ratio.'

答:
&&  && has no meaning in:

```<code>else if(definitive_buyer_move > 0 && definitive_seller_move > 0 &&  && profit_ratio >= 0.50){
</code>```

hence the invalid operands.

For the undeclared label, fixing the previous error might solve the issue or

definitive_buyer_profit does not exist;

definitive_seller_profit does not exist;

definitive_buyer_profit has a type that has no casting to double;

definitive_seller_profit has a type that has no casting to double

Anyway, your entire provided code is a bunch of if-else if-else for calling the same function in all cases. In this situation, consider using another (more readable, IMO) approach e.g.

```<code>if (b_profit > s_profit)
{
    const bool both_move_neg = b_move < 0 && s_move < 0;
    const bool both_move_pos = b_move > 0 && s_move > 0;
    const bool high_ratio = 2*abs(s_profit) >= abs(b_profit);
    const bool pick_s = ((both_move_neg && b_move < s_move) ||
                         (both_move_pos && s_move < b_move)) && high_ratio;

    *n = to_fuel_or_not_to_fuel(b, pick_s ? s_move : b_move, fuel_ratio);
}
</code>```

requiring (notice that this is C99 code)

```<code>#include <stdbool.h>
#include <stdlib.h>
#include <math.h>
</code>```

where I renamed your variable to more convenient names (to_fuel_or_not_to_fuel could undergo the same treatment; maybe fuel or conditional_fuel?) and I assumed s_profit and b_profit to be ints.

After having tried to edit your post, I realized how messy your code was! Not only are my previous remarks (about naming and using more readable conditions) still true but you must work on you indentation (and brackets)!

See by yourself: By indenting your code "properly" based on what you provide, I get

```<code>double profit_ratio = ((double) definitive_seller_profit) / ((double) definitive_buyer_profit);

if (definitive_buyer_profit > definitive_seller_profit){
    if (definitive_buyer_move < 0 && definitive_seller_move < 0 && profit_ratio >= 0.50){
        // give seller a chance if it's on the way and at least 50% profit ratio
        if (definitive_buyer_move < definitive_seller_move){
            *n = to_fuel_or_not_to_fuel(b, definitive_seller_move, fuel_ratio);
        } else {
            *n = to_fuel_or_not_to_fuel(b, definitive_buyer_move, fuel_ratio);
        }
    }
} else if (definitive_buyer_move > 0 && definitive_seller_move > 0 &&  && profit_ratio >= 0.50){
    if (definitive_buyer_move > definitive_seller_move){
        *n = to_fuel_or_not_to_fuel(b, definitive_seller_move, fuel_ratio);
    } else {
        *n = to_fuel_or_not_to_fuel(b, definitive_buyer_move, fuel_ratio);
    }
} else {
    *n = to_fuel_or_not_to_fuel(b, definitive_buyer_move, fuel_ratio);
}
}
</code>```

Notice two things:

The if { if {...} else if {...} else {...} } that your indentation is implying is not what your wrote (remember that space characters have no meaning in C and are ignored);

The last } has no corresponding {.

The last point makes me think that the undeclared label errors comes from the fact that when you are using the variable in the conditions (else) if (/*...*/ profit_ratio >= 0) your terrible indentation lead to mismatching brackets which themselves lead to the definition of profit_ratio being trapped in another block of code, leading to it being undefined where it is used.

Finally, notice that the error about profit_ratio might actually come (as I implied) from the conditions and not from its definition (with the ratio). Therefore, it would have been more effective for you to include the line at which the error was detected.

So, in conclusion, you should:

Write readable code;

Understand what you compiler says;

Write readable questions;

Add the relevant information to these questions.

Body:
double profit_ratio = ((double) definitive_seller_profit) / ((double)definitive_buyer_profit);

        if(definitive_buyer_profit > definitive_seller_profit){

            if(definitive_buyer_move < 0 && definitive_seller_move < 0 && profit_ratio >= 0.50){ // give seller a chance if it's on the way and at least 50% profit ratio

                if((definitive_buyer_move < definitive_seller_move)){
                    *n = to_fuel_or_not_to_fuel(b, definitive_seller_move, fuel_ratio);
                } else {
                    *n = to_fuel_or_not_to_fuel(b, definitive_buyer_move, fuel_ratio);
                }
            }

            } else if(definitive_buyer_move > 0 && definitive_seller_move > 0 &&  && profit_ratio >= 0.50){

                if(definitive_buyer_move > definitive_seller_move){

                    *n = to_fuel_or_not_to_fuel(b, definitive_seller_move, fuel_ratio);
                }
                else {
                    *n = to_fuel_or_not_to_fuel(b, definitive_buyer_move, fuel_ratio);
                }

            } else{

                *n = to_fuel_or_not_to_fuel(b, definitive_buyer_move, fuel_ratio);

            }

        }

So I'm getting invalid operands to binary expression ('void*'and 'double') in line:

else if(definitive_buyer_move > 0 && definitive_seller_move > 0 &&  && profit_ratio >= 0.50)

And I'm also getting...undeclared label 'profit_ratio.'

Body:
&&  && has no meaning in:

else if(definitive_buyer_move > 0 && definitive_seller_move > 0 &&  && profit_ratio >= 0.50){

hence the invalid operands.

For the undeclared label, fixing the previous error might solve the issue or

definitive_buyer_profit does not exist;

definitive_seller_profit does not exist;

definitive_buyer_profit has a type that has no casting to double;

definitive_seller_profit has a type that has no casting to double

Anyway, your entire provided code is a bunch of if-else if-else for calling the same function in all cases. In this situation, consider using another (more readable, IMO) approach e.g.

if (b_profit > s_profit)
{
    const bool both_move_neg = b_move < 0 && s_move < 0;
    const bool both_move_pos = b_move > 0 && s_move > 0;
    const bool high_ratio = 2*abs(s_profit) >= abs(b_profit);
    const bool pick_s = ((both_move_neg && b_move < s_move) ||
                         (both_move_pos && s_move < b_move)) && high_ratio;

    *n = to_fuel_or_not_to_fuel(b, pick_s ? s_move : b_move, fuel_ratio);
}

requiring (notice that this is C99 code)

#include <stdbool.h>
#include <stdlib.h>
#include <math.h>

where I renamed your variable to more convenient names (to_fuel_or_not_to_fuel could undergo the same treatment; maybe fuel or conditional_fuel?) and I assumed s_profit and b_profit to be ints.

After having tried to edit your post, I realized how messy your code was! Not only are my previous remarks (about naming and using more readable conditions) still true but you must work on you indentation (and brackets)!

See by yourself: By indenting your code "properly" based on what you provide, I get

double profit_ratio = ((double) definitive_seller_profit) / ((double) definitive_buyer_profit);

if (definitive_buyer_profit > definitive_seller_profit){
    if (definitive_buyer_move < 0 && definitive_seller_move < 0 && profit_ratio >= 0.50){
        // give seller a chance if it's on the way and at least 50% profit ratio
        if (definitive_buyer_move < definitive_seller_move){
            *n = to_fuel_or_not_to_fuel(b, definitive_seller_move, fuel_ratio);
        } else {
            *n = to_fuel_or_not_to_fuel(b, definitive_buyer_move, fuel_ratio);
        }
    }
} else if (definitive_buyer_move > 0 && definitive_seller_move > 0 &&  && profit_ratio >= 0.50){
    if (definitive_buyer_move > definitive_seller_move){
        *n = to_fuel_or_not_to_fuel(b, definitive_seller_move, fuel_ratio);
    } else {
        *n = to_fuel_or_not_to_fuel(b, definitive_buyer_move, fuel_ratio);
    }
} else {
    *n = to_fuel_or_not_to_fuel(b, definitive_buyer_move, fuel_ratio);
}
}

Notice two things:

The if { if {...} else if {...} else {...} } that your indentation is implying is not what your wrote (remember that space characters have no meaning in C and are ignored);

The last } has no corresponding {.

The last point makes me think that the undeclared label errors comes from the fact that when you are using the variable in the conditions (else) if (/*...*/ profit_ratio >= 0) your terrible indentation lead to mismatching brackets which themselves lead to the definition of profit_ratio being trapped in another block of code, leading to it being undefined where it is used.

Finally, notice that the error about profit_ratio might actually come (as I implied) from the conditions and not from its definition (with the ratio). Therefore, it would have been more effective for you to include the line at which the error was detected.

So, in conclusion, you should:

Write readable code;

Understand what you compiler says;

Write readable questions;

Add the relevant information to these questions.


问:
Managed DLL injection?
Basically I want to take a c# dll, encrypt it and save this as a file. Then another application opens this file decrypt it back into a byte array and without saving this to a file call a method in this decrypted buffer in memory. So far I have only been able to do this on unmanaged dll but I was wondering if there was anyone here who could help me get an idea of what I should do since I found almost no info after spending hours on google.</p>

答: Check out Assembly.Load(byte[]) at https://msdn.microsoft.com/en-us/library/h538bck7(v=vs.110).aspx

Title: Managed DLL injection?


问:
Log-in to Website
I'm trying to create an Excel macro that will log me into this website. I've written macros to log me into to other websites, but this one is somehow different.

When I use the following code to programmatically insert the username and password and then programmatically click the "log-in" button, the webpage comes back with the message

Error: please provide a username and Error: Please provide a
  password

```<code>Sub LogIn()
' Open IE and navigate to the log-in page
    Set ie = CreateObject("InternetExplorer.Application")

    With ie
        .Visible = True
        .navigate "https://www.prudential.com/login"

' Loop until the page is fully loaded
        Do Until Not ie.Busy And ie.ReadyState = 4
            DoEvents
        Loop
        Application.Wait (Now + TimeValue("0:00:10"))

' Enter the necessary information on the Login web page and click the submit button
        ie.document.getElementById("username").Value = "abcdef"
        ie.document.getElementById("password").Value = "12345678"
        ie.document.getElementsByClassName("btn btn-primary btn-login btn-sm-block analytics-login")(0).Click

' Loop until the page is fully loaded
        Do Until Not ie.Busy And ie.ReadyState = 4
             DoEvents
        Loop
    End With

' Do stuff

' Quit IE
    ie.Quit
End Sub
</code>```

I can see that my code has inserted the username and password into the webpage boxes, but for some reason after successfully clicking the submit button, the username and password are not being detected.

What code will successfully insert the username and password so that it can be processed by the web page?  You'll know that your code works when you get the following error message:

We are unable to verify your username and password. Please try again.

Thanks for your help!

答:
It actually wants you to send a key, so you can bypass this request like this:

```<code>ie.document.getElementById("username").Focus
ie.document.getElementById("username").Value = "abcde"
Application.SendKeys "f", True

ie.document.getElementById("password").Focus
ie.document.getElementById("password").Value = "1234567"
Application.SendKeys "8", True

ie.document.getElementsByClassName("btn btn-primary btn-login btn-sm-block analytics-login")(0).Click
</code>```

Edit:

```<code>Sub GetData()
    Dim ie As InternetExplorer
    Dim desc As IHTMLElement
    Set ie = New InternetExplorer
    With ie
        .navigate "https://www.prudential.com/login"
        .Visible = True
    End With

    Do While (ie.Busy Or ie.ReadyState <> READYSTATE_COMPLETE)
        DoEvents
    Loop

    ie.document.getElementById("username").Focus
    Application.SendKeys "abcdef"
    Application.Wait (Now + TimeValue("0:00:01"))

    ie.document.getElementById("password").Focus
    Application.SendKeys "12345678"
    Application.Wait (Now + TimeValue("0:00:01"))

    ie.document.getElementsByClassName("btn btn-primary btn-login btn-sm-block analytics-login")(0).Click

    Set ie = Nothing
End Sub
</code>```

Title: Log-in to Website

Body:
I'm trying to create an Excel macro that will log me into this website. I've written macros to log me into to other websites, but this one is somehow different.

When I use the following code to programmatically insert the username and password and then programmatically click the "log-in" button, the webpage comes back with the message

Error: please provide a username and Error: Please provide a
  password

Sub LogIn()
' Open IE and navigate to the log-in page
    Set ie = CreateObject("InternetExplorer.Application")

    With ie
        .Visible = True
        .navigate "https://www.prudential.com/login"

' Loop until the page is fully loaded
        Do Until Not ie.Busy And ie.ReadyState = 4
            DoEvents
        Loop
        Application.Wait (Now + TimeValue("0:00:10"))

' Enter the necessary information on the Login web page and click the submit button
        ie.document.getElementById("username").Value = "abcdef"
        ie.document.getElementById("password").Value = "12345678"
        ie.document.getElementsByClassName("btn btn-primary btn-login btn-sm-block analytics-login")(0).Click

' Loop until the page is fully loaded
        Do Until Not ie.Busy And ie.ReadyState = 4
             DoEvents
        Loop
    End With

' Do stuff

' Quit IE
    ie.Quit
End Sub

I can see that my code has inserted the username and password into the webpage boxes, but for some reason after successfully clicking the submit button, the username and password are not being detected.

What code will successfully insert the username and password so that it can be processed by the web page?  You'll know that your code works when you get the following error message:

We are unable to verify your username and password. Please try again.

Thanks for your help!

Body:
It actually wants you to send a key, so you can bypass this request like this:

ie.document.getElementById("username").Focus
ie.document.getElementById("username").Value = "abcde"
Application.SendKeys "f", True

ie.document.getElementById("password").Focus
ie.document.getElementById("password").Value = "1234567"
Application.SendKeys "8", True

ie.document.getElementsByClassName("btn btn-primary btn-login btn-sm-block analytics-login")(0).Click

Edit:

Sub GetData()
    Dim ie As InternetExplorer
    Dim desc As IHTMLElement
    Set ie = New InternetExplorer
    With ie
        .navigate "https://www.prudential.com/login"
        .Visible = True
    End With

    Do While (ie.Busy Or ie.ReadyState <> READYSTATE_COMPLETE)
        DoEvents
    Loop

    ie.document.getElementById("username").Focus
    Application.SendKeys "abcdef"
    Application.Wait (Now + TimeValue("0:00:01"))

    ie.document.getElementById("password").Focus
    Application.SendKeys "12345678"
    Application.Wait (Now + TimeValue("0:00:01"))

    ie.document.getElementsByClassName("btn btn-primary btn-login btn-sm-block analytics-login")(0).Click

    Set ie = Nothing
End Sub


问:
Reactfire, aren't mixins deprecated?
I am browsing the reactfire github and they use mixins.

I thought they were deprecated? Am I behind the times?

答:
Apart from re-base, also have a look at react-redux-firebase as mentioned in this reactfire discussion:

react-redux-firebase

Redux bindings for Firebase. Includes Higher Order Component for use with React.

http://react-redux-firebase.com

https://github.com/prescottprue/react-redux-firebase

Title: Reactfire, aren't mixins deprecated?


问:
Avoid default date (Jan 1900) in sql server varchar column
I have a experience table in my sql sever database having following columns:

```<code>exp_id int,
u_id int ,
exp_jobtitle varchar(100),
exp_company varchar(100),
exp_startdate date,
exp_enddate varchar(50),
exp_working varchar(50),
exp_description varchar(2000),
</code>```

If I am currently working in that particular job then nothing is inserted in exp_enddate column but Currently Working in exp_working column.

And in the frontend I am showing the result like this:

If my job is ended May 2015 - June 2015 and the problem occurs when I am currently working

I want this output May 2015 - Currently Working And I'm getting output like this

```<code>May 2015 - Jan 1900Currently Working
</code>```

Through this query :-

```<code>select right(convert(varchar(50), cast('exp_enddate' as date), 106), 8)
</code>```

How can I avoid this default date or Is there any other way to get the desired output?

```<code>May 2015 - Currently Working
</code>```

答:
If you are dealing with an empty string for the end date then SQL Server will automatically treat this as 1/1/1990.

You can see this by running the below query:

```<code>SELECT CAST( '' AS DATE )
</code>```

This returns 1900-01-01.

What you can do is check if the end date is empty, and if so, treat it as currently working, like this:

```<code>SELECT
    CASE
        WHEN exp_enddate = ''
        THEN 'Currently Working'
        ELSE RIGHT( CONVERT( VARCHAR(50), CAST( exp_enddate AS DATE ), 106 ), 8 )
    END
</code>```

This will either return the end date in your provided format, or 'currently working'.

Body:
I have a experience table in my sql sever database having following columns:

exp_id int,
u_id int ,
exp_jobtitle varchar(100),
exp_company varchar(100),
exp_startdate date,
exp_enddate varchar(50),
exp_working varchar(50),
exp_description varchar(2000),

If I am currently working in that particular job then nothing is inserted in exp_enddate column but Currently Working in exp_working column.

And in the frontend I am showing the result like this:

If my job is ended May 2015 - June 2015 and the problem occurs when I am currently working

I want this output May 2015 - Currently Working And I'm getting output like this

May 2015 - Jan 1900Currently Working

Through this query :-

select right(convert(varchar(50), cast('exp_enddate' as date), 106), 8)

How can I avoid this default date or Is there any other way to get the desired output?

May 2015 - Currently Working

Body:
If you are dealing with an empty string for the end date then SQL Server will automatically treat this as 1/1/1990.

You can see this by running the below query:

SELECT CAST( '' AS DATE )

This returns 1900-01-01.

What you can do is check if the end date is empty, and if so, treat it as currently working, like this:

SELECT
    CASE
        WHEN exp_enddate = ''
        THEN 'Currently Working'
        ELSE RIGHT( CONVERT( VARCHAR(50), CAST( exp_enddate AS DATE ), 106 ), 8 )
    END

This will either return the end date in your provided format, or 'currently working'.


问:
Python - instance of class as a parameters of another class method
My task is to rewrite app written in Java using Python. It is my first contact with Python and I'm a bit confused. As I read, Python is not strongly typed. In my program I have a lot of classes with methods with parameters which are instances of other classes. Here is a short demo:

```<code>class ClassA:

    nameOfClass = "ClassA"

    def __init__(self):
        print("I'm ClassA")

    def printOtherClassMethod(self, instanceOfOtherClass):
        instanceOfOtherClass.printThisMethod()

class ClassB:
    nameOfClass = "ClassA"

    def __init__(self):
        print("I'm ClassB")

    def printThisMethod(self):
        print("How classA can know that printThisMethod exists?")

classA = ClassA()
classB = ClassB()
classA.printOtherClassMethod(classB)
</code>```

Is there any way to specify that argument of printOtherClassMethod must be instance of ClassB? The first problem is that my IDE (PyCharm) can't detect that instanceOfOtherClass has printThisMethod and it is very easy to make mistake. Additionally, I have a practise to have each class in the individual file. I'm afraid of importing particular files. For example if ClassA and ClassB would be in individual files should I import ClassB in file of ClassA? My tests show that not, but I want to avoid milions of exceptions and error in the future.

答:
You can validate the type of the object.

```<code>if type(instanceOfOtherClass) not is ClassB:
    raise Exception("Object has the wrong type.")
</code>```

You can also check that the object has that particular method.

```<code>if not (hasattr(instanceOfOtherClass, 'printThisMethod') and callable(instanceOfOtherClass.printThisMethod)):
    raise Exception("Object does not have the correct method.")
</code>```

Body:
My task is to rewrite app written in Java using Python. It is my first contact with Python and I'm a bit confused. As I read, Python is not strongly typed. In my program I have a lot of classes with methods with parameters which are instances of other classes. Here is a short demo:

class ClassA:

    nameOfClass = "ClassA"

    def __init__(self):
        print("I'm ClassA")

    def printOtherClassMethod(self, instanceOfOtherClass):
        instanceOfOtherClass.printThisMethod()

class ClassB:
    nameOfClass = "ClassA"

    def __init__(self):
        print("I'm ClassB")

    def printThisMethod(self):
        print("How classA can know that printThisMethod exists?")

classA = ClassA()
classB = ClassB()
classA.printOtherClassMethod(classB)

Is there any way to specify that argument of printOtherClassMethod must be instance of ClassB? The first problem is that my IDE (PyCharm) can't detect that instanceOfOtherClass has printThisMethod and it is very easy to make mistake. Additionally, I have a practise to have each class in the individual file. I'm afraid of importing particular files. For example if ClassA and ClassB would be in individual files should I import ClassB in file of ClassA? My tests show that not, but I want to avoid milions of exceptions and error in the future.

Body:
You can validate the type of the object.

if type(instanceOfOtherClass) not is ClassB:
    raise Exception("Object has the wrong type.")

You can also check that the object has that particular method.

if not (hasattr(instanceOfOtherClass, 'printThisMethod') and callable(instanceOfOtherClass.printThisMethod)):
    raise Exception("Object does not have the correct method.")


问:
How do I search for packages using yarn?
How do I search for packages with yarn?
I want to get a list of results that have the search term in the name of the package as well as in descriptions (similar to how various utilities work like npm search, apropos, apt-cache search).

I tried yarn info <pkg>, but this gave a bunch of json data that was limited to just that package.

Using yarn help and duckduckgo was educational, but still didn't answer how to do this.

答:
I use npms-cli:

Install:

```<code>yarn global add npms-cli
</code>```

Then you will have available /usr/bin/npms and can search like: npms search <desired package>.

Body:
I use npms-cli:

Install:

yarn global add npms-cli

Then you will have available /usr/bin/npms and can search like: npms search <desired package>.


问:
Change string in other class (without making it global) in swift
I would like to modify a string in another class. This class will then use the variable in a function.

Here is what I've tried so far. I always get an error when unwrapping it: fatal error: unexpectedly found nil while unwrapping an Optional value. Does anyone have an idea how to change the urlString (preferably without making it global)? I couldn't find solutions for swift which also involved functions on stackoverflow... If you think I will have to make it global, please let me know!

In class #1

```<code>let videoUrl =  "https:...sometestvideo.mov"
videoPlayerView.urlString = videoUrl
</code>```

In class #2

```<code>var urlString : String?

//setup video player
func setupPlayerView() {

    print(urlString)

    //URL needed here
    if let videoURL = NSURL(string: urlString!){ //here the error occurs
</code>```

I would like to add that it is very important that the function is called asap in the second class. Therefore I didn't use setupPlayerView(_urlString)...

Accordingly it currently looks like this (class 2, a UIView):

```<code>override init(frame: CGRect){

    super.init(frame: frame)

    //function below this override init
    setupPlayerView()
</code>```

EDIT:

First of all, thank you for your solution! Nonetheless, one little problem remains (and I thought calling the function immediately would solve it... quite new to swift): namely the video player (which is set up using this function) is now above all the other subviews (one can only see the video covering the entire screen) although the opposite is desired (video using entire screen but subviews cover some parts). I will provide more code below regarding the addition of other subviews (all of these are closures) and the function setting up the view. Is there a way I can keep the videoplayer below all the other subviews (even if it needs to be loaded from a server first)? What would you suggest me to do?

Code below incorporates code from the first answer, but does not necessarily have to start from there

Class 2

```<code>override init(frame: CGRect){

    super.init(frame: frame)

    setupPlayerView()

    //add subview with controls (e.g. spinner)
    controlsContainerView.frame = frame
    addSubview(controlsContainerView)

    //add to subview and center spinner in subview
    controlsContainerView.addSubview(activityIndicatorView)
    activityIndicatorView.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
    activityIndicatorView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true

    //add various subviews
    controlsContainerView.addSubview(whiteDummyView)
    controlsContainerView.addSubview(userProfilePicture)
    //... add further subviews

    //enable interaction
    controlsContainerView.isUserInteractionEnabled = true
    //... set to true for other subviews as well

    //function below this override init
    defInteractions()

    //backgorund color of player
    backgroundColor = .black

}

//create controls container view (a closure, like the (most of the) other subviews)
let controlsContainerView: UIView = {

    //set properties of controls container view
    let controlView = UIView()
    controlView.backgroundColor = UIColor(white: 0, alpha: 1)

    return controlView

}()
</code>```

function setupPlayerView()

```<code>//setup video player
func setupPlayerView() {

    //check URL if can be converted to NSURL
    if let urlString = self.urlString, let videoURL = NSURL(string: urlString){

        print(urlString)

        //player's video
        if self.player == nil {
            player = AVPlayer(url: videoURL as URL)
        }

        //add sub-layer
        let playerLayer = AVPlayerLayer(player: player)
        self.controlsContainerView.layer.addSublayer(playerLayer)
        playerLayer.frame = self.frame

        //when are frames actually rendered (when is video loaded)
        player?.addObserver(self, forKeyPath: "currentItem.loadedTimeRanges", options: .new, context: nil)

        //loop through video
        NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: self.player?.currentItem, queue: nil, using: { (_) in
            DispatchQueue.main.async {
                self.player?.seek(to: kCMTimeZero)
                self.player?.play()
            }
        })

    }

}
</code>```

答:
While navigating to second view controller.

```<code> let viewController2 = ViewController2() //viewController2 == class2
 viewController2.urlString = videoUrl // anything you want to pass to class2.
 navigationController?.pushViewController(viewController2, animated: true)
</code>```

In your class 2:

```<code>var urlString: String = ""

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        print(urlString) // use it
        setupPlayerView()
    }
</code>```

Your func:

```<code>func setupPlayerView() {

        //check URL if can be converted to NSURL
        if  NSURL(string: urlString) != nil{

            print(urlString)

        }
    }
</code>```

Body:
I would like to modify a string in another class. This class will then use the variable in a function.

Here is what I've tried so far. I always get an error when unwrapping it: fatal error: unexpectedly found nil while unwrapping an Optional value. Does anyone have an idea how to change the urlString (preferably without making it global)? I couldn't find solutions for swift which also involved functions on stackoverflow... If you think I will have to make it global, please let me know!

In class #1

let videoUrl =  "https:...sometestvideo.mov"
videoPlayerView.urlString = videoUrl

In class #2

var urlString : String?

//setup video player
func setupPlayerView() {

    print(urlString)

    //URL needed here
    if let videoURL = NSURL(string: urlString!){ //here the error occurs

I would like to add that it is very important that the function is called asap in the second class. Therefore I didn't use setupPlayerView(_urlString)...

Accordingly it currently looks like this (class 2, a UIView):

override init(frame: CGRect){

    super.init(frame: frame)

    //function below this override init
    setupPlayerView()

EDIT:

First of all, thank you for your solution! Nonetheless, one little problem remains (and I thought calling the function immediately would solve it... quite new to swift): namely the video player (which is set up using this function) is now above all the other subviews (one can only see the video covering the entire screen) although the opposite is desired (video using entire screen but subviews cover some parts). I will provide more code below regarding the addition of other subviews (all of these are closures) and the function setting up the view. Is there a way I can keep the videoplayer below all the other subviews (even if it needs to be loaded from a server first)? What would you suggest me to do?

Code below incorporates code from the first answer, but does not necessarily have to start from there

Class 2

override init(frame: CGRect){

    super.init(frame: frame)

    setupPlayerView()

    //add subview with controls (e.g. spinner)
    controlsContainerView.frame = frame
    addSubview(controlsContainerView)

    //add to subview and center spinner in subview
    controlsContainerView.addSubview(activityIndicatorView)
    activityIndicatorView.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
    activityIndicatorView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true

    //add various subviews
    controlsContainerView.addSubview(whiteDummyView)
    controlsContainerView.addSubview(userProfilePicture)
    //... add further subviews

    //enable interaction
    controlsContainerView.isUserInteractionEnabled = true
    //... set to true for other subviews as well

    //function below this override init
    defInteractions()

    //backgorund color of player
    backgroundColor = .black

}

//create controls container view (a closure, like the (most of the) other subviews)
let controlsContainerView: UIView = {

    //set properties of controls container view
    let controlView = UIView()
    controlView.backgroundColor = UIColor(white: 0, alpha: 1)

    return controlView

}()

function setupPlayerView()

//setup video player
func setupPlayerView() {

    //check URL if can be converted to NSURL
    if let urlString = self.urlString, let videoURL = NSURL(string: urlString){

        print(urlString)

        //player's video
        if self.player == nil {
            player = AVPlayer(url: videoURL as URL)
        }

        //add sub-layer
        let playerLayer = AVPlayerLayer(player: player)
        self.controlsContainerView.layer.addSublayer(playerLayer)
        playerLayer.frame = self.frame

        //when are frames actually rendered (when is video loaded)
        player?.addObserver(self, forKeyPath: "currentItem.loadedTimeRanges", options: .new, context: nil)

        //loop through video
        NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: self.player?.currentItem, queue: nil, using: { (_) in
            DispatchQueue.main.async {
                self.player?.seek(to: kCMTimeZero)
                self.player?.play()
            }
        })

    }

}

Body:
While navigating to second view controller.

 let viewController2 = ViewController2() //viewController2 == class2
 viewController2.urlString = videoUrl // anything you want to pass to class2.
 navigationController?.pushViewController(viewController2, animated: true)

In your class 2:

var urlString: String = ""

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        print(urlString) // use it
        setupPlayerView()
    }

Your func:

func setupPlayerView() {

        //check URL if can be converted to NSURL
        if  NSURL(string: urlString) != nil{

            print(urlString)

        }
    }


问:
How do I find the time complexity (Big O) of while loop?
Code 1

```<code>int i = 0;
int j = 0;
while(i < n){
     while(j < n){
        printf("{%d,%d}",arr[i],arr[j]);
        j++;
    }
    i++;
    j = 0;
    printf("\n");
}
</code>```

Code 2

```<code>int result = 0;
int i = 0;
while (i < n / 2){
    result += arr[i];
    i += 1;
    while (i >= n / 2 && i < n){
        result += arr[i];
        i += 1;
    }
}
printf("%d\n", result);
</code>```

I only know how to find time complexity with for loops, but I am uncertain about while loop.
It would be greatly appreciated if someone could help me find the total running time of each code.

答:
A for loop, at the end of the day, IS a while loop. Something of the form:

```<code>for(int i=0; i<n; i++)
</code>```

is equivalent to:

```<code>int i=0;

while(i<n)
{
 i++;
}
</code>```

In fact in pure mathematical analysis of algorithms you are supposed to make any for loop into a while loop in your algorithms (there are a couple reasons why).

Going back to your code. The analysis is simple:

Before the first iteration of the while loop the value of i is 0.

There exists a unique statement that updates the variable i (i++).

On every iteration of the outer loop i increases by 1.

The outer loop runs at most n times.

Before the iteration of any loop the value of j is 0.

There are 2 statements that update j (j=0 and j++)

Informally: we can tell before any iteration of the inner loop the value of j is 0.

Inside the inner loop the only statement that updates j is j++.

on every iteration of the inner loop j increases by 1.

The inner loop runs at most n times by the loop guard.

The outer loop runs at most n times, the inner loop runs at most n times for every iteration of the outer loop. All other statements are constant. The algorithm is in O(n*n)=O(n^2)

The second one is slightly more convoluted but:

Before the first iteration of the outer loop the value of i is 0.

Informally: the outer loop will run until the value of i is (n/2 - 1)

The update statement (i += 1) updates i to (n/2)

Informally: the inner loop runs (n-n/2 = n/2) times and it runs exactly once.
-The outer loop runs n/2 times, the inner loop runs n/2 times exactly once.

The algorithm thus runs O(n/2+n/2) = O(n) times

Body:
Code 1

int i = 0;
int j = 0;
while(i < n){
     while(j < n){
        printf("{%d,%d}",arr[i],arr[j]);
        j++;
    }
    i++;
    j = 0;
    printf("\n");
}

Code 2

int result = 0;
int i = 0;
while (i < n / 2){
    result += arr[i];
    i += 1;
    while (i >= n / 2 && i < n){
        result += arr[i];
        i += 1;
    }
}
printf("%d\n", result);

I only know how to find time complexity with for loops, but I am uncertain about while loop.
It would be greatly appreciated if someone could help me find the total running time of each code.

Body:
A for loop, at the end of the day, IS a while loop. Something of the form:

for(int i=0; i<n; i++)

is equivalent to:

int i=0;

while(i<n)
{
 i++;
}

In fact in pure mathematical analysis of algorithms you are supposed to make any for loop into a while loop in your algorithms (there are a couple reasons why).

Going back to your code. The analysis is simple:

Before the first iteration of the while loop the value of i is 0.

There exists a unique statement that updates the variable i (i++).

On every iteration of the outer loop i increases by 1.

The outer loop runs at most n times.

Before the iteration of any loop the value of j is 0.

There are 2 statements that update j (j=0 and j++)

Informally: we can tell before any iteration of the inner loop the value of j is 0.

Inside the inner loop the only statement that updates j is j++.

on every iteration of the inner loop j increases by 1.

The inner loop runs at most n times by the loop guard.

The outer loop runs at most n times, the inner loop runs at most n times for every iteration of the outer loop. All other statements are constant. The algorithm is in O(n*n)=O(n^2)

The second one is slightly more convoluted but:

Before the first iteration of the outer loop the value of i is 0.

Informally: the outer loop will run until the value of i is (n/2 - 1)

The update statement (i += 1) updates i to (n/2)

Informally: the inner loop runs (n-n/2 = n/2) times and it runs exactly once.
-The outer loop runs n/2 times, the inner loop runs n/2 times exactly once.

The algorithm thus runs O(n/2+n/2) = O(n) times

ContentLicense: CC BY-SA 4.0