问:
at&t asm inline c++ problem

My Code

```<code>const int howmany = 5046;
char buffer[howmany];
    asm("lea     buffer,%esi"); //Get the address of buffer
    asm("mov     howmany,%ebx");         //Set the loop number
    asm("buf_loop:");                      //Lable for beginning of loop
    asm("movb     (%esi),%al");             //Copy buffer[x] to al
    asm("inc     %esi");                   //Increment buffer address
    asm("dec     %ebx");                   //Decrement loop count
    asm("jnz     buf_loop");              //jump to buf_loop if(ebx>0)
</code>```

My Problem

I am using the gcc compiler. For some reason my buffer/howmany variables are undefined in the eyes of my asm. I'm not sure why. I just want to move the beginning address of my buffer array into the esi register, loop it 'howmany' times while copying each element to the al register.

答:
All of those asm instructions need to be in the same asm statement if you want to be sure they're contiguous (without compiler-generated code between them), and you need to declare input / output / clobber operands or you will step on the compiler's registers.

You can't use lea or mov to/from a C variable name (except for global / static symbols which are actually defined in the compiler's asm output, but even then you usually shouldn't).

Instead of using mov instructions to set up inputs, ask the compiler to do it for you using input operand constraints.  If the first or last instruction of a GNU C inline asm statement, usually that means you're doing it wrong and writing inefficient code.

And BTW, GNU C++ allows C99-style variable-length arrays, so howmany is allowed to be non-const and even set in a way that doesn't optimize away to a constant.  Any compiler that can compile GNU-style inline asm will also support variable-length arrays.

How to write your loop properly

If this looks over-complicated, then https://gcc.gnu.org/wiki/DontUseInlineAsm.  Write a stand-alone function in asm so you can just learn asm instead of also having to learn about gcc and its complex but powerful inline-asm interface.  You basically have to know asm and understand compilers to use it correctly (with the right constraints to prevent breakage when optimization is enabled).

Note the use of named operands like %[ptr] instead of %2 or %%ebx.  Letting the compiler choose which registers to use is normally a good thing, but for x86 there are letters other than "r" you can use, like "=a" for rax/eax/ax/al specifically.  See https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html, and also other links in the inline-assembly tag wiki.

I also used buf_loop%=: to append a unique number to the label, so if the optimizer clones the function or inlines it multiple places, the file will still assemble.

Source + compiler asm output on the Godbolt compiler explorer.

```<code>void ext(char *);

int foo(void)
{
    int howmany = 5046;   // could be a function arg
    char buffer[howmany];
    //ext(buffer);

    const char *bufptr = buffer;  // copy the pointer to a C var we can use as a read-write operand
    unsigned char result;
    asm("buf_loop%=:  \n\t"                 // do {
        "   movb     (%[ptr]), %%al \n\t"   // Copy buffer[x] to al
        "   inc     %[ptr]        \n\t"
        "   dec     %[count]      \n\t"
        "   jnz     buf_loop      \n\t"      // } while(ebx>0)
       :   [res]"=a"(result)      // al = write-only output
         , [count] "+r" (howmany) // input/output operand, any register
         , [ptr] "+r" (bufptr)
       : // no input-only operands
       : "memory"   // we read memory that isn't an input operand, only pointed to by inputs
    );
    return result;
}
</code>```

I used %%al as an example of how to write register names explicitly: Extended Asm (with operands) needs a double % to get a literal % in the asm output.  You could also use %[res] or %0 and let the compiler substitute %al in its asm output.  (And then you'd have no reason to use a specific-register constraint unless you wanted to take advantage of cbw or lodsb or something like that.)  result is unsigned char, so the compiler will pick a byte register for it.  If you want the low byte of a wider operand, you could use %b[count] for example.

This uses a "memory" clobber, which is inefficient.  You don't need the compiler to spill everything to memory, only to make sure that the contents of buffer[] in memory matches the C abstract machine state.  (This is not guaranteed by passing a pointer to it in a register).

gcc7.2 -O3 output:

```<code>    pushq   %rbp
    movl    $5046, %edx
    movq    %rsp, %rbp
    subq    $5056, %rsp
    movq    %rsp, %rcx         # compiler-emitted to satisfy our "+r" constraint for bufptr
    # start of the inline-asm block
    buf_loop18:
       movb     (%rcx), %al
       inc     %rcx
       dec     %edx
       jnz     buf_loop
    # end of the inline-asm block

    movzbl  %al, %eax
    leave
    ret
</code>```

Without a memory clobber or input constraint, leave appears before the inline asm block, releasing that stack memory before the inline asm uses the now-stale pointer.  A signal-handler running at the wrong time would clobber it.

A more efficient way is to use a dummy memory operand which tells the compiler that the entire array is a read-only memory input to the asm statement.  See get string length in inline GNU Assembler for more about this flexible-array-member trick for telling the compiler you read all of an array without specifying the length explicitly.

In C you can define a new type inside a cast, but you can't in C++, hence the using instead of a really complicated input operand.

```<code>int bar(unsigned howmany)
{
    //int howmany = 5046;
    char buffer[howmany];
    //ext(buffer);
    buffer[0] = 1;
    buffer[100] = 100;   // test whether we got the input constraints right

    //using input_t = const struct {char a[howmany];};  // requires a constant size
    using flexarray_t = const struct {char a; char x[];};
    const char *dummy;
    unsigned char result;
    asm("buf_loop%=:  \n\t"                 // do {
        "   movb     (%[ptr]), %%al \n\t"   // Copy buffer[x] to al
        "   inc     %[ptr]        \n\t"
        "   dec     %[count]      \n\t"
        "   jnz     buf_loop      \n\t"      // } while(ebx>0)
       : [res]"=a"(result)        // al = write-only output
         , [count] "+r" (howmany) // input/output operand, any register
         , "=r" (dummy)           // output operand in the same register as buffer input, so we can modify the register
       : [ptr] "2" (buffer)     // matching constraint for the dummy output
         , "m" (*(flexarray_t *) buffer)  // whole buffer as an input operand

           //, "m" (*buffer)        // just the first element: doesn't stop the buffer[100]=100 store from sinking past the inline asm, even if you used asm volatile
       : // no clobbers
    );
    buffer[100] = 101;
    return result;
}
</code>```

I also used a matching constraint so buffer could be an input directly, and the output operand in the same register means we can modify that register.  We got the same effect in foo() by using const char *bufptr = buffer; and then using a read-write constraint to tell the compiler that the new value of that C variable is what we leave in the register.  Either way we leave a value in a dead C variable that goes out of scope without being read, but the matching constraint way can be useful for macros where you don't want to modify the value of your input (and don't need the type of your input: int dummy would work fine, too.)

The buffer[100] = 100; and buffer[100] = 101; assignments are there to show that they both appear in the asm, instead of being merged across the inline-asm (which does happen if you leave out the "m" input operand).  IDK why the buffer[100] = 101; isn't optimized away; it's dead so it should be.  Also note that asm volatile doesn't block this reordering, so it's not an alternative to a "memory" clobber or using the right constraints.

Title: at&t asm inline c++ problem

Body:
My Code

const int howmany = 5046;
char buffer[howmany];
    asm("lea     buffer,%esi"); //Get the address of buffer
    asm("mov     howmany,%ebx");         //Set the loop number
    asm("buf_loop:");                      //Lable for beginning of loop
    asm("movb     (%esi),%al");             //Copy buffer[x] to al
    asm("inc     %esi");                   //Increment buffer address
    asm("dec     %ebx");                   //Decrement loop count
    asm("jnz     buf_loop");              //jump to buf_loop if(ebx>0)

My Problem

I am using the gcc compiler. For some reason my buffer/howmany variables are undefined in the eyes of my asm. I'm not sure why. I just want to move the beginning address of my buffer array into the esi register, loop it 'howmany' times while copying each element to the al register.

Body:
All of those asm instructions need to be in the same asm statement if you want to be sure they're contiguous (without compiler-generated code between them), and you need to declare input / output / clobber operands or you will step on the compiler's registers.

You can't use lea or mov to/from a C variable name (except for global / static symbols which are actually defined in the compiler's asm output, but even then you usually shouldn't).

Instead of using mov instructions to set up inputs, ask the compiler to do it for you using input operand constraints.  If the first or last instruction of a GNU C inline asm statement, usually that means you're doing it wrong and writing inefficient code.

And BTW, GNU C++ allows C99-style variable-length arrays, so howmany is allowed to be non-const and even set in a way that doesn't optimize away to a constant.  Any compiler that can compile GNU-style inline asm will also support variable-length arrays.

How to write your loop properly

If this looks over-complicated, then https://gcc.gnu.org/wiki/DontUseInlineAsm.  Write a stand-alone function in asm so you can just learn asm instead of also having to learn about gcc and its complex but powerful inline-asm interface.  You basically have to know asm and understand compilers to use it correctly (with the right constraints to prevent breakage when optimization is enabled).

Note the use of named operands like %[ptr] instead of %2 or %%ebx.  Letting the compiler choose which registers to use is normally a good thing, but for x86 there are letters other than "r" you can use, like "=a" for rax/eax/ax/al specifically.  See https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html, and also other links in the inline-assembly tag wiki.

I also used buf_loop%=: to append a unique number to the label, so if the optimizer clones the function or inlines it multiple places, the file will still assemble.

Source + compiler asm output <a href="https://gcc.godbolt.org/#z:OYLghAFBqd5QCxAYwPYBMCmBRdBLAF1QCcAaPECAKxAEZSBnVAV2OUxAHIA3VPdANSYAHgQjIEAQ2ICAVAEoApAGYAQooAMAQU1a8AOwICAZqlQRe/eQN2KA7Ou0DnAg0YSoA7gFtJ%2BgJ42ygAiAgCsGgAsAGwqjlouAhLSAgBGzMbGmMSKYaoePn7%2BucFxuokA9BUiYumZ2Upqtk4uaPoMRskysnUADgQyKqF1WTlqzlVJqL2BBAiYAr18htkCRAKSAgDCAtwpngvIfgLMDAuSDBsCxJiS6AC0nsSEC9PZfujlLszteMD6mEEXWumAYzAANgQyi1nBdvBBFAAmRF1AD64LMvSRYSGIGcuS2%2BgJUORiTJ5ImFQE6FQNgcX3JSMRLm8qG4qTJCMROLy/RyYWC8lINm52Mk4JsYUJxKZLkmW2mgRG2VyqmEJTWtPFDLJsucBmQutFvIGGopBKJUpJiJ1iT11MwhrtxtUaB%2BUIFjKllq21ttLntVH0AC8yWiMdMvdKrfa5VT7KFPAg8ODMBBMKl1cpsBolDDEnj8XkbgwSkyhpImRASxCCNYyZNxUFE88CJh7qh9ODAiwCL1mFD82Thaq3YYNeXEaocqSIAVfAFrJMDP2CBVe6uBG9iB9hUUQcA8B0VUPEiOTfzQpPp7KIH0BnmEuS8ZN9LSVwOO12e713vp0KWp4CHiTLeJgrLEMUpKUgIBwgncAhgRBsxSEYR76GAnBGMcH5GNuu5bt%2BizLG2gjrKkgS4YBT7OI08SJDcBCsPoIJgpC0I6HYpTaM0eiGGk0gQD8DB/ACgjzkUj72PRcZuAIEkBM24RRLETT5sCyr8vkXgLsUAocZU1SiHeGSjHROqaaqGgTiEAi0AZLiWXktAaNZnpDHZrlxHGaygkYSaYHMqxwcAqBGEFrj6JubQdDubiXM8wAIIOOj5lUpwGMAkWrqiRgeTFRixcwyB5Q4wKVnkCl6aUTRcd5AiTDcACOzB4CWVwFX4hV4MGmA6hl%2BhZcYqbCNIO7%2BLlSkFQIRUlXSrpSDIlbjMC6p5GWtU1TJzjTcCsjoMw3jeMUak0Scvz/ICSSLaxtYObCDDwky4aYtiuJFtGvqxhS5KTDS83%2Bvi0GIWyHKJFyPKqHyJRCiKOLck2FoysD8qKmkpkqnka2hOs2pASKzL6voToBi60Oeua3rIza%2BP2lgJNA5DY4eqEupUzGyKAwTLhBqGiQvZGbOfdav3xlxsHJqm6aZioOaPhSIHFqCZacyElbItWoK1vWosbBKHlPC8X7dluA6rlzAjnq6LDju5nNTjOzJzjpkkNVSuHrmbA5br%2BO7/nuik3Iex45PjlsE0MjsCBAB1Hf4Os/ZMG7e/h/6RWs8wzZIYEHkebZLZcmnZQOwpMLBhzHKy%2BDGChCxB3nJ5nS4itQ6adv207mkJ27iGSAQEiZVM7QDJIcmmDIEWx8dpt9gOFsjsi3i3rIEDDSIY2SBNRgKOj9TEPWkxJqgqa76MGyXDhUUp77Hy8T9cYL4iS%2Bzj0GP74nVJUKc4WZ8YbUdEIVMYFDB4hpKCDCWEZpEF6BnBYTlVAuTcjVYIiCoEkAWMYYgqBvAzQMAAa0Hr0C4P8FgGHBAYc4j1hSYG4JgFieBjACH8CwE4ZxBBwl2MfPuKY%2BpARfFSN8SQMSpFSNkaiiRzL5ngYgmyoQXL2VOgxQKzFbrsVOgmXinAhTgi4GETgpB9BcA0Po1AXAthInUFOGaLA2ALCRMoWg%2BiCBGK0UKPBIAYgADoACcdhlCIkiHYSItBETRFoIE7kpAdGcEiPowxnBjGkFMZwfRDAQAaFIM4hJWjSBwFgDARAKBsG9B4WQCg4himlJAMAOwiJSB/0hGIygqQXGkFSAYaQ/guCONIGgI6dCCAAHlvytKwAuYAqZRltUdAQPAtC0nZNICIR0A4OCcB6W4TA0SekDDwN4bpOTyGpDSZAIU0xZmdgWfcDonwQj/GYBYixtBaACHuAAdXFBKe4gzlCpJsewOg2jdFxNack4QAAOaI9xoiRAEMAZAho7CeKdrgQgJARQOOFAqbwJTUyDERA4%2BQTiXHyDcSAMIyhPEaFCXYMI3JwV%2BPBXS2lUSuCxNIPs8FiJPGBLpbygJtKAngoMaCrgqT0mZJJbkgpc4QDJwIOQSgfTcXZDoEs/ARBiCAtZZwPRIrFnJPsS8zwhAEACAhVCmFcKEUCCRYiYl2TSWkHmHcVVEAgUxP0fs2gSK%2BWCv5fy4V8TEnJPFRkrJxinXuIpVSmldKwgMuUEyxELLom/P1SGsVkrHUevtRmkxWaI2uNILQ4gIlOweKAA%3D%3D" rel="nofollow noreferrer">on the Godbolt compiler explorer.

void ext(char *);

int foo(void)
{
    int howmany = 5046;   // could be a function arg
    char buffer[howmany];
    //ext(buffer);

    const char *bufptr = buffer;  // copy the pointer to a C var we can use as a read-write operand
    unsigned char result;
    asm("buf_loop%=:  \n\t"                 // do {
        "   movb     (%[ptr]), %%al \n\t"   // Copy buffer[x] to al
        "   inc     %[ptr]        \n\t"
        "   dec     %[count]      \n\t"
        "   jnz     buf_loop      \n\t"      // } while(ebx>0)
       :   [res]"=a"(result)      // al = write-only output
         , [count] "+r" (howmany) // input/output operand, any register
         , [ptr] "+r" (bufptr)
       : // no input-only operands
       : "memory"   // we read memory that isn't an input operand, only pointed to by inputs
    );
    return result;
}

I used %%al as an example of how to write register names explicitly: Extended Asm (with operands) needs a double % to get a literal % in the asm output.  You could also use %[res] or %0 and let the compiler substitute %al in its asm output.  (And then you'd have no reason to use a specific-register constraint unless you wanted to take advantage of cbw or lodsb or something like that.)  result is unsigned char, so the compiler will pick a byte register for it.  If you want the low byte of a wider operand, you could use %b[count] for example.

This uses a "memory" clobber, which is inefficient.  You don't need the compiler to spill everything to memory, only to make sure that the contents of buffer[] in memory matches the C abstract machine state.  (This is not guaranteed by passing a pointer to it in a register).

gcc7.2 -O3 output:

    pushq   %rbp
    movl    $5046, %edx
    movq    %rsp, %rbp
    subq    $5056, %rsp
    movq    %rsp, %rcx         # compiler-emitted to satisfy our "+r" constraint for bufptr
    # start of the inline-asm block
    buf_loop18:
       movb     (%rcx), %al
       inc     %rcx
       dec     %edx
       jnz     buf_loop
    # end of the inline-asm block

    movzbl  %al, %eax
    leave
    ret

Without a memory clobber or input constraint, leave appears before the inline asm block, releasing that stack memory before the inline asm uses the now-stale pointer.  A signal-handler running at the wrong time would clobber it.

A more efficient way is to use a dummy memory operand which tells the compiler that the entire array is a read-only memory input to the asm statement.  See get string length in inline GNU Assembler for more about this flexible-array-member trick for telling the compiler you read all of an array without specifying the length explicitly.

In C you can define a new type inside a cast, but you can't in C++, hence the using instead of a really complicated input operand.

int bar(unsigned howmany)
{
    //int howmany = 5046;
    char buffer[howmany];
    //ext(buffer);
    buffer[0] = 1;
    buffer[100] = 100;   // test whether we got the input constraints right

    //using input_t = const struct {char a[howmany];};  // requires a constant size
    using flexarray_t = const struct {char a; char x[];};
    const char *dummy;
    unsigned char result;
    asm("buf_loop%=:  \n\t"                 // do {
        "   movb     (%[ptr]), %%al \n\t"   // Copy buffer[x] to al
        "   inc     %[ptr]        \n\t"
        "   dec     %[count]      \n\t"
        "   jnz     buf_loop      \n\t"      // } while(ebx>0)
       : [res]"=a"(result)        // al = write-only output
         , [count] "+r" (howmany) // input/output operand, any register
         , "=r" (dummy)           // output operand in the same register as buffer input, so we can modify the register
       : [ptr] "2" (buffer)     // matching constraint for the dummy output
         , "m" (*(flexarray_t *) buffer)  // whole buffer as an input operand

           //, "m" (*buffer)        // just the first element: doesn't stop the buffer[100]=100 store from sinking past the inline asm, even if you used asm volatile
       : // no clobbers
    );
    buffer[100] = 101;
    return result;
}

I also used a matching constraint so buffer could be an input directly, and the output operand in the same register means we can modify that register.  We got the same effect in foo() by using const char *bufptr = buffer; and then using a read-write constraint to tell the compiler that the new value of that C variable is what we leave in the register.  Either way we leave a value in a dead C variable that goes out of scope without being read, but the matching constraint way can be useful for macros where you don't want to modify the value of your input (and don't need the type of your input: int dummy would work fine, too.)

The buffer[100] = 100; and buffer[100] = 101; assignments are there to show that they both appear in the asm, instead of being merged across the inline-asm (which does happen if you leave out the "m" input operand).  IDK why the buffer[100] = 101; isn't optimized away; it's dead so it should be.  Also note that asm volatile doesn't block this reordering, so it's not an alternative to a "memory" clobber or using the right constraints.


来源: stackexchange

问:
How to remove superfluous characters from returned list result by print statement
I have a small application connected to a DB.
I can insert data with raw_input and then I have select query to return some results as a report.

this is the code snippet:

```<code>if user_input == 'Y':
    cursor.execute(SQLCommand, Values)
    cursor.execute(SQLCommand1)
    result = cursor.fetchall()
    print 'The total costs until now are '
    print result
</code>```

This is the ouput:

```<code>The total costs until now are
[(2061.1, )]
</code>```

I simply need to see only the number, without any special characters. Should I use pprint?

Thanks

答:
Looks like the returned result is a list (the []) containing a single tuple (the ()). So, index into the list and then the tuple to get the value you want:

```<code>print result[0][0]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a small application connected to a DB.
I can insert data with raw_input and then I have select query to return some results as a report.

this is the code snippet:

if user_input == 'Y':
    cursor.execute(SQLCommand, Values)
    cursor.execute(SQLCommand1)
    result = cursor.fetchall()
    print 'The total costs until now are '
    print result

This is the ouput:

The total costs until now are
[(2061.1, )]

I simply need to see only the number, without any special characters. Should I use pprint?

Thanks

Body:
Looks like the returned result is a list (the []) containing a single tuple (the ()). So, index into the list and then the tuple to get the value you want:

print result[0][0]


问:
Save multiple instances of an image downloaded by wget
```<code>#!/bin/bash
trap '.' INT
u = "URL"
if echo $u | egrep -q '^(http://|https://).+(\.jpg|\.jpeg|\.JPG|\.JPEG)$'
then echo "Url checks out"
while :
do
 wget -q $u -O picture$i.jpg
 time=$(date)
 echo "<html><head><title>Spy</title></head><body><h1>spying</h1><p>Picture
 uploaded: $time</p><img src=\"picture$i.jpg\" width=\"300\"></body></html>"
 > spy.html
    for (( i=1; i<=10; i++))
     do
      if [$i = 10]
     then
      rm picture$i.jpg
     else
      mv picture$i picture$(($i+1)).jpg
      mv spy.html spy$(($i+1)).html
     fi
    done
 sleep 60
 done
 else echo "Link not accepted"
 fi
</code>```

What it does is that the url on top is to a camera taking photos every minute. My code downloads that image, saves it and puts it in a html file every 60 seconds.
So what I am trying to do is save the newest image in spy.html and the older ones would iteration through the loop until it reaches 10.
So newst picture in index.html then the second newest in index1.html and so on..
Running this code yields no such file on picture and the html file. This kind of makes sense, but fixing it is a different matter.
Still looking for help on this.

答:
You can do it like that:

```<code>#!/bin/bash
trap '.' INT
u="URL"
counter=0 # Or 1 if you want to start counting from 1
if echo ${u} | egrep -q '^(http://|https://).+(\.jpg|\.jpeg|\.JPG|\.JPEG)$'
 then echo "Url checks out"
 while :
 do
  wget -q ${u} -O picture.jpg
  time=$(date)
  echo "<html><head><title>Spy</title></head><body><h1>spying</h1><p>Picture
  uploaded: ${time}</p><img src=\"picture.jpg\" width=\"300\"></body></html>"
 > index_${counter}.html  # Just makes a file with the counter in it's name
  counter=counter+1 # Count's up
  sleep 60
 done
else
 echo "Link not accepted"
fi
</code>```

I have to say, I didn't check if it works. But I believe the rest of the code is correct, so it should.

Body:
#!/bin/bash
trap '.' INT
u = "URL"
if echo $u | egrep -q '^(http://|https://).+(\.jpg|\.jpeg|\.JPG|\.JPEG)$'
then echo "Url checks out"
while :
do
 wget -q $u -O picture$i.jpg
 time=$(date)
 echo "<title>Spy</title>
spying

Picture
 uploaded: $time
"
 > spy.html
    for (( i=1; i<=10; i++))
     do
      if [$i = 10]
     then
      rm picture$i.jpg
     else
      mv picture$i picture$(($i+1)).jpg
      mv spy.html spy$(($i+1)).html
     fi
    done
 sleep 60
 done
 else echo "Link not accepted"
 fi

What it does is that the url on top is to a camera taking photos every minute. My code downloads that image, saves it and puts it in a html file every 60 seconds.
So what I am trying to do is save the newest image in spy.html and the older ones would iteration through the loop until it reaches 10.
So newst picture in index.html then the second newest in index1.html and so on..
Running this code yields no such file on picture and the html file. This kind of makes sense, but fixing it is a different matter.
Still looking for help on this.

Body:
You can do it like that:

#!/bin/bash
trap '.' INT
u="URL"
counter=0 # Or 1 if you want to start counting from 1
if echo ${u} | egrep -q '^(http://|https://).+(\.jpg|\.jpeg|\.JPG|\.JPEG)$'
 then echo "Url checks out"
 while :
 do
  wget -q ${u} -O picture.jpg
  time=$(date)
  echo "<html><head><title>Spy</title></head><body><h1>spying</h1><p>Picture
  uploaded: ${time}</p><img src=\"picture.jpg\" width=\"300\"></body></html>"
 > index_${counter}.html  # Just makes a file with the counter in it's name
  counter=counter+1 # Count's up
  sleep 60
 done
else
 echo "Link not accepted"
fi

I have to say, I didn't check if it works. But I believe the rest of the code is correct, so it should.

ContentLicense: CC BY-SA 4.0


答:
The [] in the output means that the result is a list. Inside the list, the () means that the single element of the list is a tuple. If you are unfamiliar with lists and tuples, you definitely need to read about them in the official Python tutorial. These are the bread and butter of Python programming.

There are two ways you can get the result you want.

Index by row and column position:

```<code>print result[0][0]
</code>```

Index by row position and column name:

```<code>print result[0]['total']
</code>```

Note

If you know that you will only get a single row from your query, you can also use fetchone() instead of fetchall():

```<code>result = cursor.fetchone()
print result['total']
</code>```

Title: How to remove superfluous characters from returned list result by print statement

Body:
The [] in the output means that the result is a list. Inside the list, the () means that the single element of the list is a tuple. If you are unfamiliar with lists and tuples, you definitely need to read about them in the official Python tutorial. These are the bread and butter of Python programming.

There are two ways you can get the result you want.

Index by row and column position:

print result[0][0]

Index by row position and column name:

print result[0]['total']

Note

If you know that you will only get a single row from your query, you can also use fetchone() instead of fetchall():

result = cursor.fetchone()
print result['total']


问:
Is there a way to distribute windows phone 7 applications without using the windows phone 7 marketplace?
I may need to port a private application from android to windows phone 7.</p>

答: The short answer at the moment is "No". However, if you have a developer account, you can unlock up to 3 phones and deploy your XAP directly to them. Also there are plans to allow companies to deploy apps directly to phones without going via the marketplace, though unfortunately no official dates for this yet.</p>

ContentLicense: CC BY-SA 2.5


问:
.Net API to query folder and files in ADL Store
We are getting feed from EDS as per configured interval. For example : If push is configured for every 8 hrs. for Employee table then folder structure in ADL would look like :

```<code>Employee
  20171116
      Employee_20171116_00:00
      Employee_20171116_08:00
      Employee_20171116_16:00
  20171117
      Employee_20171117_00:00
      Employee_20171117_08:00
      Employee_20171117_16:00
</code>```

And so on….

After initial full push, these files will have delta records (there will be indicator in file to differentiate full pull vs delta mode) I am using watermark approach to pull these delta files incrementally; so I will store date and time stamp for last processed file. During next run, I need to pick files came to store after last run. Hence I need to query all file names in ascending order and looking for appropriate client api available to do so.

Thanks in Advance !!

答:
Depending on your processing requirements, you can use

U-SQL. In that case look at file sets.

.NET SDK for Azure Data Lake Store: https://learn.microsoft.com/en-us/azure/data-lake-store/data-lake-store-data-operations-net-sdk

Body:
We are getting feed from EDS as per configured interval. For example : If push is configured for every 8 hrs. for Employee table then folder structure in ADL would look like :

Employee
  20171116
      Employee_20171116_00:00
      Employee_20171116_08:00
      Employee_20171116_16:00
  20171117
      Employee_20171117_00:00
      Employee_20171117_08:00
      Employee_20171117_16:00

And so on….

After initial full push, these files will have delta records (there will be indicator in file to differentiate full pull vs delta mode) I am using watermark approach to pull these delta files incrementally; so I will store date and time stamp for last processed file. During next run, I need to pick files came to store after last run. Hence I need to query all file names in ascending order and looking for appropriate client api available to do so.

Thanks in Advance !!


问:
Linux rename files before directories
I have the following command that I run to lowercase files/directories, replace . with _ and various other manipulations.  The problem with it is that it seems to try to rename the directories first and then it cannot find the files below it. Is there a way to rename all files in a directory first then the directory itself recursively?  e.g.

directory1

file1

file2

directory1

file1

file2

directory2

file1

directory2

file1

file2

My code is

```<code>while IFS= read -rd '' entry; do
   entry="${entry#./}"         # strip ./
   if [[ -d $entry ]]; then
      rename  'y/A-Z/a-z/; s/ /_/g; s/_-_/-/g; s/sometext//g; s/_extras/-extras/g' "$entry"
   else
      rename  'y/A-Z/a-z/; s/\.(?=.*\.)/_/g; s/ /_/g;  s/_-_/-/g; s/sometext//g; s/_extras/-extras/g' "$entry"
   fi
done < <(find . -iname '*' -print0)
</code>```

答:
Have you looked at this answer?
 Your scenario is more complicated but it looks like they were dealing with the same difficulty in terms of recursion.</p>

Title: Linux rename files before directories

Body:
I have the following command that I run to lowercase files/directories, replace . with _ and various other manipulations.  The problem with it is that it seems to try to rename the directories first and then it cannot find the files below it. Is there a way to rename all files in a directory first then the directory itself recursively?  e.g.

directory1

file1

file2

directory1

file1

file2

directory2

file1

directory2

file1

file2

My code is

while IFS= read -rd '' entry; do
   entry="${entry#./}"         # strip ./
   if [[ -d $entry ]]; then
      rename  'y/A-Z/a-z/; s/ /_/g; s/_-_/-/g; s/sometext//g; s/_extras/-extras/g' "$entry"
   else
      rename  'y/A-Z/a-z/; s/\.(?=.*\.)/_/g; s/ /_/g;  s/_-_/-/g; s/sometext//g; s/_extras/-extras/g' "$entry"
   fi
done < <(find . -iname '*' -print0)


问:
Get SubKeys of Json in JavaScript
I have this code, but it doesn't prints subkeys....

```<code>    for (var key in result) {
        if (!result.hasOwnProperty(key)) continue;
        var obj = result[key];
        for (var prop in obj) {
            if (!obj.hasOwnProperty(prop)) continue;
            alert(prop + " = " + obj[prop]);
        }
    }
</code>```

When is an object print: someKey[Object object]

my result (example):

[ { "branch_id": 992, "sale_id": 24422, "identifier": "", "emitter": { "id": 68, "tax_id": "", "address": { "street": "Carretera a buenavista km 21", "country_code": "MEX", } } } ]

答:
It's better if you handle your function as recursive function instead nested for in statements, so you only need to verify if your value if an object to recall the function again, so in code you have this:

var json = {
 "key1": "value1",
 "key2": "value2",
 "key3": {
   "sub_1_key1": "subvalue1",
    "sub_1_key2": "subvalue2",
    "sub_1_key3": "subvalue3",
    "sub_1_key4": {
     "sub_2_key1": "sub_2_value1"
    }
  },
};

var logger = document.getElementById('logs');

function goThroughJSON(json) {
 for (var attr in json) {
   var value = json[attr];
   if (typeof value === 'object' && !(attr instanceof Array)) {
     return goThroughJSON(value);
    }
    logger.innerHTML += attr + '
'
  }
}

goThroughJSON(json);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="logs"></div></code>```

I really hope you find it helful.

Title: Get SubKeys of Json in JavaScript

Body:
I have this code, but it doesn't prints subkeys....

    for (var key in result) {
        if (!result.hasOwnProperty(key)) continue;
        var obj = result[key];
        for (var prop in obj) {
            if (!obj.hasOwnProperty(prop)) continue;
            alert(prop + " = " + obj[prop]);
        }
    }

When is an object print: someKey[Object object]

my result (example):

[ { "branch_id": 992, "sale_id": 24422, "identifier": "", "emitter": { "id": 68, "tax_id": "", "address": { "street": "Carretera a buenavista km 21", "country_code": "MEX", } } } ]

Body:
It's better if you handle your function as recursive function instead nested for in statements, so you only need to verify if your value if an object to recall the function again, so in code you have this:

var json = {
 "key1": "value1",
 "key2": "value2",
 "key3": {
   "sub_1_key1": "subvalue1",
    "sub_1_key2": "subvalue2",
    "sub_1_key3": "subvalue3",
    "sub_1_key4": {
     "sub_2_key1": "sub_2_value1"
    }
  },
};

var logger = document.getElementById('logs');

function goThroughJSON(json) {
 for (var attr in json) {
   var value = json[attr];
   if (typeof value === 'object' && !(attr instanceof Array)) {
     return goThroughJSON(value);
    }
    logger.innerHTML += attr + '<br>'
  }
}

goThroughJSON(json);

<div id="logs"></div>

I really hope you find it helful.


问:
Possible to use string formatting to split a string value?
EDIT:
I'm stuck with python 2.7.5 ...

ANOTHER EDIT:
Clarifying the need for the changes to be in the template, not the code handling the dictionary.

I'm using a string formatter for building paths from templates.

I know I can do this:

```<code>currentUser = {'first': "Monty", 'last': "Python"}
template = '/usr/{user[last]}/{user[first]}' # will come from a config file
template.format(user=currentUser)
# Result: '/usr/Python/Monty'
</code>```

but in the case of

```<code>currentUser = {'first': "Raymond", 'last': "Luxury-Yacht"}
</code>```

Is there a way to split, say, by - and use an index?

```<code># something like:
template = '/usr/{user[last].split(-)[0]/{user[first]}' # will come from a config file
template.format(user=currentUser)
# Result: '/usr/Luxury/Raymond'
</code>```

The decision to choose:

which key to split

by what character

which index to use from split

MUST come from the template string; if the current mini-language can't achieve this, I will have to write a custom formatter.

DISCLAIMER: The example is a bit contrived, and not practical, I know.  I'm actually dealing with a database where two key bits of information are stored in a single field, joined by underscores -_-.  I understand that I could do post-processing on the data after extracting it from the database, but due to conventions for this field differing per-project, I can't even assume that a split operation is valid (some values on some projects won't have the underscore issue).  Rather than code a solution around each convention, I'm hoping to be able to provide users with a template "language" so each project can themselves determine how to extract that data, adapt to whatever naming convention they choose, and configure their templates accordingly.

TL/DR: I'm not looking for a solution to fixing my incoming data -- I'm exploring the possibility of splitting strings using Python's string format mini-language.

答:
If you're open to Python 3.6, you can use f-strings:

```<code>users = [{'first': "Raymond", 'last': "Luxury-Yacht"},
         {'first': "Monty", 'last': "Python"}]

sep = '-'
for user in users:
    path = f"/usr/{user['last'].split(sep)[0]}/{user['first'].split(sep)[0]}"
    print(path)
</code>```

/usr/Luxury/Raymond
/usr/Python/Monty
```

<hr>

<p>However, if you want to stick to your dict style formatting in Python 2, you can use the current template with a small wrapper class that does the clean up of the dictionary values:</p>

```class Wrapper(object):
    __slots__ = ('sep', 'dct')

    def __init__(self, dct, sep='-'):
        self.sep = sep
        self.dct = dct

    def __getitem__(self, key):
        return self.dct[key].split(self.sep)[0]

template = '/usr/{user[last]}/{user[first]}'
for usr in map(Wrapper, users):
    path = template.format(user=usr)
    print(path)
```

<hr>

<pre class="lang-none prettyprint-override"><code>/usr/Luxury/Raymond
/usr/Python/Monty
</code>```

Body:
EDIT:
I'm stuck with python 2.7.5 ...

ANOTHER EDIT:
Clarifying the need for the changes to be in the template, not the code handling the dictionary.

I'm using a string formatter for building paths from templates.

I know I can do this:

currentUser = {'first': "Monty", 'last': "Python"}
template = '/usr/{user[last]}/{user[first]}' # will come from a config file
template.format(user=currentUser)
# Result: '/usr/Python/Monty'

but in the case of

currentUser = {'first': "Raymond", 'last': "Luxury-Yacht"}

Is there a way to split, say, by - and use an index?

# something like:
template = '/usr/{user[last].split(-)[0]/{user[first]}' # will come from a config file
template.format(user=currentUser)
# Result: '/usr/Luxury/Raymond'

The decision to choose:

which key to split

by what character

which index to use from split

MUST come from the template string; if the current mini-language can't achieve this, I will have to write a custom formatter.

DISCLAIMER: The example is a bit contrived, and not practical, I know.  I'm actually dealing with a database where two key bits of information are stored in a single field, joined by underscores -_-.  I understand that I could do post-processing on the data after extracting it from the database, but due to conventions for this field differing per-project, I can't even assume that a split operation is valid (some values on some projects won't have the underscore issue).  Rather than code a solution around each convention, I'm hoping to be able to provide users with a template "language" so each project can themselves determine how to extract that data, adapt to whatever naming convention they choose, and configure their templates accordingly.

TL/DR: I'm not looking for a solution to fixing my incoming data -- I'm exploring the possibility of splitting strings using Python's string format mini-language.

Body:
If you're open to Python 3.6, you can use f-strings:

users = [{'first': "Raymond", 'last': "Luxury-Yacht"},
         {'first': "Monty", 'last': "Python"}]

sep = '-'
for user in users:
    path = f"/usr/{user['last'].split(sep)[0]}/{user['first'].split(sep)[0]}"
    print(path)

/usr/Luxury/Raymond
/usr/Python/Monty

However, if you want to stick to your dict style formatting in Python 2, you can use the current template with a small wrapper class that does the clean up of the dictionary values:

class Wrapper(object):
    __slots__ = ('sep', 'dct')

    def __init__(self, dct, sep='-'):
        self.sep = sep
        self.dct = dct

    def __getitem__(self, key):
        return self.dct[key].split(self.sep)[0]

template = '/usr/{user[last]}/{user[first]}'
for usr in map(Wrapper, users):
    path = template.format(user=usr)
    print(path)

/usr/Luxury/Raymond
/usr/Python/Monty


问:
Sort array of custom objects alphabetically as per search string rest object should come at last
Everyone I have a array of following File object

```<code>File{
var displayName: String? // eg detail.txt, abc.doc
var size: Int?
..
}
</code>```

say, I have a array of this file object

```<code>let arrayOfFile = [f1,f2,f3,f4.....f1000];
</code>```

These file objects are getting display in a UITableView over a screen. There are a search option, where user can search files...
Now the problem is, when user type something into UISearchBar I need to sort arrayOfFile array in such a way that the File object which contains search string (within name) comes first (all in alphabetic sorted order) and other files which doesn't contains search string within name come at the end.

this is what I have tried so far...

```<code>self.dataArray =  self.searchDataSource.sorted(by: { ( f1, f2) -> Bool in
    if f1.displayName.lowercased().strContains(text) && f2.displayName.lowercased().strContains(text){
                            if f1.displayName.localizedCaseInsensitiveCompare(f2.displayName) == ComparisonResult.orderedAscending{
                                return true;
                            }
                            else if f1.displayName.localizedCaseInsensitiveCompare(f2.displayName) == ComparisonResult.orderedSame{
                                return true;
                            }
                            else if f1.displayName.localizedCaseInsensitiveCompare(f2.displayName) == ComparisonResult.orderedDescending{
                                return false;
                            }
                            else{
                                return false;
                            }
                        }
                        else if f1.displayName.lowercased().strContains(text){
                            return  true
                        }else if f2.displayName.lowercased().strContains(text){
                            return true
                        }
                        else{
                            return false
                        }
                       })
</code>```

答:
Best way to do this would be to make your ‘File’ class conform to ‘comparable’.
Then call sort method on the File array.</p>

Body:
Everyone I have a array of following File object

File{
var displayName: String? // eg detail.txt, abc.doc
var size: Int?
..
}

say, I have a array of this file object

let arrayOfFile = [f1,f2,f3,f4.....f1000];

These file objects are getting display in a UITableView over a screen. There are a search option, where user can search files...
Now the problem is, when user type something into UISearchBar I need to sort arrayOfFile array in such a way that the File object which contains search string (within name) comes first (all in alphabetic sorted order) and other files which doesn't contains search string within name come at the end.

this is what I have tried so far...

self.dataArray =  self.searchDataSource.sorted(by: { ( f1, f2) -> Bool in
    if f1.displayName.lowercased().strContains(text) && f2.displayName.lowercased().strContains(text){
                            if f1.displayName.localizedCaseInsensitiveCompare(f2.displayName) == ComparisonResult.orderedAscending{
                                return true;
                            }
                            else if f1.displayName.localizedCaseInsensitiveCompare(f2.displayName) == ComparisonResult.orderedSame{
                                return true;
                            }
                            else if f1.displayName.localizedCaseInsensitiveCompare(f2.displayName) == ComparisonResult.orderedDescending{
                                return false;
                            }
                            else{
                                return false;
                            }
                        }
                        else if f1.displayName.lowercased().strContains(text){
                            return  true
                        }else if f2.displayName.lowercased().strContains(text){
                            return true
                        }
                        else{
                            return false
                        }
                       })


问:
bootstrap not following column width
SO i m trying to add input forms with different column width ..
Below is my code:

`<

```<code>div class="row">
 <div class="col-md-10">
   <div class="form-group form-inline col-md-6 col-lg-4">
      <input type="text" name="cw" id="inputammino" value="A">
   </div>
   <div class="form-group form-inline col-md-4 col-lg-4">
     <input type="text" name="cw2" id="inputcusti" value="42.010565">
   </div>
   <div class="form-group form-inline col-md-2 col-lg-4">
     <input type="text" name="cw3" id="amiaci" value="K">
   </div>
 </div>
 </div>
</code>```

`

<img src="https://i.stack.imgur.com/hznbB.png" alt="bootstrap form">

But instead of adding more column width to first column its adding it to last..What am I doing wrong?

答:
I am using Bootstrap 3.3.7 and I have formatted your HTML as below by using BootStrap 3.3 Documentation and its working fine for me.</p>

```<code><div class="form-inline">
   <div class="form-group">
     <div class="col-md-6">
        <input type="text" name="cw" id="inputammino" value="A">
     </div>
     <div class="col-md-4">
       <input type="text" name="cw2" id="inputcusti" value="42.010565">
     </div>
     <div class="col-md-2">
       <input type="text" name="cw3" id="amiaci" value="K">
     </div>
   </div>
</div>
</code>```

Title: bootstrap not following column width

Body:
SO i m trying to add input forms with different column width ..
Below is my code:

`<

div class="row">

      <input type="text" name="cw" id="inputammino" value="A">

     <input type="text" name="cw2" id="inputcusti" value="42.010565">

     <input type="text" name="cw3" id="amiaci" value="K">

`

<img src="https://i.stack.imgur.com/hznbB.png" alt="bootstrap form">

But instead of adding more column width to first column its adding it to last..What am I doing wrong?

Body:
I am using Bootstrap 3.3.7 and I have formatted your HTML as below by using BootStrap 3.3 Documentation and its working fine for me.

<div class="form-inline">
   <div class="form-group">
     <div class="col-md-6">
        <input type="text" name="cw" id="inputammino" value="A">
     </div>
     <div class="col-md-4">
       <input type="text" name="cw2" id="inputcusti" value="42.010565">
     </div>
     <div class="col-md-2">
       <input type="text" name="cw3" id="amiaci" value="K">
     </div>
   </div>
</div>


问:
Server closes connection before exec function in my php script finish executing
I have a PHP script that I have to execute from a browser. Inside that script, I use exec() function like this:

```<code>exec("sudo scriptname 2>&1", $out);
</code>```

I want $out to hold the output returned by that script. I need the output for further processing. The script takes about 2 minutes to run. The problem is that when I run the PHP script in the browser, it keeps on running for a minute and then stops. Due to this, the PHP script dies and I get an error similar to 'Page not Responding'.

On chrome, the screen displays an error like this:

```<code>ServerName.com unexpectedly closed the connection
ERR_INCOMPLETE_CHUNKED_ENCODING
</code>```

On Mozilla, the screen goes blank (completely white).

After searching the chrome error, I do believe that the web server (I am running Apache) closes the connection due to inactivity from the client as the PHP script isn't really doing anything but waiting for the exec() function to finish.

I tried setting max_execution_time, max_input_time, default_socket_timeout and used set_time_limit(0) hoping that this might not kill the PHP script, but it didn't work.

I do not want to use PTHREADS to generate two threads where one runs the exec() function and the other monitors it or somehow keeps the server busy.

I believe there is some setting within PHP or apache that is set to 60 seconds, which kills the connection from the server. I just don't know what it is.

Also, the PHP script runs perfectly when I replace the script within exec() with another one that takes less than a minute.

EDIT: The Apache Timeout value is set to 120 seconds.

答: Any chance sudo is waiting for username/password input and is timing out after 1 min?</p>

Body:
I have a PHP script that I have to execute from a browser. Inside that script, I use exec() function like this:

exec("sudo scriptname 2>&1", $out);

I want $out to hold the output returned by that script. I need the output for further processing. The script takes about 2 minutes to run. The problem is that when I run the PHP script in the browser, it keeps on running for a minute and then stops. Due to this, the PHP script dies and I get an error similar to 'Page not Responding'.

On chrome, the screen displays an error like this:

ServerName.com unexpectedly closed the connection
ERR_INCOMPLETE_CHUNKED_ENCODING

On Mozilla, the screen goes blank (completely white).

After searching the chrome error, I do believe that the web server (I am running Apache) closes the connection due to inactivity from the client as the PHP script isn't really doing anything but waiting for the exec() function to finish.

I tried setting max_execution_time, max_input_time, default_socket_timeout and used set_time_limit(0) hoping that this might not kill the PHP script, but it didn't work.

I do not want to use PTHREADS to generate two threads where one runs the exec() function and the other monitors it or somehow keeps the server busy.

I believe there is some setting within PHP or apache that is set to 60 seconds, which kills the connection from the server. I just don't know what it is.

Also, the PHP script runs perfectly when I replace the script within exec() with another one that takes less than a minute.

EDIT: The Apache Timeout value is set to 120 seconds.


问:
password authentication failed with sequelize v4 replication
I am attempting to connect to my database(s) via replication. I have filled out the fields in the replication option in a variety of ways only to get the same error each time:

password authentication failed for user "my_local_system_username"

where somehow sequelize/pg thinks that I am trying to log in with my operating system user name???

Here is what I tried:

```<code>const serverParams = {
    user: auth.db.user,
    password: auth.db.password,
    port: 5432
};

const dbConfig = {
    options: {
        dialect: 'postgres',
        protocol: 'tcp',
        replication: {
            write: {},
            read: process.env.NODE_ENV === 'production' ?
                [
                    {
                        ...serverParams,
                        host: 'db1.lupoex.com'
                    },
                    {
                        ...serverParams,
                        host: 'db2.lupoex.com'
                    }
                ] :
                [
                    {
                        ...serverParams,
                        host: 'test.db.lupoex.com'
                    }
                ]
        },
        pool: {
            max: 5,
            min: 0,
            idle: 5000,
            acquire: 20000
        }
        //logging: function(query) {
        //    console.log(query)
        //}
    }
};

new Sequelize('database', null, null, dbConfig.options);
</code>```

Thanks in advance, all comments/suggestions welcome.

答:
I figured this out. It seems the config needs a username like so:

```<code>const serverParams = {
    user: auth.db.user,
    username: auth.db.user,
    password: auth.db.password,
    port: 5432
};
</code>```

Body:
I am attempting to connect to my database(s) via replication. I have filled out the fields in the replication option in a variety of ways only to get the same error each time:

password authentication failed for user "my_local_system_username"

where somehow sequelize/pg thinks that I am trying to log in with my operating system user name???

Here is what I tried:

const serverParams = {
    user: auth.db.user,
    password: auth.db.password,
    port: 5432
};

const dbConfig = {
    options: {
        dialect: 'postgres',
        protocol: 'tcp',
        replication: {
            write: {},
            read: process.env.NODE_ENV === 'production' ?
                [
                    {
                        ...serverParams,
                        host: 'db1.lupoex.com'
                    },
                    {
                        ...serverParams,
                        host: 'db2.lupoex.com'
                    }
                ] :
                [
                    {
                        ...serverParams,
                        host: 'test.db.lupoex.com'
                    }
                ]
        },
        pool: {
            max: 5,
            min: 0,
            idle: 5000,
            acquire: 20000
        }
        //logging: function(query) {
        //    console.log(query)
        //}
    }
};

new Sequelize('database', null, null, dbConfig.options);

Thanks in advance, all comments/suggestions welcome.

Body:
I figured this out. It seems the config needs a username like so:

const serverParams = {
    user: auth.db.user,
    username: auth.db.user,
    password: auth.db.password,
    port: 5432
};


问:
Yocto build not including files in sdcard image
I am trying to build an SDK into my sysroot on my yocto build. However when i compile my build i get no errors and everything appears to have worked fine.

When i flash my SD  card and run it on my board and go to look for my files, they arent there.

here is my .bb file which is used to install the SDK i want to use.

```<code>giffgaff-connectDESCRIPTION = "azure"
HOMEPAGE = "https://github.com/Azure/azure-iot-sdk-c"
LICENSE = "MIT"
SECTION = "applications"
PRIORITY = "optional"
DEPENDS = "mono"
LIC_FILES_CHKSUM = "file://${WORKDIR}/git/LICENSE;md5=4283671594edec4c13aeb073c219237a"

SRCREV = "${AUTOREV}"
SRC_URI = "git://git@bitbucket.org/condecosoftware/azure-iot-sdk-c;protocol=ssh;branch=master"

COMPATIBLE_MACHINE = "imx6qsabresd"

S = "${WORKDIR}"

ALLOW_EMPTY_${PN} = "1"

do_compile() {
  echo libdir: ${libdir}
  echo Files : FILES_${PN}
  echo "compiler: ${CC}"
  echo "sysroot: ${STAGING_DIR_TARGET}"
  export SYSROOT=${STAGING_DIR_TARGET}
  cd ${WORKDIR}/git/build_all/linux/
  ./build.sh --toolchain-file toolchain-yocto.cmake -cl --sysroot=${STAGING_DIR_TARGET} --install-path-prefix ${STAGING_DIR_TARGET}
  cd ../..
  cmake -P cmake/iotsdk_linux/cmake_install.cmake
}

do_install() {
    cd git
    pwd
    echo ${D}
    echo ${libdir}
    install -d 0755  ${D}${libdir}

    install -m 0755 ./cmake/iotsdk_linux/umqtt/libumqtt.a ${D}${libdir}/
    install -m 0755 ./cmake/iotsdk_linux/uamqp/libuamqp.a ${D}${libdir}/
    install -m 0755 ./cmake/iotsdk_linux/c-utility/libaziotsharedutil.a ${D}${libdir}/
    install -m 0755 ./cmake/iotsdk_linux/iothub_client/libiothub_client_http_transport.a ${D}${libdir}/
    install -m 0755 ./cmake/iotsdk_linux/iothub_client/libiothub_client.a ${D}${libdir}/
    install -m 0755 ./cmake/iotsdk_linux/iothub_client/libiothub_client_amqp_ws_transport.a ${D}${libdir}/
    install -m 0755 ./cmake/iotsdk_linux/iothub_client/libiothub_client_amqp_transport.a ${D}${libdir}/
    install -m 0755 ./cmake/iotsdk_linux/iothub_client/libiothub_client_mqtt_transport.a ${D}${libdir}/
    install -m 0755 ./cmake/iotsdk_linux/iothub_client/libiothub_client_mqtt_ws_transport.a ${D}${libdir}/
    install -m 0755 ./cmake/iotsdk_linux/serializer/libserializer.a ${D}${libdir}/
    install -m 0755 ./cmake/iotsdk_linux/iothub_service_client/libiothub_service_client.a ${D}${libdir}/
}

do_fetch_extra(){
    cd ${WORKDIR}/git/
    git submodule update --init --recursive
}

addtask fetch_extra after do_unpack before do_patch
</code>```

Any help would be great appreciated. Thanks

答:
You will probably need to add

```<code>PACKAGES =+ "${PN}-staticdev"
FILES_${PN}-staticdev += "${libdir}/*.a"
</code>```

to ship every files you installed into your image.
You can also add every files one by one instead of wildcard.

Some remarks:

For git submodules, you can use gitsm:// url, it will initialize every submodules.

You can also put the following instruction to avoid doing some change dir in recipe.

```<code>S = "${WORKDIR}/git"
</code>```

By the way, you can look this OE recipe for Azure from Intel meta-iot-cloud layer. It is python recipe, but it depends on C iot sdk, it can be inspiring:

https://github.com/intel-iot-devkit/meta-iot-cloud/blob/master/recipes-azure/azure-iot-sdk/azure-iot-sdk_1.1.23.bb

Body:
I am trying to build an SDK into my sysroot on my yocto build. However when i compile my build i get no errors and everything appears to have worked fine.

When i flash my SD  card and run it on my board and go to look for my files, they arent there.

here is my .bb file which is used to install the SDK i want to use.

giffgaff-connectDESCRIPTION = "azure"
HOMEPAGE = "https://github.com/Azure/azure-iot-sdk-c"
LICENSE = "MIT"
SECTION = "applications"
PRIORITY = "optional"
DEPENDS = "mono"
LIC_FILES_CHKSUM = "file://${WORKDIR}/git/LICENSE;md5=4283671594edec4c13aeb073c219237a"

SRCREV = "${AUTOREV}"
SRC_URI = "git://git@bitbucket.org/condecosoftware/azure-iot-sdk-c;protocol=ssh;branch=master"

COMPATIBLE_MACHINE = "imx6qsabresd"

S = "${WORKDIR}"

ALLOW_EMPTY_${PN} = "1"

do_compile() {
  echo libdir: ${libdir}
  echo Files : FILES_${PN}
  echo "compiler: ${CC}"
  echo "sysroot: ${STAGING_DIR_TARGET}"
  export SYSROOT=${STAGING_DIR_TARGET}
  cd ${WORKDIR}/git/build_all/linux/
  ./build.sh --toolchain-file toolchain-yocto.cmake -cl --sysroot=${STAGING_DIR_TARGET} --install-path-prefix ${STAGING_DIR_TARGET}
  cd ../..
  cmake -P cmake/iotsdk_linux/cmake_install.cmake
}

do_install() {
    cd git
    pwd
    echo ${D}
    echo ${libdir}
    install -d 0755  ${D}${libdir}

    install -m 0755 ./cmake/iotsdk_linux/umqtt/libumqtt.a ${D}${libdir}/
    install -m 0755 ./cmake/iotsdk_linux/uamqp/libuamqp.a ${D}${libdir}/
    install -m 0755 ./cmake/iotsdk_linux/c-utility/libaziotsharedutil.a ${D}${libdir}/
    install -m 0755 ./cmake/iotsdk_linux/iothub_client/libiothub_client_http_transport.a ${D}${libdir}/
    install -m 0755 ./cmake/iotsdk_linux/iothub_client/libiothub_client.a ${D}${libdir}/
    install -m 0755 ./cmake/iotsdk_linux/iothub_client/libiothub_client_amqp_ws_transport.a ${D}${libdir}/
    install -m 0755 ./cmake/iotsdk_linux/iothub_client/libiothub_client_amqp_transport.a ${D}${libdir}/
    install -m 0755 ./cmake/iotsdk_linux/iothub_client/libiothub_client_mqtt_transport.a ${D}${libdir}/
    install -m 0755 ./cmake/iotsdk_linux/iothub_client/libiothub_client_mqtt_ws_transport.a ${D}${libdir}/
    install -m 0755 ./cmake/iotsdk_linux/serializer/libserializer.a ${D}${libdir}/
    install -m 0755 ./cmake/iotsdk_linux/iothub_service_client/libiothub_service_client.a ${D}${libdir}/
}

do_fetch_extra(){
    cd ${WORKDIR}/git/
    git submodule update --init --recursive
}

addtask fetch_extra after do_unpack before do_patch

Any help would be great appreciated. Thanks

Body:
You will probably need to add

PACKAGES =+ "${PN}-staticdev"
FILES_${PN}-staticdev += "${libdir}/*.a"

to ship every files you installed into your image.
You can also add every files one by one instead of wildcard.

Some remarks:

For git submodules, you can use gitsm:// url, it will initialize every submodules.

You can also put the following instruction to avoid doing some change dir in recipe.

S = "${WORKDIR}/git"

By the way, you can look this OE recipe for Azure from Intel meta-iot-cloud layer. It is python recipe, but it depends on C iot sdk, it can be inspiring:

https://github.com/intel-iot-devkit/meta-iot-cloud/blob/master/recipes-azure/azure-iot-sdk/azure-iot-sdk_1.1.23.bb


问:
Omniauth-ldap invalid credentials
I'm having a heck of a time getting omniauth-ldap to work properly with our AD server, and I believe it is because our usernames have our Domain Names in them.

This will successfully connect to our ldap server:

```<code>ldapsearch -h ldap.ourdomain.com -b "dc=ourdomain,dc=int" -D "OURDOMAIN\username" -w <password> '(sAMAccountName=username)'
</code>```

But, these settings in OmniAuth only result in "invalid credentials"

```<code>Padrino.use OmniAuth::Strategies::LDAP,
    :host => "ldap.ourdomain.com",
    :base => "dc=OURDOMAIN,dc=INT",
    :uid => "sAMAccountName",
    :bind_dn => 'OURDOMAIN\%{username}',
    # This is hard coded for now, but I need it to be the value entered by the user
    :password => "mypassword"
</code>```

UPDATE

Working on this further, I have discovered that omniauth-ldap sets the bind method to :anonymous if the :bind_dn and :password are not set.

However, it does not insert the username and does not provide the user-entered password if the values are set.

What I need is

```<code>:bind_dn => 'OURDOMAIN\<user entered username>',
:password => <user entered password>
</code>```

but the password and entered username are only provided to the connection if you hard code them.

答: I had to solve this by creating a service account. That account logs in then queries for the existence and validity of the user that's actually trying to log in. The service account credentials can be set in your Omniauth configuration, and then you can utilize omniauth-ldap as you would any other omniauth methodology.</p>

Title: Omniauth-ldap invalid credentials

Body:
I'm having a heck of a time getting omniauth-ldap to work properly with our AD server, and I believe it is because our usernames have our Domain Names in them.

This will successfully connect to our ldap server:

ldapsearch -h ldap.ourdomain.com -b "dc=ourdomain,dc=int" -D "OURDOMAIN\username" -w <password> '(sAMAccountName=username)'

But, these settings in OmniAuth only result in "invalid credentials"

Padrino.use OmniAuth::Strategies::LDAP,
    :host => "ldap.ourdomain.com",
    :base => "dc=OURDOMAIN,dc=INT",
    :uid => "sAMAccountName",
    :bind_dn => 'OURDOMAIN\%{username}',
    # This is hard coded for now, but I need it to be the value entered by the user
    :password => "mypassword"

UPDATE

Working on this further, I have discovered that omniauth-ldap sets the bind method to :anonymous if the :bind_dn and :password are not set.

However, it does not insert the username and does not provide the user-entered password if the values are set.

What I need is

:bind_dn => 'OURDOMAIN\<user entered username>',
:password => <user entered password>

but the password and entered username are only provided to the connection if you hard code them.


问:
How to plot the output (bias and weight) of a simple 1 layer model?
I have a very simple model that is the data input to a hidden layer with 2 units that then outputs to an activation layer and then to the softmax layer.

mxnet will report the computed bias and weight with something like

```<code>fullyconnected0_bias -> [ 1.8431 -1.84309]
fullyconnected0_weight ->
[
 [-1.22873 -1.22873]
 [ 1.22872  1.22872]
]
</code>```

given the geometric intuition that this represents a separating hyperplane, how would one go about plotting this? For some reason I can't find any examples of anyone doing this in my searching? What do the weights and bias represent in terms of plot-able inputs?

答: One thing you may want to check out is the tensorboard-lite project which works with MXNet, with which you can easily visualize the network weights/outputs.  https://github.com/dmlc/tensorboard

Body:
I have a very simple model that is the data input to a hidden layer with 2 units that then outputs to an activation layer and then to the softmax layer.

mxnet will report the computed bias and weight with something like

fullyconnected0_bias -> [ 1.8431 -1.84309]
fullyconnected0_weight ->
[
 [-1.22873 -1.22873]
 [ 1.22872  1.22872]
]

given the geometric intuition that this represents a separating hyperplane, how would one go about plotting this? For some reason I can't find any examples of anyone doing this in my searching? What do the weights and bias represent in terms of plot-able inputs?


问:
If `ModelState.IsValid==false`, we should return `View()` or `View(movie)`?
If ModelState.IsValid==false, we should return View() or View(movie)?

```<code>    public ActionResult Create()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Create(Movie movie)
    {
        if (ModelState.IsValid)
        {
            context.Movies.Add(movie);
            context.SaveChanges();
            return RedirectToAction("Index");
        }
        else
        {
            return View();
        }
    }
</code>```

or

```<code>    public ActionResult Create()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Create(Movie movie)
    {
        if (ModelState.IsValid)
        {
            context.Movies.Add(movie);
            context.SaveChanges();
            return RedirectToAction("Index");
        }
        else
        {
            return View(movie);
        }
    }
</code>```

?

答:
What I like to do is:

```<code>[HttpPost]
public ActionResult Create(Movie movie)
{
   this.ViewData.Model = movie;
...
</code>```

That way I can return View() without worrying about passing the model as argument. There can be more than one situation where you may want to return the view, e.g. try/catch around SaveChanges(). This also gives you the chance to handle errors on the OnException method and return a view without losing the model.

Body:
If ModelState.IsValid==false, we should return View() or View(movie)?

    public ActionResult Create()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Create(Movie movie)
    {
        if (ModelState.IsValid)
        {
            context.Movies.Add(movie);
            context.SaveChanges();
            return RedirectToAction("Index");
        }
        else
        {
            return View();
        }
    }

or

    public ActionResult Create()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Create(Movie movie)
    {
        if (ModelState.IsValid)
        {
            context.Movies.Add(movie);
            context.SaveChanges();
            return RedirectToAction("Index");
        }
        else
        {
            return View(movie);
        }
    }

?

Body:
What I like to do is:

[HttpPost]
public ActionResult Create(Movie movie)
{
   this.ViewData.Model = movie;
...

That way I can return View() without worrying about passing the model as argument. There can be more than one situation where you may want to return the view, e.g. try/catch around SaveChanges(). This also gives you the chance to handle errors on the OnException method and return a view without losing the model.


问:
See when my skill reprompts users
Is there a way to see if my skill has reprompted a user? I know this happens if a user doesn't respond within an allotted amount of time and it would be informative because I'd like to rephrase some of my responses if this tends to happen more frequently for some utterances than others.</p>

答: No. At this point, this isn't possible. You might be able to use a timer in your skill service to guesstimate however. </p>

Title: See when my skill reprompts users


问:
What's the smallest subset of language features you need to bootstrap it's compiler?
What would be the absolute necessary core features of a language (inspired from C) as a sub-language which can be used to write a compiler for the whole language?</p>

答:
There are two ways to interpret your question: as a theoretical computer science question; and, as a practical engineering question.

There's already an answer that leans toward the theoretical answer.  So, I'm going to go more to the practical side.

I think you'll need integers, pointers, variables, an if statement, a loop statement, and functions.  As the other post points out, you'll need to have some way of reading from a file to get the source code to compile and writing to a file to save the generated assembly or object code.

I'd suggest you look into the Small C compiler.  It's a compiler for a subset of C that is able to compile itself.  If you look at the Wikipedia page for Small C, you'll see some books have been published about the compiler.  While the books are out of print, you may be able to find one available second hand.


问:
Can problems happen when multiple Python processes create a .pyc file?
Suppose I have a large number of Python processes launching at the same time from a common directory.

If a Python source file has been recently modified the interpreter will compile a .pyc file.

If there are multiple processes simultaneously trying to build a .pyc for the same Python source file, can this create a race condition or other issues?

Will Python (or cpython specifically) guarantee concurrency protection when compiling?

I'm aware of methods that could be used to avoid this, I'm only interested in understanding if this use case can be problematic.

答:
Generally no, when CPython write bytecode cache file, it first write to a temporary file, then move to the desired location with os.replace. os.replace uses rename(2) system call underlying, rename() is atomic if the OS/filesystem does not crash in the middle. As a result bytecode file write is atomic.

IMHO what you should worry about is bytecode cache file stale checking. Python check cache file freshness with source file stat.mtime (and file size). The caveat is, resolution of mtime being used by python is one second, thus if one process modified source file while another process is writing cache file in the same second, left the bytecode cache file inconsistent with source and will not get refreshed later. Good news is pep-0552 get accepted, changed to hashed based cache file, which will take care of this case.


问:
Can Mercurial (Hg) show me what remote a branch or a commit is from?
I have a Mercurial (Hg) repository with 2 remotes, let's call them default and upstream.

I have pulled from both remotes and would like to know which commits/branches came from the remote called default and which commits/branches came from the remote called upstream. How do I achieve this in Hg?

Ideally I would like to use the hg log command much like I use the git log --describe --all command which I'm more familiar with.

Is there a template for the hg log command that is equivalent to git log --describe?

Note: I'm already aware of using hg out <remote> to show me what set of commits is not available on the remote I'm interested in, but I was hoping for something a little more visual.

答:
I have pulled from both remotes and would like to know which commits/branches came from the remote called default and which commits/branches came from the remote called upstream. How do I achieve this in Hg?

In general, you can't.  (But see below, and Lazy Badger's suggested extension.)

Git doesn't actually do this either.  Nonetheless, you can, as you said:

... use the git log --describe --all command ...

This does not tell you who delivered the commits to you.  Instead, it tells you which of your references is "closest" to the to-be-described commit ("closest" being defined in a vague handwave-y manner).  What Git does, that Mercurial doesn't, is to create, in your repository, specific references—remote-tracking names like remote1/branch and remote2/branch—that remember which commit was identified by the name branch on remote1 and remote2 respectively.

Provided that precisely one of the two remotes has those commits in the first place, only one such reference can be "closest".  Git will choose that one, and from that, you can infer who has the commits and who does not.  It fails, or can fail, if both remotes have the commits: you get an arbitrary reference (which may suffice anyway depending on your underlying goal).

Now, you can do something.  Specifically, the issue in this case is that Mercurial's branch names are global, and commits are permanently glued to the branch on which they were made.  If you connect to remote1 and receive some commits, they have whatever hash ID and branch name they have, and your Mercurial stores them in your repository under that same hash ID and using that same name—and now Mercurial (like Git) forgets the source, because those are now your commits.

But you do know that whatever commits just came in (if any) came from remote1, not remote2.  Moreover, if any commits did come in, they will have increased the local revision ID number (-r -n tip).  You can save that new number—or even the entire span—somewhere.  All of those commits in that span, "old tip + 1" to "new tip" inclusive, came from remote1.

Repeat this for remote2: any new commits that arrive came from them.

(There is another option, but it's drastic: you can use the Convert extension to change the branch names of commits as they come in.  If you do this, though, you are stuck with those commits being on the other branch: you would have to copy, i.e., graft or rebase, the commits to move them to their original branches later, if you want that.  There are additional, and better, extensions, but unlike Convert, they are not distributed with Mercurial.)


问:
AudioPlayer' (are you missing a using directive or an assembly reference?) (CS1061)
I tried to audio messenger in cross platform and I found one plugin.AudioRecorder but I need xaml and cs functional.

```<code> Error CS1061: 'AudioPlayer' does not contain a definition for
 'FinishedPlaying' and no extension method 'FinishedPlaying' accepting
 a first argument of type 'AudioPlayer' could be found (are you missing
 a using directive or an assembly reference?) (CS1061) (Qbakbak.iOS)
</code>```

please any one help me..

答:
1) Ensure that your references are correct and up to date(You might not be referencing the plugin .dll in your project)

2) Check your using statements (using AudioRecorder;)

3) Make sure you are in the correct namespace

4) Clean / Rebuild your project

Body:
I tried to audio messenger in cross platform and I found one plugin.AudioRecorder but I need xaml and cs functional.

 Error CS1061: 'AudioPlayer' does not contain a definition for
 'FinishedPlaying' and no extension method 'FinishedPlaying' accepting
 a first argument of type 'AudioPlayer' could be found (are you missing
 a using directive or an assembly reference?) (CS1061) (Qbakbak.iOS)

please any one help me..


问:
Previewing an image after it has been submitted through AJAX (Rails solution)?
I'm trying to see what is the best way to implement a mechanism as in use here: https://sortfolio.com/signup . Essentially, one selects a picture to be uploaded. Picture uploads in the background and then it appears on the page with no refresh required.

So far I manage to do the POST of the image (I'm posting to an IFrame, using a jQuery plugin) and show the progress bat. I don't quite understand, when / how to pull the image back.

I'm using paperclip for processing.

Any thoughts ?

Thanks.

答:
In your Rails controller, when responding to an AJAX request, send back the newly uploaded image URL, the entire image as a JSON object (w/ URL included), or the partial HTML to render the image.

For example, using the first method, use jQuery to set the src of the img.

Something like within the callback of the AJAX request:

```<code>$('#image').attr('src', /* url sent back from AJAX request */);</code>```

Body:
In your Rails controller, when responding to an AJAX request, send back the newly uploaded image URL, the entire image as a JSON object (w/ URL included), or the partial HTML to render the image.

For example, using the first method, use jQuery to set the src of the img.

Something like within the callback of the AJAX request:

$('#image').attr('src', /* url sent back from AJAX request */);


问:
How to use $regex in mongoDB query with string variable?
I am trying to do a simple wildcard query in a MongoDB database using a user-generated string variable. For example, if the user searches 'Bu', things like 'Burger' and 'Burger King' should be returned from the database.  I have searched and tried several things but nothing seems to work. Any help would be greatly appreciated. Note: This is client-side JS. </p>

```<code>    var text = document.getElementById("Search_Box").value;

    var regex = new RegExp(text + ".*");

    client.login().then(() => db.collection('businesses')
        .find({name:{$regex:regex}}).then(docs => {
          console.log("[MongoDB Stitch] Connected to Stitch");
</code>```

答:
If you had the following documents:

```<code>{
    "_id" : ObjectId("5a0f3a464d8a2fe38bec4e92"),
    "name" : "Burger"
}

{
    "_id" : ObjectId("5a0f3a464d8a2fe38bec4e94"),
    "name" : "Burger King"
}

{
    "_id" : ObjectId("5a0f3a464d8a2fe38bec4e96"),
    "name" : "Booby's"
}

{
    "_id" : ObjectId("5a0f3a464d8a2fe38bec4e98"),
    "name" : "McDonald"
}
</code>```

Starting with

To get everything starting with "Bu" you could do

```<code>db.collection('businesses').find({name: {$regex: '^Bu'}})
</code>```

or

```<code>db.collection('businesses').find({name: {$regex: /^Bu/}})
</code>```

In the middle of

If you needed anything that contained "Ki.*g" anywhere in the word you could do:

```<code>db.collection('businesses').find({name: {$regex: 'Ki.*g'}})
</code>```

or

```<code>db.collection('businesses').find({name: {$regex: /Ki.*g/}})
</code>```

Do the effort and go through the documentation. Everything is explained there, with a lot more details. https://docs.mongodb.com/manual/reference/operator/query/regex/

Body:
I am trying to do a simple wildcard query in a MongoDB database using a user-generated string variable. For example, if the user searches 'Bu', things like 'Burger' and 'Burger King' should be returned from the database.  I have searched and tried several things but nothing seems to work. Any help would be greatly appreciated. Note: This is client-side JS.

    var text = document.getElementById("Search_Box").value;

    var regex = new RegExp(text + ".*");

    client.login().then(() => db.collection('businesses')
        .find({name:{$regex:regex}}).then(docs => {
          console.log("[MongoDB Stitch] Connected to Stitch");

Body:
If you had the following documents:

{
    "_id" : ObjectId("5a0f3a464d8a2fe38bec4e92"),
    "name" : "Burger"
}

{
    "_id" : ObjectId("5a0f3a464d8a2fe38bec4e94"),
    "name" : "Burger King"
}

{
    "_id" : ObjectId("5a0f3a464d8a2fe38bec4e96"),
    "name" : "Booby's"
}

{
    "_id" : ObjectId("5a0f3a464d8a2fe38bec4e98"),
    "name" : "McDonald"
}

Starting with

To get everything starting with "Bu" you could do

db.collection('businesses').find({name: {$regex: '^Bu'}})

or

db.collection('businesses').find({name: {$regex: /^Bu/}})

In the middle of

If you needed anything that contained "Ki.*g" anywhere in the word you could do:

db.collection('businesses').find({name: {$regex: 'Ki.*g'}})

or

db.collection('businesses').find({name: {$regex: /Ki.*g/}})

Do the effort and go through the documentation. Everything is explained there, with a lot more details. https://docs.mongodb.com/manual/reference/operator/query/regex/


问:
How can a PresentingViewController get notified that its PresentedViewController dismissed itself?
Given:

ViewController A that presents ViewController B

ViewController B has no reference to ViewController A (except implicitly the presentingViewController property)

ViewController B calls dismiss on itself and does nothing else

What I want to achieve:

ViewController A wants to know when ViewController B got dismissed in order to clean up some state

Restrictions:

I do not want to use KVO

I do not want to modify ViewController B or its behavior in any way

What I have found out so far:

dismiss(animated:completion:) according to the documentation forwards the call to its presentingViewController. But as it seems dismiss(animated:completion:) is not called, but rather a private method _performCoordinatedPresentOrDismiss:animated:.

iOS documentation on presentingViewController is misleading. It says "the view controller that was presented has this property set to the view controller that presented it", but that's not true. In iOS 11, this will always point to the root parent VC of the VC that present was called on. Similarly the documentation on presentedViewController is misleading. It says "the view controller that called the method has this property set to the view controller that it presented", that's not the whole story. Every VC in the hierarchy of the VC (all its parent VCs and child VCs) that called present will point to the same presentedViewController.

答: In your Controller A , kame it as UINavigationControllerDelegate and with navigationController:didShowViewController mark the presentation of Controller B (isControllerBisPresented = true). When viewDidAppear of B , check if isControllerBisPresented is true.


问:
Can I use strcmp without pointers?
I have to make a program which takes a file of DNA sequences and a DNA subsequence from command arguments and find each time the subsequence and how many times it occurs. I'm having troubles with strcmp in line 36 and 42. Currently the way I have it I figured out through GDB that I am comparing the address of the strings and not the actual strings. But if I remove the & I get an error. I'm not sure what is the correct way to go about this is. TIA

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

int main(int argc, char *argv[]) {
    // place subsequence in string
    char *subsequence = argv[2];
    // get length of subsequence
    int seqLength = strlen(subsequence);
    // define file type and open for reading
    FILE *inputFile = fopen(argv[1], "r");
    // get each line using while loop
    char inputLine[200]; // string variable to store each line
    int i, j, lineLength, counter = 0, flag = -1;

    while (fgets(inputLine, 200, inputFile) != NULL) { // loop through each line
        lineLength = strlen(inputLine);

        for (i = 0; i < lineLength; i++) { // loop through each char in the line
            if (strcmp(&inputLine[i], &subsequence[0]) == 0) {
            // if current char matches beginning of sequence loop through
            // each of the remaining chars and check them against
            // corresponding chars in the sequence

                flag = 0;

                for (j = i + 1; j - i < seqLength; j++) {
                    if (strcmp(&inputLine[j], &subsequence[j - i]) != 0) {
                        flag = 1;
                        break;
                    }
                }

                if (flag == 0) {
                    counter++;
                }
            }
        }
    }

    fclose(inputFile);
    printf("%s appears %d time(s)\n", subsequence, counter);
    return 0;
}
</code>```

dna.txt:

```<code>GGAAGTAGCAGGCCGCATGCTTGGAGGTAAAGTTCATGGTTCCCTGGCCC
</code>```

input:

```<code>./dnaSearch dna.txt GTA
</code>```

expected output:

```<code>GTA appears 2 times
</code>```

答:
Just do like this:

```<code>if (inputLine[i] == subsequence[0]) {
    if (inputLine[j] != subsequence[j - i]) {
</code>```

You do not need library functions to compare single characters.

Title: Can I use strcmp without pointers?

Body:
I have to make a program which takes a file of DNA sequences and a DNA subsequence from command arguments and find each time the subsequence and how many times it occurs. I'm having troubles with strcmp in line 36 and 42. Currently the way I have it I figured out through GDB that I am comparing the address of the strings and not the actual strings. But if I remove the & I get an error. I'm not sure what is the correct way to go about this is. TIA

#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[]) {
    // place subsequence in string
    char *subsequence = argv[2];
    // get length of subsequence
    int seqLength = strlen(subsequence);
    // define file type and open for reading
    FILE *inputFile = fopen(argv[1], "r");
    // get each line using while loop
    char inputLine[200]; // string variable to store each line
    int i, j, lineLength, counter = 0, flag = -1;

    while (fgets(inputLine, 200, inputFile) != NULL) { // loop through each line
        lineLength = strlen(inputLine);

        for (i = 0; i < lineLength; i++) { // loop through each char in the line
            if (strcmp(&inputLine[i], &subsequence[0]) == 0) {
            // if current char matches beginning of sequence loop through
            // each of the remaining chars and check them against
            // corresponding chars in the sequence

                flag = 0;

                for (j = i + 1; j - i < seqLength; j++) {
                    if (strcmp(&inputLine[j], &subsequence[j - i]) != 0) {
                        flag = 1;
                        break;
                    }
                }

                if (flag == 0) {
                    counter++;
                }
            }
        }
    }

    fclose(inputFile);
    printf("%s appears %d time(s)\n", subsequence, counter);
    return 0;
}

dna.txt:

GGAAGTAGCAGGCCGCATGCTTGGAGGTAAAGTTCATGGTTCCCTGGCCC

input:

./dnaSearch dna.txt GTA

expected output:

GTA appears 2 times

Body:
Just do like this:

if (inputLine[i] == subsequence[0]) {
    if (inputLine[j] != subsequence[j - i]) {

You do not need library functions to compare single characters.


问:
r - fill columns in data frame
```<code>    V1 V2 V3
1   a  b  c
2   a  d  c
3   a  b  g
4   f  b  c
5   a  b  c
6   a  b  c
7   a  b  c
</code>```

I want to fill columns in data frame with values from rows above. It should look like this.

```<code>    V1 V2 V3
1   a  b  c
2   a  d  c
3   a  d  g
4   f  d  g
5   f  d  g
6   f  d  g
7   f  d  g
</code>```

答:
Here's another solution using cumany in dplyr:

```<code>library(dplyr)

df %>%
  mutate_all(funs(ifelse(cumany(. == max(.)), max(.), .)))
</code>```

Result:

```<code>  V1 V2 V3
1  a  b  c
2  a  d  c
3  a  d  g
4  f  d  g
5  f  d  g
6  f  d  g
7  f  d  g
</code>```

Title: r - fill columns in data frame

Body:
    V1 V2 V3
1   a  b  c
2   a  d  c
3   a  b  g
4   f  b  c
5   a  b  c
6   a  b  c
7   a  b  c

I want to fill columns in data frame with values from rows above. It should look like this.

    V1 V2 V3
1   a  b  c
2   a  d  c
3   a  d  g
4   f  d  g
5   f  d  g
6   f  d  g
7   f  d  g

Body:
Here's another solution using cumany in dplyr:

library(dplyr)

df %>%
  mutate_all(funs(ifelse(cumany(. == max(.)), max(.), .)))

Result:

  V1 V2 V3
1  a  b  c
2  a  d  c
3  a  d  g
4  f  d  g
5  f  d  g
6  f  d  g
7  f  d  g


问:
Adding Title Formatter to ggplot2
I'm working on a package that will make it easier for other users at my company to use ggplot2. One of the things I would like to do is to add a function that automatically formats ugly variable names to pretty titles.

I have a function that does this already. Let's assume there's some dummy data and a basic plot:

```<code>data <- data.frame(
  place_name = c("Los Angeles","New York"),
  some_amount = c(5,10)
)

g <- ggplot(data, aes(x = place_name, y = some_amount)) +
  geom_bar(stat = 'identity') +
  labs(title = "test_of_function")
</code>```

So I have my ggplot, and I want to format the titles. This function works fine once I apply it to the labels of a function.

```<code>format_title <- function(...,sep = "[^[:alnum:]]+"){

  args <- list(...)

  if (is.list(args[[1]]))
    args <- args[[1]]

  lapply(args, function(x, sep){
    stringr::str_to_title(stringr::str_replace_all(x,sep," "))
  }, sep = sep)
}

format_plot_titles <- function(g){
  g$labels <- format_title(g$labels)
  g
}
</code>```

So now if we compare them:

```<code>g
</code>```

```<code>format_plot_titles(g)
</code>```

What I was hoping to do is add it via the ggplot2 +, but in order to do that I need access to what the previous labels of the plot were.

It would look something like this (with better names):

```<code>ggplot(data, aes(x = place_name, y = some_amount)) +
    geom_bar() +
    title_labels()
</code>```

I'm having a lot of trouble figuring out how to access the labels of the previous plot as I attempt to layer the new labels on top of the old one. Any help is appreciated!

Edit: Solved this. There was no slick solution though. I basically had to overwrite the default s3 method for the + that ggplot2 exports to take in a new type of object I'm calling a "formatter". This allows me to construct a method that checks for the formatter class, and if my object does inherit the formatter class, it applies that formatter to the plot labels. Here's the code:

```<code>`+.gg` <- function (e1, e2) {
  e2name <- deparse(substitute(e2))
  if (ggplot2::is.theme(e1))
    ggplot2:::add_theme(e1, e2, e2name)
  else if (ggplot2::is.ggplot(e1) & is.formatter(e2)){
    add_formatter(e1, e2, e2name)
  }
  else if (ggplot2::is.ggplot(e1))
    ggplot2:::add_ggplot(e1, e2, e2name)
}

update_format <- function(p, formatter){
  p <- ggplot2:::plot_clone(p)
  p$labels <- formatter(p$labels)
  p
}

add_formatter <- function(p, formatter, objectname) {
  update_format(p, formatter)
}

is.formatter <- function(x){
  inherits(x,"formatter")
}

format_title <- function(...,sep = "[^[:alnum:]]+"){

  args <- list(...)

  if (is.list(args[[1]]))
    args <- args[[1]]

  lapply(args, function(x, sep){
    stringr::str_to_title(stringr::str_replace_all(x,sep," "))
  }, sep = sep)
}

title_labels <- function(...){
  structure(format_title, class = "formatter")
}

ggplot(data, aes(x = place_name, y = some_amount)) +
  geom_bar(stat = 'identity') +
  title_labels()
</code>```

答:
Posting edit as a formal answer.

Solved this. There was no slick solution though. I basically had to overwrite the default s3 method for the + that ggplot2 exports to take in a new type of object I'm calling a "formatter". This allows me to construct a method that checks for the formatter class, and if my object does inherit the formatter class, it applies that formatter to the plot labels. Here's the code:

```<code>`+.gg` <- function (e1, e2) {
  e2name <- deparse(substitute(e2))
  if (ggplot2::is.theme(e1))
    ggplot2:::add_theme(e1, e2, e2name)
  else if (ggplot2::is.ggplot(e1) & is.formatter(e2)){
    add_formatter(e1, e2, e2name)
  }
  else if (ggplot2::is.ggplot(e1))
    ggplot2:::add_ggplot(e1, e2, e2name)
}

update_format <- function(p, formatter){
  p <- ggplot2:::plot_clone(p)
  p$labels <- formatter(p$labels)
  p
}

add_formatter <- function(p, formatter, objectname) {
  update_format(p, formatter)
}

is.formatter <- function(x){
  inherits(x,"formatter")
}

format_title <- function(...,sep = "[^[:alnum:]]+"){

  args <- list(...)

  if (is.list(args[[1]]))
    args <- args[[1]]

  lapply(args, function(x, sep){
    stringr::str_to_title(stringr::str_replace_all(x,sep," "))
  }, sep = sep)
}

title_labels <- function(...){
  structure(format_title, class = "formatter")
}

ggplot(data, aes(x = place_name, y = some_amount)) +
  geom_bar(stat = 'identity') +
  title_labels()
</code>```

Title: Adding Title Formatter to ggplot2

Body:
I'm working on a package that will make it easier for other users at my company to use ggplot2. One of the things I would like to do is to add a function that automatically formats ugly variable names to pretty titles.

I have a function that does this already. Let's assume there's some dummy data and a basic plot:

data <- data.frame(
  place_name = c("Los Angeles","New York"),
  some_amount = c(5,10)
)

g <- ggplot(data, aes(x = place_name, y = some_amount)) +
  geom_bar(stat = 'identity') +
  labs(title = "test_of_function")

So I have my ggplot, and I want to format the titles. This function works fine once I apply it to the labels of a function.

format_title <- function(...,sep = "[^[:alnum:]]+"){

  args <- list(...)

  if (is.list(args[[1]]))
    args <- args[[1]]

  lapply(args, function(x, sep){
    stringr::str_to_title(stringr::str_replace_all(x,sep," "))
  }, sep = sep)
}

format_plot_titles <- function(g){
  g$labels <- format_title(g$labels)
  g
}

So now if we compare them:

g

format_plot_titles(g)

What I was hoping to do is add it via the ggplot2 +, but in order to do that I need access to what the previous labels of the plot were.

It would look something like this (with better names):

ggplot(data, aes(x = place_name, y = some_amount)) +
    geom_bar() +
    title_labels()

I'm having a lot of trouble figuring out how to access the labels of the previous plot as I attempt to layer the new labels on top of the old one. Any help is appreciated!

Edit: Solved this. There was no slick solution though. I basically had to overwrite the default s3 method for the + that ggplot2 exports to take in a new type of object I'm calling a "formatter". This allows me to construct a method that checks for the formatter class, and if my object does inherit the formatter class, it applies that formatter to the plot labels. Here's the code:

`+.gg` <- function (e1, e2) {
  e2name <- deparse(substitute(e2))
  if (ggplot2::is.theme(e1))
    ggplot2:::add_theme(e1, e2, e2name)
  else if (ggplot2::is.ggplot(e1) & is.formatter(e2)){
    add_formatter(e1, e2, e2name)
  }
  else if (ggplot2::is.ggplot(e1))
    ggplot2:::add_ggplot(e1, e2, e2name)
}

update_format <- function(p, formatter){
  p <- ggplot2:::plot_clone(p)
  p$labels <- formatter(p$labels)
  p
}

add_formatter <- function(p, formatter, objectname) {
  update_format(p, formatter)
}

is.formatter <- function(x){
  inherits(x,"formatter")
}

format_title <- function(...,sep = "[^[:alnum:]]+"){

  args <- list(...)

  if (is.list(args[[1]]))
    args <- args[[1]]

  lapply(args, function(x, sep){
    stringr::str_to_title(stringr::str_replace_all(x,sep," "))
  }, sep = sep)
}

title_labels <- function(...){
  structure(format_title, class = "formatter")
}

ggplot(data, aes(x = place_name, y = some_amount)) +
  geom_bar(stat = 'identity') +
  title_labels()

Body:
Posting edit as a formal answer.

Solved this. There was no slick solution though. I basically had to overwrite the default s3 method for the + that ggplot2 exports to take in a new type of object I'm calling a "formatter". This allows me to construct a method that checks for the formatter class, and if my object does inherit the formatter class, it applies that formatter to the plot labels. Here's the code:

`+.gg` <- function (e1, e2) {
  e2name <- deparse(substitute(e2))
  if (ggplot2::is.theme(e1))
    ggplot2:::add_theme(e1, e2, e2name)
  else if (ggplot2::is.ggplot(e1) & is.formatter(e2)){
    add_formatter(e1, e2, e2name)
  }
  else if (ggplot2::is.ggplot(e1))
    ggplot2:::add_ggplot(e1, e2, e2name)
}

update_format <- function(p, formatter){
  p <- ggplot2:::plot_clone(p)
  p$labels <- formatter(p$labels)
  p
}

add_formatter <- function(p, formatter, objectname) {
  update_format(p, formatter)
}

is.formatter <- function(x){
  inherits(x,"formatter")
}

format_title <- function(...,sep = "[^[:alnum:]]+"){

  args <- list(...)

  if (is.list(args[[1]]))
    args <- args[[1]]

  lapply(args, function(x, sep){
    stringr::str_to_title(stringr::str_replace_all(x,sep," "))
  }, sep = sep)
}

title_labels <- function(...){
  structure(format_title, class = "formatter")
}

ggplot(data, aes(x = place_name, y = some_amount)) +
  geom_bar(stat = 'identity') +
  title_labels()


问:
A CSS selector to get last visible div
A tricky CSS selector question, don't know if it's even possible.

Lets say this is the HTML layout:

```<code><div></div>
<div></div>
<div></div>
<div style="display:none"></div>
<div style="display:none"></div>
</code>```

I want to select the last div, which is displayed (ie. not display:none) which would be the third div in the given example.
Mind you, the number of divs on the real page can differ (even the display:none ones).

答:
This worked for me. </p>

```<code>.alert:not(:first-child){
    margin: 30px;
}
</code>```

Title: A CSS selector to get last visible div

Body:
A tricky CSS selector question, don't know if it's even possible.

Lets say this is the HTML layout:

I want to select the last div, which is displayed (ie. not display:none) which would be the third div in the given example.
Mind you, the number of divs on the real page can differ (even the display:none ones).

Body:
This worked for me.

.alert:not(:first-child){
    margin: 30px;
}