问:
segmentation fault(core dumped) error while using inline assembly
I'm using inline assembly in GCC. I want to rotate a variable content 2 bits to the left (I moved the variable to the rax register and then rotate it 2 times). I wrote the code below but I faced segmentation fault(core dumped) error.
I would be grateful if you could help me.</p>

```<code>uint64_t X = 13835058055282163712U;
 asm volatile(
            "movq %0 , %%rax\n"
            "rol %%rax\n"
            "rol %%rax\n"
            :"=r"(X)
            :"r"(X)
         );
printf("%" PRIu64 "\n" , X);
</code>```

答:
The key to understanding inline asm is to understand that each asm statement has two parts:

The text of the actual assembler stuff, in which the compiler will make textual substitutions, but does not understand.

This is the AssemblerTemplate in the documentation (everything up to the first : in the __asm__()).

A description of what the assembler stuff does, in terms that the compiler does understand.

This the : OutputOperands : InputOperands : Clobbers in the documentation.

This must tell the compiler how the assembler fits in with all the code which the compiler is generating around it.  The code generation is busy allocating registers to hold values, deciding what order to do things in, moving things out of loops, eliminating unused fragments of code, discarding values it no longer needs, and so on.

The actual assembler is a black box which takes the inputs described here, produces the outputs described and as a side effect may 'clobber' some registers and/or memory.  This must be a complete description of what the assembler does... otherwise the compiler-generated asm around your template will clash with it and rely on false assumptions.

Armed with this information the compiler can decide what registers the assembler can use, and you should let it do that.

So, your fragment:

```<code> asm volatile(
            "movq %0 , %%rax\n"
            "rol %%rax\n"
            "rol %%rax\n"
            :"=r"(X)
            :"r"(X)
         );
</code>```

has a few "issues":

you may have chosen %rax for the result on the basis that the asm() is like a function, and may be expected to return a result in %rax -- but that isn't so.

you went ahead and used %rax, which the compiler may (well) already have allocated to something else... so you are, effectively, 'clobbering' %rax but you have failed to tell the compiler about it !

you specified =r(X) (OutputOperand) which tells the compiler to expect an output in some register and that output will be the new value of the variable X.  The %0 in the AssemblerTemplate will be replaced by the register selected for the output.  Sadly, your assembly treats %0 as the input :-(  And the output is, in fact, in %rax -- which, as above, the compiler is unaware of.

you also specified r(X) (InputOperand) which tells the compiler to arrange for the current value of the variable X to be placed in some register for the assembler to use.  This would be %1 in the AssemblerTemplate.  Sadly, your assembly does not use this input.

Even though the output and input operands both refer to X, the compiler may not make %0 the same register as %1.  (This allows it to use the asm block as a non-destructive operation that leaves the original value of an input unmodified.  If this isn't how your template works, don't write it that way.

generally you don't need the volatile when all the inputs and outputs are properly described by constraints.  One of the fine things the compiler will do is discard an asm() if (all of) the output(s) are not used... volatile tells the compiler not to do that (and tells it a number of other things... see the manual).

Apart from that, things were wonderful.  The following is safe, and avoids a mov instruction:

```<code> asm("rol %0\n"
     "rol %0\n"   : "+r"(X));
</code>```

where "+r"(X) says that there is one combined input and output register required, taking the old value of X and returning a new one.

Now, if you don't want to replace X, then assuming Y is to be the result, you could:

```<code> asm("mov %1, %0\n"
     "rol %0\n"
     "rol %0\n"   : "=r"(Y) : "r"(X));
</code>```

But it's better to leave it up to the compiler to decide whether it needs to mov or whether it can just let an input be destroyed.

There are a couple of rules about InputOperands which are worth mentioning:

The assembler must not overwrite any of the InputOperands -- the compiler is tracking which values it has in which registers, and is expecting InputOperands to be preserved.

The compiler expects all InputOperands to be read before any OutputOperand is written.  This is important when the compiler knows that a given InputOperand is not used again after the asm(), and it can therefore allocate the InputOperand's register to an OutputOperand.  There is a thing called earlyclobber (=&r(foo)) to deal with this little wrinkle.

In the above, if you don't in fact use X again the compiler could allocate %0 and %1 to the same register!  But the (redundant) mov will still be assembled -- remembering that the compiler really doesn't understand the AssemblerTemplate.  So, you are in general better off shuffling values around in the C, not the asm().  See https://gcc.gnu.org/wiki/DontUseInlineAsm and  Best practices for circular shift (rotate) operations in C++

So here are four variations on a theme, and the code generated (gcc -O2):

```<code>// (1) uses both X and Y in the printf() -- does mov %1, %0 in asm()
void Never_Inline footle(void)               Dump of assembler code for function footle:
{                                              mov    $0x492782,%edi   # address of format string
  unsigned long  X, Y ;                        xor    %eax,%eax
                                               mov    $0x63,%esi       # X = 99
  X = 99 ;                                     rol    %rsi            # 1st asm
  __asm__("\t rol  %0\n"                       rol    %rsi
          "\t rol  %0\n" : "+r"(X)             mov    %rsi,%rdx       # 2nd asm, compiler using it as a copy-and-rotate
      ) ;                                      rol    %rdx
                                               rol    %rdx
  __asm__("\t mov  %1, %0\n"                   jmpq   0x4010a0 <printf@plt>  # tailcall printf
          "\t rol  %0\n"
          "\t rol  %0\n" : "=r"(Y) : "r"(X)
      ) ;

  printf("%lx %lx\n", X, Y) ;
}

// (2) uses both X and Y in the printf() -- does Y = X in 'C'
void Never_Inline footle(void)               Dump of assembler code for function footle:
{                                              mov    $0x492782,%edi
  unsigned long  X, Y ;                        xor    %eax,%eax
                                               mov    $0x63,%esi
  X = 99 ;                                     rol    %rsi       # 1st asm
  __asm__("\t rol  %0\n"                       rol    %rsi
          "\t rol  %0\n" : "+r"(X)             mov    %rsi,%rdx  # compiler-generated mov
      ) ;                                      rol    %rdx       # 2nd asm
                                               rol    %rdx
  Y = X ;                                      jmpq   0x4010a0 <printf@plt>
  __asm__("\t rol  %0\n"
          "\t rol  %0\n" : "+r"(Y)
      ) ;

  printf("%lx %lx\n", X, Y) ;
}

// (3) uses only Y in the printf() -- does mov %1, %0 in asm()
void Never_Inline footle(void)               Dump of assembler code for function footle:
{                                              mov    $0x492782,%edi
  unsigned long  X, Y ;                        xor    %eax,%eax
                                               mov    $0x63,%esi
  X = 99 ;                                     rol    %rsi
  __asm__("\t rol  %0\n"                       rol    %rsi
          "\t rol  %0\n" : "+r"(X)             mov    %rsi,%rsi   # redundant instruction because of mov in the asm template
      ) ;                                      rol    %rsi
                                               rol    %rsi
  __asm__("\t mov  %1, %0\n"                   jmpq   0x4010a0 <printf@plt>
          "\t rol  %0\n"
          "\t rol  %0\n" : "=r"(Y) : "r"(X)
      ) ;

  printf("%lx\n", Y) ;
}

// (4) uses only Y in the printf() -- does Y = X in 'C'
void Never_Inline footle(void)               Dump of assembler code for function footle:
{                                              mov    $0x492782,%edi
  unsigned long  X, Y ;                        xor    %eax,%eax
                                               mov    $0x63,%esi
  X = 99 ;                                     rol    %rsi
  __asm__("\t rol  %0\n"                       rol    %rsi
          "\t rol  %0\n" : "+r"(X)             rol    %rsi    # no wasted mov, compiler picked %0=%1=%rsi
      ) ;                                      rol    %rsi
                                               jmpq   0x4010a0 <printf@plt>
  Y = X ;
  __asm__("\t rol  %0\n"
          "\t rol  %0\n" : "+r"(Y)
      ) ;

  printf("%lx\n", Y) ;
}
</code>```

which, hopefully, demonstrates the compiler busily allocating values to registers, tracking which values it needs to hold on to, minimizing register/register moves, and generally being clever.

So the trick is to work with the compiler, understanding that the :OutputOperands:InputOperands:Clobbers is where you are describing what the assembler is doing.

Body:
I'm using inline assembly in GCC. I want to rotate a variable content 2 bits to the left (I moved the variable to the rax register and then rotate it 2 times). I wrote the code below but I faced segmentation fault(core dumped) error.
I would be grateful if you could help me.

uint64_t X = 13835058055282163712U;
 asm volatile(
            "movq %0 , %%rax\n"
            "rol %%rax\n"
            "rol %%rax\n"
            :"=r"(X)
            :"r"(X)
         );
printf("%" PRIu64 "\n" , X);

Body:
The key to understanding inline asm is to understand that each asm statement has two parts:

The text of the actual assembler stuff, in which the compiler will make textual substitutions, but does not understand.

This is the AssemblerTemplate in the documentation (everything up to the first : in the __asm__()).

A description of what the assembler stuff does, in terms that the compiler does understand.

This the : OutputOperands : InputOperands : Clobbers in the documentation.

This must tell the compiler how the assembler fits in with all the code which the compiler is generating around it.  The code generation is busy allocating registers to hold values, deciding what order to do things in, moving things out of loops, eliminating unused fragments of code, discarding values it no longer needs, and so on.

The actual assembler is a black box which takes the inputs described here, produces the outputs described and as a side effect may 'clobber' some registers and/or memory.  This must be a complete description of what the assembler does... otherwise the compiler-generated asm around your template will clash with it and rely on false assumptions.

Armed with this information the compiler can decide what registers the assembler can use, and you should let it do that.

So, your fragment:

 asm volatile(
            "movq %0 , %%rax\n"
            "rol %%rax\n"
            "rol %%rax\n"
            :"=r"(X)
            :"r"(X)
         );

has a few "issues":

you may have chosen %rax for the result on the basis that the asm() is like a function, and may be expected to return a result in %rax -- but that isn't so.

you went ahead and used %rax, which the compiler may (well) already have allocated to something else... so you are, effectively, 'clobbering' %rax but you have failed to tell the compiler about it !

you specified =r(X) (OutputOperand) which tells the compiler to expect an output in some register and that output will be the new value of the variable X.  The %0 in the AssemblerTemplate will be replaced by the register selected for the output.  Sadly, your assembly treats %0 as the input :-(  And the output is, in fact, in %rax -- which, as above, the compiler is unaware of.

you also specified r(X) (InputOperand) which tells the compiler to arrange for the current value of the variable X to be placed in some register for the assembler to use.  This would be %1 in the AssemblerTemplate.  Sadly, your assembly does not use this input.

Even though the output and input operands both refer to X, the compiler may not make %0 the same register as %1.  (This allows it to use the asm block as a non-destructive operation that leaves the original value of an input unmodified.  If this isn't how your template works, don't write it that way.

generally you don't need the volatile when all the inputs and outputs are properly described by constraints.  One of the fine things the compiler will do is discard an asm() if (all of) the output(s) are not used... volatile tells the compiler not to do that (and tells it a number of other things... see the manual).

Apart from that, things were wonderful.  The following is safe, and avoids a mov instruction:

 asm("rol %0\n"
     "rol %0\n"   : "+r"(X));

where "+r"(X) says that there is one combined input and output register required, taking the old value of X and returning a new one.

Now, if you don't want to replace X, then assuming Y is to be the result, you could:

 asm("mov %1, %0\n"
     "rol %0\n"
     "rol %0\n"   : "=r"(Y) : "r"(X));

But it's better to leave it up to the compiler to decide whether it needs to mov or whether it can just let an input be destroyed.

There are a couple of rules about InputOperands which are worth mentioning:

The assembler must not overwrite any of the InputOperands -- the compiler is tracking which values it has in which registers, and is expecting InputOperands to be preserved.

The compiler expects all InputOperands to be read before any OutputOperand is written.  This is important when the compiler knows that a given InputOperand is not used again after the asm(), and it can therefore allocate the InputOperand's register to an OutputOperand.  There is a thing called earlyclobber (=&r(foo)) to deal with this little wrinkle.

In the above, if you don't in fact use X again the compiler could allocate %0 and %1 to the same register!  But the (redundant) mov will still be assembled -- remembering that the compiler really doesn't understand the AssemblerTemplate.  So, you are in general better off shuffling values around in the C, not the asm().  See https://gcc.gnu.org/wiki/DontUseInlineAsm and  Best practices for circular shift (rotate) operations in C++

So here are four variations on a theme, and the code generated (gcc -O2):

// (1) uses both X and Y in the printf() -- does mov %1, %0 in asm()
void Never_Inline footle(void)               Dump of assembler code for function footle:
{                                              mov    $0x492782,%edi   # address of format string
  unsigned long  X, Y ;                        xor    %eax,%eax
                                               mov    $0x63,%esi       # X = 99
  X = 99 ;                                     rol    %rsi            # 1st asm
  __asm__("\t rol  %0\n"                       rol    %rsi
          "\t rol  %0\n" : "+r"(X)             mov    %rsi,%rdx       # 2nd asm, compiler using it as a copy-and-rotate
      ) ;                                      rol    %rdx
                                               rol    %rdx
  __asm__("\t mov  %1, %0\n"                   jmpq   0x4010a0 <printf@plt>  # tailcall printf
          "\t rol  %0\n"
          "\t rol  %0\n" : "=r"(Y) : "r"(X)
      ) ;

  printf("%lx %lx\n", X, Y) ;
}

// (2) uses both X and Y in the printf() -- does Y = X in 'C'
void Never_Inline footle(void)               Dump of assembler code for function footle:
{                                              mov    $0x492782,%edi
  unsigned long  X, Y ;                        xor    %eax,%eax
                                               mov    $0x63,%esi
  X = 99 ;                                     rol    %rsi       # 1st asm
  __asm__("\t rol  %0\n"                       rol    %rsi
          "\t rol  %0\n" : "+r"(X)             mov    %rsi,%rdx  # compiler-generated mov
      ) ;                                      rol    %rdx       # 2nd asm
                                               rol    %rdx
  Y = X ;                                      jmpq   0x4010a0 <printf@plt>
  __asm__("\t rol  %0\n"
          "\t rol  %0\n" : "+r"(Y)
      ) ;

  printf("%lx %lx\n", X, Y) ;
}

// (3) uses only Y in the printf() -- does mov %1, %0 in asm()
void Never_Inline footle(void)               Dump of assembler code for function footle:
{                                              mov    $0x492782,%edi
  unsigned long  X, Y ;                        xor    %eax,%eax
                                               mov    $0x63,%esi
  X = 99 ;                                     rol    %rsi
  __asm__("\t rol  %0\n"                       rol    %rsi
          "\t rol  %0\n" : "+r"(X)             mov    %rsi,%rsi   # redundant instruction because of mov in the asm template
      ) ;                                      rol    %rsi
                                               rol    %rsi
  __asm__("\t mov  %1, %0\n"                   jmpq   0x4010a0 <printf@plt>
          "\t rol  %0\n"
          "\t rol  %0\n" : "=r"(Y) : "r"(X)
      ) ;

  printf("%lx\n", Y) ;
}

// (4) uses only Y in the printf() -- does Y = X in 'C'
void Never_Inline footle(void)               Dump of assembler code for function footle:
{                                              mov    $0x492782,%edi
  unsigned long  X, Y ;                        xor    %eax,%eax
                                               mov    $0x63,%esi
  X = 99 ;                                     rol    %rsi
  __asm__("\t rol  %0\n"                       rol    %rsi
          "\t rol  %0\n" : "+r"(X)             rol    %rsi    # no wasted mov, compiler picked %0=%1=%rsi
      ) ;                                      rol    %rsi
                                               jmpq   0x4010a0 <printf@plt>
  Y = X ;
  __asm__("\t rol  %0\n"
          "\t rol  %0\n" : "+r"(Y)
      ) ;

  printf("%lx\n", Y) ;
}

which, hopefully, demonstrates the compiler busily allocating values to registers, tracking which values it needs to hold on to, minimizing register/register moves, and generally being clever.

So the trick is to work with the compiler, understanding that the :OutputOperands:InputOperands:Clobbers is where you are describing what the assembler is doing.


来源: stackexchange

问:
Boost MPL to generate code for object serialization?
I want to generate serialization/deserialization code for

```<code>class Object
{
    string a;
    int b;
    long c;
    char d;
};
</code>```

by looking at a mpl sequence, but I need to be able to identify object and retrieve it back as well, I can't figure out how would I get the names of it members, do I have to know it?

code should look like

```<code>void SerializeObject(ostream os)
{
   serialize(object.a, os);
   serialize(object.b, os);

   //serialize(object.member, os);
}
</code>```

I want to generate above code by user only defining a mpl sequence corresponding the object layout, is it doable, can you give me some hints?

my aim is:

User defines mpl::vector<String, int, long, char> for above object and my metaprogram can generate the coded needed.

答:
Consider a boost::fusion, and use the macro BOOST_FUSION_ADAPT_STRUCT() to promote your structure to a fusion sequence (random access), e.g. once you've defined the above structure, you can do something like

```<code>BOOST_FUSION_ADAPT_STRUCT(
    Object,
    (std::string, a)
    (int, b)
    (long, c)
    (char, d)
)
</code>```

Now that it's been promoted, you can simply use a for_each to iterate over the members, something like:

```<code>template<typename archive>
struct serializer {
   serializer(archive& ar):ar(ar) {}

   template<typename T>
   void operator()(const T& o) const {
      ar & o;  // assuming binary for example...
   }
   archive& ar;
};

template<typename archive, typename sequence>
void serialize(archive& ar, sequence const& v) {
   boost::fusion::for_each(v, serializer<archive>(ar));
}
</code>```

To use, it should be as simple as:

```<code>Object foo; // instance to serialize
serialize(<archive>, foo);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to generate serialization/deserialization code for

class Object
{
    string a;
    int b;
    long c;
    char d;
};

by looking at a mpl sequence, but I need to be able to identify object and retrieve it back as well, I can't figure out how would I get the names of it members, do I have to know it?

code should look like

void SerializeObject(ostream os)
{
   serialize(object.a, os);
   serialize(object.b, os);

   //serialize(object.member, os);
}

I want to generate above code by user only defining a mpl sequence corresponding the object layout, is it doable, can you give me some hints?

my aim is:

User defines mpl::vector<String, int, long, char> for above object and my metaprogram can generate the coded needed.

Body:
Consider a boost::fusion, and use the macro BOOST_FUSION_ADAPT_STRUCT() to promote your structure to a fusion sequence (random access), e.g. once you've defined the above structure, you can do something like

BOOST_FUSION_ADAPT_STRUCT(
    Object,
    (std::string, a)
    (int, b)
    (long, c)
    (char, d)
)

Now that it's been promoted, you can simply use a for_each to iterate over the members, something like:

template<typename archive>
struct serializer {
   serializer(archive& ar):ar(ar) {}

   template<typename T>
   void operator()(const T& o) const {
      ar & o;  // assuming binary for example...
   }
   archive& ar;
};

template<typename archive, typename sequence>
void serialize(archive& ar, sequence const& v) {
   boost::fusion::for_each(v, serializer<archive>(ar));
}

To use, it should be as simple as:

Object foo; // instance to serialize
serialize(<archive>, foo);


问:
Secure way to run `sudo` commands in Azure Devops SSH Task
I have to run few commands in Azure VM through Azure Devops release pipeline. I created SSH step and can successfully connect to remote VM. But having trouble running commands which requires sudo permissions.

e.g systemctl restart <some service>

```<code>errors :
##[error][sudo] password for ***:
##[error]Command failed with errors on remote machine.
</code>```

i tried echo <password> | sudo -S systemctl restart <some service>. No luck.

What is secure way to accomplish this?

答:
This is exactly what you need, it works in my azure devops pipeline on my ubuntu server:

https://serverfault.com/questions/772778/allowing-a-non-root-user-to-restart-a-service

Command for ssh task in azure pipeline:

```<code>sudo systemctl restart <some service>
</code>```

and in linux machine (ubuntu in my case):

```<code>sudo visudo -f /etc/sudoers.d/90-clouding-ubuntu
</code>```

add these two lines

```<code>Cmnd_Alias RESTART_SVC = /bin/systemctl restart <some service>
%<myuser> ALL=(ALL) NOPASSWD: RESTART_SVC
</code>```

You must write right service name and right username (must have rights for sudo).

ContentLicense: CC BY-SA 4.0

Body:
I have to run few commands in Azure VM through Azure Devops release pipeline. I created SSH step and can successfully connect to remote VM. But having trouble running commands which requires sudo permissions.

e.g systemctl restart <some service>

errors :
##[error][sudo] password for ***:
##[error]Command failed with errors on remote machine.

i tried echo <password> | sudo -S systemctl restart <some service>. No luck.

What is secure way to accomplish this?

Body:
This is exactly what you need, it works in my azure devops pipeline on my ubuntu server:

https://serverfault.com/questions/772778/allowing-a-non-root-user-to-restart-a-service

Command for ssh task in azure pipeline:

sudo systemctl restart <some service>

and in linux machine (ubuntu in my case):

sudo visudo -f /etc/sudoers.d/90-clouding-ubuntu

add these two lines

Cmnd_Alias RESTART_SVC = /bin/systemctl restart <some service>
%<myuser> ALL=(ALL) NOPASSWD: RESTART_SVC

You must write right service name and right username (must have rights for sudo).


问:
React-admin table displays twice
From some reason the code I write here build 2 tables and displaying both.
I tried to re-write it many times and still displaying 2 tables.

users.js

results:

what should I try?

答: It may be that you loaded the entire App component twice. To test that you can try to render some string in the App component. It could also be that Admin renders Users already.

Title: React-admin table displays twice


问:
Hide and show a div using input value using JavaScript
Someone help me with the below code I want to hide and show a div using input value using JavaScript.

        <form name="myform">

<input type="text" id="ref3" value="">

                Show me

        </form>

    ```

答:
Just call updateUI function on blur event of the textbox. You can also use onkeyup event to immediately reflect the change.

HTML

```<code><form name="myform">
        <div><input type="text" id="ref3" value="" onblur="updateUI()"></div>
        <div id="hotapp3" style="visibility:hidden">
            <label>Show me</label>
        </div>
</form>
</code>```

JavaScript

```<code>function updateUI() {
    var value = document.getElementById('ref3').value;
    if (Number(value) == 2) {
        document.getElementById('hotapp3').style.visibility = 'visible';
    } else {
        document.getElementById('hotapp3').style.visibility = 'hidden';
    }
}
</code>```

Here is working JSFiddle - https://jsfiddle.net/86yfgwk9/

Body:
Just call updateUI function on blur event of the textbox. You can also use onkeyup event to immediately reflect the change.

HTML

<form name="myform">
        <div><input type="text" id="ref3" value="" onblur="updateUI()"></div>
        <div id="hotapp3" style="visibility:hidden">
            <label>Show me</label>
        </div>
</form>

JavaScript

function updateUI() {
    var value = document.getElementById('ref3').value;
    if (Number(value) == 2) {
        document.getElementById('hotapp3').style.visibility = 'visible';
    } else {
        document.getElementById('hotapp3').style.visibility = 'hidden';
    }
}

Here is working JSFiddle - https://jsfiddle.net/86yfgwk9/


问:
How to handle secrets in Google App Engine?
My application needs a bunch of secrets to run: database credentials, API credentials, etc. It's running in Google App Engine Standard Java 11. I need these secrets as environment variables or as arguments to my application, so that my framework can pick them up and establish the connections accordingly. My particular framework is Spring Boot, but I believe Django, Rails and many others use the same methods.

What's the best way of doing this?

One of the answers I get to this question is to use Google Cloud Key Management, which looks promising, but I can't figure out how to turn those values into environment variables in App Engine. Is it possible? I've read  Setting Up Authentication for Server to Server Production Applications, but I don't see any indication there about how to turn the secrets into environment variables in App Engine (am I missing it?).

The other alternatives I've seen include hard-coding them in app.yaml or another file that is never committed and lives in my machine, which means I'm the only one who can deploy... I can't even deploy from another machine. This is problematic for me.

Another potential solution I've seen is to delegate the problem to Google Cloud Build, so that it fetches a value/file from CKM and pushes it to App Engine (1, 2). I'm not using GCB and I doubt I will, since it's so basic.

I really wish App Engine had a environment variables page like Heroku does.

答:
[Update] (as of Feb 2020) GCP's Secret Manager is in beta, see:

https://cloud.google.com/secret-manager/docs/overview

For Java-specific implementation, see:
https://cloud.google.com/secret-manager/docs/creating-and-accessing-secrets#secretmanager-access-secret-version-java

Your specific solution would depend how your app is set up, but you should be able to access the secret(s) and create environment variables with the values or otherwise pass them to your app.

You can use GCP IAM to create a service accounts to manage access or add a role like Secret Manager Secret Accessor to an existing member/service (e.g., in this case, I added that permision to the App Engine default service account).

I tried it out with Node.js on GAE standard, and it seems to work well; I didn't do any performance tests but it should be fine, particularly if you primarily need the secrets on app start or as part of a build process.

For local (non-GCP) development/testing, you can create a service account with appropriate secret manager permissions and get the json service key. You then set an environment variable named GOOGLE_APPLICATION_CREDENTIALS to the path of the file, e.g.:

```<code>export GOOGLE_APPLICATION_CREDENTIALS=/path/to/local_service_key.json
</code>```

and the app running in that shell session should pick up the permissions without any additional auth code.
See: https://cloud.google.com/docs/authentication/getting-started
(You would want to exclude the key file from version control.)

Body:
[Update] (as of Feb 2020) GCP's Secret Manager is in beta, see:

https://cloud.google.com/secret-manager/docs/overview

For Java-specific implementation, see:
https://cloud.google.com/secret-manager/docs/creating-and-accessing-secrets#secretmanager-access-secret-version-java

Your specific solution would depend how your app is set up, but you should be able to access the secret(s) and create environment variables with the values or otherwise pass them to your app.

You can use GCP IAM to create a service accounts to manage access or add a role like Secret Manager Secret Accessor to an existing member/service (e.g., in this case, I added that permision to the App Engine default service account).

I tried it out with Node.js on GAE standard, and it seems to work well; I didn't do any performance tests but it should be fine, particularly if you primarily need the secrets on app start or as part of a build process.

For local (non-GCP) development/testing, you can create a service account with appropriate secret manager permissions and get the json service key. You then set an environment variable named GOOGLE_APPLICATION_CREDENTIALS to the path of the file, e.g.:

export GOOGLE_APPLICATION_CREDENTIALS=/path/to/local_service_key.json

and the app running in that shell session should pick up the permissions without any additional auth code.
See: https://cloud.google.com/docs/authentication/getting-started
(You would want to exclude the key file from version control.)


问:
Stopping Docker containers by image name - Ubuntu
On Ubuntu 14.04 (Trusty Tahr) I'm looking for a way to stop a running container and the only information I have is the image name that was used in the Docker run command.

Is there a command to find all the matching running containers that match that image name and stop them?

答:
use: docker container stop $(docker container ls -q --filter ancestor=mongo)

```<code>    (base) :~ user$ docker ps
    CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                      NAMES
    d394144acf3a        mongo               "docker-entrypoint.s…"   15 seconds ago      Up 14 seconds       0.0.0.0:27017->27017/tcp   magical_nobel
    (base) :~ user$ docker container stop $(docker container ls -q --filter ancestor=mongo)
    d394144acf3a
    (base) :~ user$ docker ps
    CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
    (base) :~ user$
</code>```

Body:
use: docker container stop $(docker container ls -q --filter ancestor=mongo)

    (base) :~ user$ docker ps
    CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                      NAMES
    d394144acf3a        mongo               "docker-entrypoint.s…"   15 seconds ago      Up 14 seconds       0.0.0.0:27017->27017/tcp   magical_nobel
    (base) :~ user$ docker container stop $(docker container ls -q --filter ancestor=mongo)
    d394144acf3a
    (base) :~ user$ docker ps
    CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
    (base) :~ user$


问:
How ASP .NET MVC architecture fits into the traditional multi layered architecture
Moving from the traditional way of architecting web applications with a Business Layer, Service Layer, Data Access Layer and a Presentation Layer to the MVC design pattern, I find it difficult to understand how it fits in the old model.

It seems to be that the MVC model itself already has done allot of the separation of concerns that is needed and used to be achieved via a layered architecture. Can someone shed some light on this subject please?

As a reference, below is how I understand it, please share your view on this

MVC Views and Controllers along with View Models -are- Presentation Layer

MVC Models - could be - Data Access Layer or Business Layer or even Service Layer

答:
I see the Asp.Net MVC part only as the view (or presentation) part of the whole application.

I struggled too with the problem how to structure the app in a proper way.

Following the Onion Architecture I heard about here (and especially the image found here), my solution looks this way:

Project.Core

Business logic/services implementations, entities, interfaces that must be implemented by the other projects (i.e. "IRepository", "IAuthenticationService",...)

Project.Data

DB connection - in my case NHibernate repositories and entity-mappings go here.
Implements data-interfaces of Project.Core

Project.UI.Web

The Asp.Net MVC ("presentation") project - it wires the whole app together.

Has implementations for Interfaces in Project.Core and wires them (and those from Project.Data) up with some DI framework like Castle Windsor.

Project.UI.Web follows the following conventions:

its models are only(!) viewmodels

the views consume their own viewmodel (one-view-one-viewmodel)

the controllers just need to validate the input, transforms it into domain objects (as the business logic knows exacly nothing about viewmodels) and delegate the real work (business logic) to the business services.

Summary:

If you follow this model it's helpful to focus on Project.Core: that is the real application. It doesn't worry about the real persistence of data nor cares about how does it get presented. It's just about "how-to-do-it". But it's laying out the rules and contracts (interfaces) the other projects must provide implementations for.

I hope this helps you with how to layout an Asp.Net MVC application!

Lg

warappa


问:
retrieve points of interests (attractions/tourist places) of a place/country using google places api
I want to retrieve points of interests of a place/country through google places api say 'points of interests in london'. I want the results to be same as  I google search it like [here][1. I've used something like this

'https://maps.googleapis.com/maps/api/place/radarsearch/json?location='+str(lat)+','+str(long)+'&radius=500&type=tourist&rankby=prominence&key=API_KEY')

where lat,long are respective latitude,longitude of that place/country.

But the resulting json file does not retrieve points of interests of that place rather it just outputs nearby places.

i also tried this

'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location='+str(lat)+','+str(long)+'&radius=500&type=tourist&&rankby=prominence&key=API_KEY'

which ended up in same results

is there any option to do it without using radius parameter

please do help me

答:
I worked on a project that made extensive use of this functionality. In the end, the best way to get attractions in a city was to use a query like:

https://maps.googleapis.com/maps/api/place/autocomplete/json?input=your-query-here&types=establishment&location=37.76999,-122.44696&radius=500&key=YOUR_API_KEY

If you want points of interest that aren't businesses, remove the types=establishment arg.


答:
Try this

1) Call a function when input value changes use onchange or blur any one event

2) set div id equal to hotapp3

Method 1

```<code>    <head>
    <script>
    function checkValue(){

      let value = document.getElementById('ref3').value;
        if (value == 2) {
          document.getElementById('hotapp3').style.visibility = 'visible';
        } else {
          document.getElementById('hotapp3').style.visibility = 'hidden';
        }
    }
    </script>
    </head>

    <body>
        <form name="myform">
            <div><input type="text" id="ref3" value="" onchange="checkValue()"></div>
            <div id="hotapp3" style="visibility:hidden">
                <label>Show me</label>
            </div>
        </form>
    </body>

    </html>
</code>```

Method 2

You can also do few changes pass input text value directly to function at the time of calling like this

onchange="test(this.value)

```<code><input type="text" id="ref3" value="" onchange="test(this.value)">
</code>```

and can use it directly in function

```<code>function test(value){
        if (value == 2) {
          document.getElementById('hotapp3').style.visibility = 'visible';
        } else {
          document.getElementById('hotapp3').style.visibility = 'hidden';
        }
 }
</code>```

As commented by you if you want to do same for default value than call this function on page relode

window.onload = function() {
  checkValue();
};

Title: Hide and show a div using input value using JavaScript

Body:
Someone help me with the below code I want to hide and show a div using input value using JavaScript.

        <form name="myform">

<input type="text" id="ref3" value="">

                Show me

        </form>

Body:
Try this

1) Call a function when input value changes use onchange or blur any one event

2) set div id equal to hotapp3

Method 1

    <head>
    <script>
    function checkValue(){

      let value = document.getElementById('ref3').value;
        if (value == 2) {
          document.getElementById('hotapp3').style.visibility = 'visible';
        } else {
          document.getElementById('hotapp3').style.visibility = 'hidden';
        }
    }
    </script>
    </head>

    <body>
        <form name="myform">
            <div><input type="text" id="ref3" value="" onchange="checkValue()"></div>
            <div id="hotapp3" style="visibility:hidden">
                <label>Show me</label>
            </div>
        </form>
    </body>

    </html>

Method 2

You can also do few changes pass input text value directly to function at the time of calling like this

onchange="test(this.value)

<input type="text" id="ref3" value="" onchange="test(this.value)">

and can use it directly in function

function test(value){
        if (value == 2) {
          document.getElementById('hotapp3').style.visibility = 'visible';
        } else {
          document.getElementById('hotapp3').style.visibility = 'hidden';
        }
 }

As commented by you if you want to do same for default value than call this function on page relode

window.onload = function() {
  checkValue();
};


问:
Renaming labels of a factor in R
I have census data of Male and Female populations organizaed by age group:

```<code>library(tidyverse)

url <- "https://www2.census.gov/programs-surveys/popest/datasets/2010-2018/counties/asrh/cc-est2018-alldata-54.csv"

if (!file.exists("./datafiles/cc-est2018-alldata-54.csv"))
  download.file(url, destfile = "./datafiles/cc-est2018-alldata-54.csv", mode = "wb")

popSample <- read.csv("./datafiles/cc-est2018-alldata-54.csv") %>%
  filter(AGEGRP != 0 & YEAR == 1) %>%
  select("STNAME", "CTYNAME", "AGEGRP", "TOT_POP", "TOT_MALE", "TOT_FEMALE")

popSample$AGEGRP <- as.factor(popSample$AGEGRP)
</code>```

I then plot the Male and Female population relationships, faceted by age group (1-18, which is currently treated as a int

```<code>g <- ggplot(popSample, aes(x=TOT_MALE, y=TOT_FEMALE)) +
  geom_point(alpha = 0.5, colour="darkblue") +
  scale_x_log10() +
  scale_y_log10() +
  facet_wrap(~AGEGRP) +
  stat_smooth(method = "lm", col = "darkred", size=.75) +
  labs(title = "F vs. M Population across all Age Groups", x = "Total Male (log10)", y = "Total Female (log10)") +
  theme_light()

g
</code>```

Which results in this plot: https://share.getcloudapp.com/v1ur6O4e

The problem: I am trying to convert the column AGEGRP from ‘int’ to ‘factor’, and change the factors labels from “1”, “2”, “3”, … “18” to "AgeGroup1", "AgeGroup2", "AgeGroup3", … "AgeGroup18"

When I try this code, my AGEGRP column's observation values are all replaced with NAs:popSample$AGEGRP <- factor(popSample$AGEGRP, levels = c("0 to 4", "5 to 9", "10 to 14", "15 to 19", "20 to 24", "25 to 29", "30 to 34", "35 to 39", "40 to 44", "45 to 49", "50 to 54", "55 to 59", "60 to 64", "65 to 69", "70 to 74", "75 to 79", "80 to 84", "85+"))

https://share.getcloudapp.com/qGuo1O4y

Thank you for your help,

Title: Renaming labels of a factor in R

Body:
I have census data of Male and Female populations organizaed by age group:

library(tidyverse)

url <- "https://www2.census.gov/programs-surveys/popest/datasets/2010-2018/counties/asrh/cc-est2018-alldata-54.csv"

if (!file.exists("./datafiles/cc-est2018-alldata-54.csv"))
  download.file(url, destfile = "./datafiles/cc-est2018-alldata-54.csv", mode = "wb")

popSample <- read.csv("./datafiles/cc-est2018-alldata-54.csv") %>%
  filter(AGEGRP != 0 & YEAR == 1) %>%
  select("STNAME", "CTYNAME", "AGEGRP", "TOT_POP", "TOT_MALE", "TOT_FEMALE")

popSample$AGEGRP <- as.factor(popSample$AGEGRP)

I then plot the Male and Female population relationships, faceted by age group (1-18, which is currently treated as a int

g <- ggplot(popSample, aes(x=TOT_MALE, y=TOT_FEMALE)) +
  geom_point(alpha = 0.5, colour="darkblue") +
  scale_x_log10() +
  scale_y_log10() +
  facet_wrap(~AGEGRP) +
  stat_smooth(method = "lm", col = "darkred", size=.75) +
  labs(title = "F vs. M Population across all Age Groups", x = "Total Male (log10)", y = "Total Female (log10)") +
  theme_light()

g

Which results in this plot: https://share.getcloudapp.com/v1ur6O4e

The problem: I am trying to convert the column AGEGRP from ‘int’ to ‘factor’, and change the factors labels from “1”, “2”, “3”, … “18” to "AgeGroup1", "AgeGroup2", "AgeGroup3", … "AgeGroup18"

When I try this code, my AGEGRP column's observation values are all replaced with NAs:popSample$AGEGRP <- factor(popSample$AGEGRP, levels = c("0 to 4", "5 to 9", "10 to 14", "15 to 19", "20 to 24", "25 to 29", "30 to 34", "35 to 39", "40 to 44", "45 to 49", "50 to 54", "55 to 59", "60 to 64", "65 to 69", "70 to 74", "75 to 79", "80 to 84", "85+"))

https://share.getcloudapp.com/qGuo1O4y

Thank you for your help,

Body:
popSample$AGEGRP <- factor( popSample$AGEGRP, levels = c("0 to 4", "5 to 9", "10 to 14", "15 to 19", "20 to 24", "25 to 29", "30 to 34", "35 to 39", "40 to 44", "45 to 49", "50 to 54", "55 to 59", "60 to 64", "65 to 69", "70 to 74", "75 to 79", "80 to 84", "85+"))

Need to add all levels though.

Alternatively

levels(popSample$AGEGRP) <- c("0 to 4", "5 to 9", "10 to 14", "15 to 19", "20 to 24", "25 to 29", "30 to 34", "35 to 39", "40 to 44", "45 to 49", "50 to 54", "55 to 59", "60 to 64", "65 to 69", "70 to 74", "75 to 79", "80 to 84", "85+")

should work as well.


问:
Thunderbird Webextensions Plug-In get a messageList
I already tried different things to get a list of mails from my inbox folder in Thunderbird.

let page = await browser.messages.list(folder);

But how to declare folder?

MailFolder is explained in Thunderbird Docs, but how do i get

```<code>accountId (string) The account this folder belongs to.
path (string) Path to this folder in the account. Although paths look predictable, never guess a folder’s path, as there are a number of reasons why it may not be what you think it is.
[name] (string) The human-friendly name of this folder.
[type] (string) The type of folder, for several common types.
</code>```

?

Another way i found is to use query(queryInfo). Documentation explains:

Gets all messages that have the specified properties, or all messages if no properties are specified.

But when I pass no argument, i get an exception.

Can someone provide me a piece of code which just assigns my inbox folder to a messageList object?

答:
The author of this answer had exactly the same problem.
He wanted to filter out spam messages with a certain content within the body of the emails.
Therefore he decided to test his regexps on emails which were already in the trash folder.
And he read the exact same documentation as you did and ended up in not knowing how to pass the "folder" object corretly to the .messages.list(folder) method.

The first "aha" experience was the following reading:
"WebExtension APIs are asynchronous, [... and] return a Promise object [...]".

Trying to read and deeply understand the following excellent explanation abot using Promise objects (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises) helped to solve the authors problem with the following first [and mostly quick and dirty] code.

Supposed you just know the "name" of the account, you want to examine specific folders of, you can try the following code, which did it for the author of this answer:

```<code>function accountsList_successCallback( arrayOfMailAccount ) {
    let accountId = false;
    for (i = 0; i < arrayOfMailAccount.length; i++) {
    if ( arrayOfMailAccount[i][ "name" ] == "firstname.lastname@email.com" ) {
        accountId  = arrayOfMailAccount[i][ "id" ];
        break;
        }
    }
    console.log('Last line of function accountsList_successCallback() before return of accountId: ' + accountId );
    return accountId;
}

function mailAccount_successCallback( mailAccount ) {
    console.log('Last line of function mailAccount_successCallback(), returning mailAccount\'s MailFolder array');
    return mailAccount[ "folders" ];
}
function returnWantedMailFolder( Folders ) {
    let mailFolder = false;
    for (j = 0; j < Folders.length; j++) {
    if ( Folders[j][ "type" ] == "trash" ) { // use "inbox" here instead of "trash"
        mailFolder = Folders[j];
        break;
        }
    }
    console.log('Last line of function returnWantedMailFolder()');
    return mailFolder;
}
function messagesList_successCallback( messageList ) {
    console.log( "messageListId: " + messageList[ "id" ] );
    console.log( "Number of Emails in this Page: " + messageList[ "messages" ].length );
    /*
     * This is where you can place your messages examining
     * rotines...
     *
     * And don't forget to loop through the next pages.
     * You just got the first of maybe several pages.
     *
     */
    console.log('Last line of function messagesList_successCallback()');
}

function accountsList_failureCallback(error) {
  console.error( "Fehler (accountsList_failureCallback) : " + error);
}
function accountsGet_failureCallback(error) {
  console.error( "Fehler (accountsGet_failureCallback) : " + error);
}
function mailAccount_failureCallback(error) {
  console.error( "Fehler (mailAccount_failureCallback) : " + error);
}
function returnWantedMailFolder_failureCallback(error) {
  console.error( "Fehler (returnWantedMailFolder_failureCallback) : " + error);
}
function messagesList_failureCallback(error) {
  console.error( "Fehler (messagesList_failureCallback) : " + error);
}

browser.accounts.list()
    .then( accountsList_successCallback,
       accountsList_failureCallback)  // after .list() is fulfilled...
                                      // accountsList_successCallback is called, which
                                      // in this example returns the accountId string...
    .then( accountId => browser.accounts.get( accountId ),
       accountsGet_failureCallback)   // returns a MailAccount Promise, passed to ...
    .then( mailAccount_successCallback,
       mailAccount_failureCallback)   // returns an array of MailFolder...
    .then( arrayMailFolders => returnWantedMailFolder( arrayMailFolders ),
       returnWantedMailFolder_failureCallback)
    .then( mailFolder => browser.messages.list( mailFolder ), // <-- this was the problem, right?
       messagesList_failureCallback)  // returns a page Promise, passed to ...
    .then( messagesList_successCallback,
           messagesList_failureCallback)
;

</code>```

This code can FOR SURE and will be further optimized. Some of the "failureCallback" routines will probably never been called. And with a single .catch( failureCallback ) at the end of the .then() chain you can eliminate all other failureCallback functions.

This many failureCallback functions were necessary til the author of this answer checked, what is really going on within this "new" kind of thinking.

The author of this answer wishes you good luck. richard.

Body:
I already tried different things to get a list of mails from my inbox folder in Thunderbird.

let page = await browser.messages.list(folder);

But how to declare folder?

MailFolder is explained in Thunderbird Docs, but how do i get

accountId (string) The account this folder belongs to.
path (string) Path to this folder in the account. Although paths look predictable, never guess a folder’s path, as there are a number of reasons why it may not be what you think it is.
[name] (string) The human-friendly name of this folder.
[type] (string) The type of folder, for several common types.

?

Another way i found is to use query(queryInfo). Documentation explains:

Gets all messages that have the specified properties, or all messages if no properties are specified.

But when I pass no argument, i get an exception.

Can someone provide me a piece of code which just assigns my inbox folder to a messageList object?

Body:
The author of this answer had exactly the same problem.
He wanted to filter out spam messages with a certain content within the body of the emails.
Therefore he decided to test his regexps on emails which were already in the trash folder.
And he read the exact same documentation as you did and ended up in not knowing how to pass the "folder" object corretly to the .messages.list(folder) method.

The first "aha" experience was the following reading:
"WebExtension APIs are asynchronous, [... and] return a Promise object [...]".

Trying to read and deeply understand the following excellent explanation abot using Promise objects (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises) helped to solve the authors problem with the following first [and mostly quick and dirty] code.

Supposed you just know the "name" of the account, you want to examine specific folders of, you can try the following code, which did it for the author of this answer:

function accountsList_successCallback( arrayOfMailAccount ) {
    let accountId = false;
    for (i = 0; i < arrayOfMailAccount.length; i++) {
    if ( arrayOfMailAccount[i][ "name" ] == "firstname.lastname@email.com" ) {
        accountId  = arrayOfMailAccount[i][ "id" ];
        break;
        }
    }
    console.log('Last line of function accountsList_successCallback() before return of accountId: ' + accountId );
    return accountId;
}

function mailAccount_successCallback( mailAccount ) {
    console.log('Last line of function mailAccount_successCallback(), returning mailAccount\'s MailFolder array');
    return mailAccount[ "folders" ];
}
function returnWantedMailFolder( Folders ) {
    let mailFolder = false;
    for (j = 0; j < Folders.length; j++) {
    if ( Folders[j][ "type" ] == "trash" ) { // use "inbox" here instead of "trash"
        mailFolder = Folders[j];
        break;
        }
    }
    console.log('Last line of function returnWantedMailFolder()');
    return mailFolder;
}
function messagesList_successCallback( messageList ) {
    console.log( "messageListId: " + messageList[ "id" ] );
    console.log( "Number of Emails in this Page: " + messageList[ "messages" ].length );
    /*
     * This is where you can place your messages examining
     * rotines...
     *
     * And don't forget to loop through the next pages.
     * You just got the first of maybe several pages.
     *
     */
    console.log('Last line of function messagesList_successCallback()');
}

function accountsList_failureCallback(error) {
  console.error( "Fehler (accountsList_failureCallback) : " + error);
}
function accountsGet_failureCallback(error) {
  console.error( "Fehler (accountsGet_failureCallback) : " + error);
}
function mailAccount_failureCallback(error) {
  console.error( "Fehler (mailAccount_failureCallback) : " + error);
}
function returnWantedMailFolder_failureCallback(error) {
  console.error( "Fehler (returnWantedMailFolder_failureCallback) : " + error);
}
function messagesList_failureCallback(error) {
  console.error( "Fehler (messagesList_failureCallback) : " + error);
}

browser.accounts.list()
    .then( accountsList_successCallback,
       accountsList_failureCallback)  // after .list() is fulfilled...
                                      // accountsList_successCallback is called, which
                                      // in this example returns the accountId string...
    .then( accountId => browser.accounts.get( accountId ),
       accountsGet_failureCallback)   // returns a MailAccount Promise, passed to ...
    .then( mailAccount_successCallback,
       mailAccount_failureCallback)   // returns an array of MailFolder...
    .then( arrayMailFolders => returnWantedMailFolder( arrayMailFolders ),
       returnWantedMailFolder_failureCallback)
    .then( mailFolder => browser.messages.list( mailFolder ), // <-- this was the problem, right?
       messagesList_failureCallback)  // returns a page Promise, passed to ...
    .then( messagesList_successCallback,
           messagesList_failureCallback)
;

This code can FOR SURE and will be further optimized. Some of the "failureCallback" routines will probably never been called. And with a single .catch( failureCallback ) at the end of the .then() chain you can eliminate all other failureCallback functions.

This many failureCallback functions were necessary til the author of this answer checked, what is really going on within this "new" kind of thinking.

The author of this answer wishes you good luck. richard.


问:
Why is Spring Boot @Async dropping items in my List argument?
I am experiencing some sort of thread issue with the @Async method annotation where one argument contains a List of enum and is dropping items. The list is very small, 2 items. The dropping of items is not immediate, but sometimes takes hours or days to appear.

This is the general flow of our program:

A Controller generates the said List in its @RequestMapping method, passes the list to a Service class, which makes a call to a database for batching and triggers an event for each item from the database, passing the list. This list eventually gets passed into an @Async method which then drops either the first item or both items.

```<code>Controller.methodA()
  -> Creates list with two items in it
  -> Calls void Service.methodX(list)
    -> Load batch from database
    -> Iterate over batch
      -> Print items from list --- list in tact
      -> Calls void AsyncService.asyncMethod(list)
        -> Print items from list --- eventually drops items here always the first item, sometimes both.
</code>```

Code configuration and bare-bones sample:

We configured it to have 2 threads:

@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {

    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setMaxPoolSize(5);  // Never actually creates 5 threads
        threadPoolTaskExecutor.setCorePoolSize(2); // Only 2 threads are ever created
        threadPoolTaskExecutor.initialize();
        return threadPoolTaskExecutor;
    }
}
```

<p>This is a local replica to try to trigger the core issue, but no luck:</p>

<pre class="lang-java prettyprint-override"><code>@RestController
public class ThreadingController {

    private final ThreadingService threadingService;

    public ThreadingController(ThreadingService threadingService) {
        this.threadingService = threadingService;
    }

    @GetMapping("/test")
    public void testThreads() {
        List<SomeEnum> list = new ArrayList<>();
        list.add(SomeEnum.FIRST_ENUM);
        list.add(SomeEnum.SECOND_ENUM);

        for (int i = 0; i < 1000; i++) {
            this.threadingService.workSomeThreads(i, list);
        }
    }
}
</code>```

public enum SomeEnum {
    FIRST_ENUM("FIRST_ENUM"),
    SECOND_ENUM("SECOND_ENUM");

    @Getter
    private String name;

    SomeEnum(String name) {
        this.name = name;
    }

}
```

<pre class="lang-java prettyprint-override"><code>@Slf4j
@Service
public class ThreadingService {

    @Async
    public void workSomeThreads(int i, List<SomeEnum> list) {
        try {
            Thread.sleep(100L);  // Add some delay to slow things down to trigger GC or other tests during processing
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("Count {} ; Here are the list items: {}", i, list.toString());
        assert(list.size() == 2);
    }
}
</code>```

If we look through this, I have one controller simulating both the Controller and Service mentioned earlier. It spins through a batch of data, sending the same list over and over. There's an aync method in another class to test that the list is the same. I was not able to replicate the issue locally, but this is the core problem.

To my knowledge, Java is pass-by-reference and every variable passed into a method gets its own pointer in the stack to that reference in memory, but don't think it would cause us to run out of memory. We are running in PCF and don't see any memory spikes or anything during this time. Memory is constant around 50%. I also tried using a CopyOnWriteArrayList (thread safe) instead of ArrayList and still the problem exists.

Questions:

Any idea why the @Async method would drop items in the method argument? The list is never modified after construction, so why would items disappear? Why would the first item always disappear? Why not the second item? Why would both disappear?

Edit: So this question had little to do with @Async in the end. I found deeply nested code that removed items from the list, causing items to go missing.

答:
What you said is correct, Java is indeed pass-by-reference. The change in your list must be definitely due to some other code that is modifying this list while the threads are executing. There is no other way the object would change its values.
You must investigate the code in the below section to identify if there is something that is modifying the list.

```<code>    -> Print items from list --- eventually drops items here always the first item, sometimes both.
    -> code following this might be changing the list.
</code>```

As the AsyncService would execute its code asynchronously and in the mean time, some other code modifies the list.

You may as well make the method params to be final.

Body:
I am experiencing some sort of thread issue with the @Async method annotation where one argument contains a List of enum and is dropping items. The list is very small, 2 items. The dropping of items is not immediate, but sometimes takes hours or days to appear.

This is the general flow of our program:

A Controller generates the said List in its @RequestMapping method, passes the list to a Service class, which makes a call to a database for batching and triggers an event for each item from the database, passing the list. This list eventually gets passed into an @Async method which then drops either the first item or both items.

Controller.methodA()
  -> Creates list with two items in it
  -> Calls void Service.methodX(list)
    -> Load batch from database
    -> Iterate over batch
      -> Print items from list --- list in tact
      -> Calls void AsyncService.asyncMethod(list)
        -> Print items from list --- eventually drops items here always the first item, sometimes both.

Code configuration and bare-bones sample:

We configured it to have 2 threads:

@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {

    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setMaxPoolSize(5);  // Never actually creates 5 threads
        threadPoolTaskExecutor.setCorePoolSize(2); // Only 2 threads are ever created
        threadPoolTaskExecutor.initialize();
        return threadPoolTaskExecutor;
    }
}

This is a local replica to try to trigger the core issue, but no luck:

@RestController
public class ThreadingController {

    private final ThreadingService threadingService;

    public ThreadingController(ThreadingService threadingService) {
        this.threadingService = threadingService;
    }

    @GetMapping("/test")
    public void testThreads() {
        List<SomeEnum> list = new ArrayList<>();
        list.add(SomeEnum.FIRST_ENUM);
        list.add(SomeEnum.SECOND_ENUM);

        for (int i = 0; i < 1000; i++) {
            this.threadingService.workSomeThreads(i, list);
        }
    }
}

public enum SomeEnum {
    FIRST_ENUM("FIRST_ENUM"),
    SECOND_ENUM("SECOND_ENUM");

    @Getter
    private String name;

    SomeEnum(String name) {
        this.name = name;
    }

}

@Slf4j
@Service
public class ThreadingService {

    @Async
    public void workSomeThreads(int i, List<SomeEnum> list) {
        try {
            Thread.sleep(100L);  // Add some delay to slow things down to trigger GC or other tests during processing
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("Count {} ; Here are the list items: {}", i, list.toString());
        assert(list.size() == 2);
    }
}

If we look through this, I have one controller simulating both the Controller and Service mentioned earlier. It spins through a batch of data, sending the same list over and over. There's an aync method in another class to test that the list is the same. I was not able to replicate the issue locally, but this is the core problem.

To my knowledge, Java is pass-by-reference and every variable passed into a method gets its own pointer in the stack to that reference in memory, but don't think it would cause us to run out of memory. We are running in PCF and don't see any memory spikes or anything during this time. Memory is constant around 50%. I also tried using a CopyOnWriteArrayList (thread safe) instead of ArrayList and still the problem exists.

Questions:

Any idea why the @Async method would drop items in the method argument? The list is never modified after construction, so why would items disappear? Why would the first item always disappear? Why not the second item? Why would both disappear?

Edit: So this question had little to do with @Async in the end. I found deeply nested code that removed items from the list, causing items to go missing.

Body:
What you said is correct, Java is indeed pass-by-reference. The change in your list must be definitely due to some other code that is modifying this list while the threads are executing. There is no other way the object would change its values.
You must investigate the code in the below section to identify if there is something that is modifying the list.

    -> Print items from list --- eventually drops items here always the first item, sometimes both.
    -> code following this might be changing the list.

As the AsyncService would execute its code asynchronously and in the mean time, some other code modifies the list.

You may as well make the method params to be final.


问:
write an object to a file using pointer in c++
I have this object ob, which I am writing to the file using the pointer to that object. But it does not seem to be working.

```<code>class A
{
public:
    int Arr[10];
    A();
};
A::A()
{
    for(int i=0;i<10;i++)
        Arr[i] = 0;
}
A obj;
int main(int argc, char *argv[])
{
    A *ptr = &obj, temp;
    obj.Arr[0] = 1;

    fstream fp("temp", ios::in|ios::binary|ios::out);
    fp.write((char *)ptr, sizeof(*ptr));
    fp.close();

    fp.open("temp", ios::in|ios::binary|ios::out);
    fp.read((char *)&temp, sizeof(temp));
    for(int i=0;i<10;i++)
        cout<<temp.Arr[i]<<" ";
    fp.close();
    return 0;
}
</code>```

Output :

```<code>0 0 0 0 0 0 0 0 0 0
</code>```

Expected output :

```<code>1 0 0 0 0 0 0 0 0 0
</code>```

How do I write the object directly using the pointer. Also is there any way to directly read the contents in the pointer itself?

答:
You open the file for reading (std::ios::in) both times. When you open the file for reading, it must exist or else opening it will fail, which means that your first open doesn't succeed, so the file isn't created.

Your second open will also fail because of the missing file.

Therefore, always check that opening a file actually succeeds and use the proper openmode:

```<code>#include <fstream>
#include <iostream>
class A {
public:
    int Arr[10]{};

    void print() const {
        for(int val : Arr) std::cout << val << ' ';
        std::cout << '\n';
    }
};

int main() {
    A obj;
    A temp;
    obj.Arr[0] = 1;

    // open file for writing and check that opening succeeded
    if(std::ofstream fp("temp", std::ios::binary); fp) {
        obj.print();
        fp.write(reinterpret_cast<const char*>(&obj), sizeof(obj));
    }

    // open the file for reading and check that opening succeeded
    if(std::ifstream fp("temp", std::ios::binary); fp) {
        fp.read(reinterpret_cast<char*>(&temp), sizeof(temp));
        temp.print();
    }
}
</code>```

Body:
I have this object ob, which I am writing to the file using the pointer to that object. But it does not seem to be working.

class A
{
public:
    int Arr[10];
    A();
};
A::A()
{
    for(int i=0;i<10;i++)
        Arr[i] = 0;
}
A obj;
int main(int argc, char *argv[])
{
    A *ptr = &obj, temp;
    obj.Arr[0] = 1;

    fstream fp("temp", ios::in|ios::binary|ios::out);
    fp.write((char *)ptr, sizeof(*ptr));
    fp.close();

    fp.open("temp", ios::in|ios::binary|ios::out);
    fp.read((char *)&temp, sizeof(temp));
    for(int i=0;i<10;i++)
        cout<<temp.Arr[i]<<" ";
    fp.close();
    return 0;
}

Output :

0 0 0 0 0 0 0 0 0 0

Expected output :

1 0 0 0 0 0 0 0 0 0

How do I write the object directly using the pointer. Also is there any way to directly read the contents in the pointer itself?

Body:
You open the file for reading (std::ios::in) both times. When you open the file for reading, it must exist or else opening it will fail, which means that your first open doesn't succeed, so the file isn't created.

Your second open will also fail because of the missing file.

Therefore, always check that opening a file actually succeeds and use the proper openmode:

#include <fstream>
#include <iostream>
class A {
public:
    int Arr[10]{};

    void print() const {
        for(int val : Arr) std::cout << val << ' ';
        std::cout << '\n';
    }
};

int main() {
    A obj;
    A temp;
    obj.Arr[0] = 1;

    // open file for writing and check that opening succeeded
    if(std::ofstream fp("temp", std::ios::binary); fp) {
        obj.print();
        fp.write(reinterpret_cast<const char*>(&obj), sizeof(obj));
    }

    // open the file for reading and check that opening succeeded
    if(std::ifstream fp("temp", std::ios::binary); fp) {
        fp.read(reinterpret_cast<char*>(&temp), sizeof(temp));
        temp.print();
    }
}


问:
Ray intersection, Ray anything acctually, OpenGL-ES?
Is this possible to do with OpenGL-ES?

Im trying to make a quite simple 3D game in android with the use of OpenGL-ES.
Now im stuck on the part where i think that using a ray to get the coordinates of a point on the surface of a sphere depending on 2D touch coordinates, would be the best way.

Im fairly new to 3D programming and openGL overall but all the tutorials iv'e found on the internet on how to achive this is by using methods OpenGL-ES don't support.

I guess using the inverse of my perspective projection transform is how it's supposed to be, but i hav'e now clue how to get that.

(Im setting up my perspective to 45 degrees with GLU.gluPerspective)

答:
I have recently come across this as well as part of my bachelor-thesis. I haven't found a direct way to do this with opengl.
What I have done is I have taken the x and y coordinates of the touch point. I then created two 3D points, one with the z-value 1 and one with z=-1. This gives you two different coordinates. And then you just take the inverse of your transformation matrix just as you guessed. If you manage the matrix yourself that shouldn't be too hard. If you let OpenGL manage the matrix you should be able to get the inversed matrix by calling gluUnproject (http://www.opengl.org/sdk/docs/man/xhtml/gluUnProject.xml).
This will give you two points in object coordinates, now you have your ray, and now you can intersect this ray with all the objects you want to. (Here is an extensive list of intersection algorithms between different objects with code examples: http://www.realtimerendering.com/intersections.html)

Just in case you're interested: As part of my bachelor thesis I am creating a 3D Rendering Engine that should take a lot of this work away from the developer. It's still work in progress, but if you're interested, you can take a look: https://github.com/Chnoch/Bachelor-Thesis
PM me if you'd like more information


问:
How to create a workflow in 2013 to send multiple email in a month
I want to create a Designer Workflow in 2013 which will trigger the email automatically for 5 times in a month. List is same but the calculation and logic is different for every email. First time, i can initiate the process to send the email (ex-creating a button to initiate) then email will be sent after 2 days then after 4 days resp

For this, i used 2 things-

HTTP Web Service call- but it is giving me unexpected error. Even I am not able to fetch the list records.

created a JavaScript with set Timeout function. But the problem is How and where to deploy and schedule this script so it will run till the last email and trigger it automatically after some days based on the logic.

can anyone help me please?
or if there are any other solution, please share.

答:
You cannot put JavaScript into a workflow.  SharePoint Designer 2013 Workflows have two built-in actions that will allow you to make it wait for a specified time.

Pause for Duration - allows you to specify a length of time to wait before executing the next step.

Pause until Date - allows you to specify a specify date/time in the future that the workflow should pause until that that date/time is reached.


问:
Download artifact contents from another pipeline build
I have two azure devops pipelines as follows:

the first one creates an artifact under the name 'AncientArtifact-1.2.0.$(Build.BuildId)'.

the second one is trying to use this artifact using the Download Build Artifacts task configured as follows:

This creates a folder named 'AncientArtifact-1.2.0.12345' (first pipeline most recent BuildId=12345) inside a $(CustomDestinationFolder) in the second pipeline build.

I want to rename the above folder to something like 'ancient' and move it to another directory within the second pipeline build to be included in the second pipeline artifact.

I have tried using the copy files task but the problem is I don't know the name of the downloaded artifact folder thus I can only specify its parent $(CustomDestinationFolder) as source folder and so my destination folder will look something like $(destinationFolder)\AncientArtifact-1.2.0.12345*.
Using the flattenFolders option will flatten everything and that is not what I want.

Some approaches come to mind:

Remove the $(Build.BuildId) from the artifact name. This way I know the exact name that the downloaded artifact will have. The issue is that I would like to keep it.

A custom script in the second pipeline that would list the folders inside the $(CustomDestinationFolder), get the name of the artifact folder rename it a hardcoded 'ancient' name. It feels quite hackish.

Is there a better way to handle this?

答:
You might be able to do go down a route with the copy file task and wildcards to get what you want.

But if you ultimately want to rename the artifact folder for inclusion in the second pipeline, I would just go ahead rename the artifact folder after you download it.

I would not call it hackish, if it solves the problem simply and is easy to understand.

```<code>- task: DownloadBuildArtifacts@0
  inputs:
    buildType: 'specific'
    project: 'your-project'
    pipeline: 'your-pipeline'
    buildVersionToDownload: 'latest'
    downloadType: 'specific'
    downloadPath: '$(System.ArtifactsDirectory)\customLocation'

- task: PowerShell@2
  inputs:
    targetType: 'inline'
    script: Get-ChildItem $(System.ArtifactsDirectory)\customLocation | Rename-Item -NewName 'ancient'
</code>```

Body:
You might be able to do go down a route with the copy file task and wildcards to get what you want.

But if you ultimately want to rename the artifact folder for inclusion in the second pipeline, I would just go ahead rename the artifact folder after you download it.

I would not call it hackish, if it solves the problem simply and is easy to understand.

- task: DownloadBuildArtifacts@0
  inputs:
    buildType: 'specific'
    project: 'your-project'
    pipeline: 'your-pipeline'
    buildVersionToDownload: 'latest'
    downloadType: 'specific'
    downloadPath: '$(System.ArtifactsDirectory)\customLocation'

- task: PowerShell@2
  inputs:
    targetType: 'inline'
    script: Get-ChildItem $(System.ArtifactsDirectory)\customLocation | Rename-Item -NewName 'ancient'


问:
jQuery html() function with javascript
It appears that the .html function doesn't return javascript.  Is there a function that returns both javascript and html?

EDIT:

Example:

Main Page

```<code>$.ajax({
  url: 'ajaxpage.php',
  type: 'post',
  data: postvars,
  cache: false,
  dataType: 'html',
  success: function (html) {
    $('#content').html($(html).find('#content').html());
  }
});
</code>```

ajaxpage.php

```<code><html>
<body>
<div id="content">
   //SOME HTML
   <script type="text/javascript">
      //SOME JAVASCRIPT
   </script>
</div>
</body>
</html>
</code>```

$(html).find('#content').html() returns

```<code>   //SOME HTML
</code>```

while I want

```<code>   //SOME HTML
   <script type="text/javascript">
      //SOME JAVASCRIPT
   </script>
</code>```

答: Try using .load() instead of .html()

Title: jQuery html() function with javascript

Body:
It appears that the .html function doesn't return javascript.  Is there a function that returns both javascript and html?

EDIT:

Example:

Main Page

$.ajax({
  url: 'ajaxpage.php',
  type: 'post',
  data: postvars,
  cache: false,
  dataType: 'html',
  success: function (html) {
    $('#content').html($(html).find('#content').html());
  }
});

ajaxpage.php

   //SOME HTML

$(html).find('#content').html() returns

   //SOME HTML

while I want

   //SOME HTML

Body: Try using .load() instead of .html()


问:
Powershell: how to split, do math and format
I am looking for a 1-liner that looks something like this:

(gitversion | ConvertFrom-Json).SemVer.split('.') | [string]::Format("{0}.{1}.{2}",$_[0],$_[1] + 1,$_[2]) | git tag $_
```

So, right now I have 0.1.0 and I want a 1 liner that will map it to:
0.2.0

I am sure a guru in PS can make fast work of this

答:
If I understand this right, you want to add 1 to the 2nd number.  I wish I could do $a.minor += 1, but the [version] type is read-only.

```<code>$a = '0.1.0'
$nums = $a.split('.')
'{0}.{1}.{2}' -f $nums[0], ([int]$nums[1] + 1), $nums[2]

0.2.0
</code>```

Or

```<code>$a = '0.1.0'
$nums = $a -split '\.'
([int]$nums[1])++
$nums -join '.'

0.2.0
</code>```

Or

```<code>$a = '0.1.0'
$nums = $a.split('.')
([int]$nums[1])++
'{0}.{1}.{2}' -f $nums

0.2.0
</code>```

I was also trying the ps 6 version of -replace with the scriptblock, but it became challenging.

See also Increment version in a text file

Here's another one, but it needs powershell 6 for the -replace with a scriptblock.  I'm using regex with positive lookahead and positive lookbehind, so I'm only replacing the number and not the 2 dots on each side.  This would only work with 3 numbers, unless you wanted to increment 2 middle numbers by 1, lol.  It certainly qualifies as a one-liner.

```<code>'0.11.0' -replace '(?<=\.)\d+(?=\.)', { [int]"$_" + 1 }

0.12.0

'0.11.11.0' -replace '(?<=\.)\d+(?=\.)', { [int]"$_" + 1 }

0.12.12.0
</code>```

Body:
I am looking for a 1-liner that looks something like this:

(gitversion | ConvertFrom-Json).SemVer.split('.') | [string]::Format("{0}.{1}.{2}",$_[0],$_[1] + 1,$_[2]) | git tag $_

So, right now I have 0.1.0 and I want a 1 liner that will map it to:
0.2.0

I am sure a guru in PS can make fast work of this

Body:
If I understand this right, you want to add 1 to the 2nd number.  I wish I could do $a.minor += 1, but the [version] type is read-only.

$a = '0.1.0'
$nums = $a.split('.')
'{0}.{1}.{2}' -f $nums[0], ([int]$nums[1] + 1), $nums[2]

0.2.0

Or

$a = '0.1.0'
$nums = $a -split '\.'
([int]$nums[1])++
$nums -join '.'

0.2.0

Or

$a = '0.1.0'
$nums = $a.split('.')
([int]$nums[1])++
'{0}.{1}.{2}' -f $nums

0.2.0

I was also trying the ps 6 version of -replace with the scriptblock, but it became challenging.

See also Increment version in a text file

Here's another one, but it needs powershell 6 for the -replace with a scriptblock.  I'm using regex with positive lookahead and positive lookbehind, so I'm only replacing the number and not the 2 dots on each side.  This would only work with 3 numbers, unless you wanted to increment 2 middle numbers by 1, lol.  It certainly qualifies as a one-liner.

'0.11.0' -replace '(?<=\.)\d+(?=\.)', { [int]"$_" + 1 }

0.12.0

'0.11.11.0' -replace '(?<=\.)\d+(?=\.)', { [int]"$_" + 1 }

0.12.12.0


问:
FragmentStatePagerAdapter is deprecated from API 27
FragmentStatePagerAdapter is deprecated from API 27. What's the alternative of FragmentStatePagerAdapter?

```<code>private class MainPagerAdapter extends FragmentStatePagerAdapter {

    MainPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        Fragment result = new DummyFragment();
        return result;
    }

    @Override
    public int getCount() {
        return 5;
    }

}
</code>```

Above code shows FragmentStatePagerAdapter, getItem(...) and super(...) as deprecated.

答:
The constructor with only FragmentManager as a paramaeter is duplicated and changed to

```<code>public FragmentStatePagerAdapter(@NonNull FragmentManager fm,
        @Behavior int behavior)
</code>```

but you can achieve the same by using the below constructor, you should also inject your tabsNumber via constructor to avoid using hard codded numbers, and return it via getCount().

```<code>public PagerAdapter(FragmentManager fm, int NumOfTabs) {
    super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
    this.numberOfTabs= NumOfTabs;
}

@Override
    public int getCount() {

        return numberOfTabs;
    }
</code>```

for more details check the official documentation for AndroidX

Body:
FragmentStatePagerAdapter is deprecated from API 27. What's the alternative of FragmentStatePagerAdapter?

private class MainPagerAdapter extends FragmentStatePagerAdapter {

    MainPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        Fragment result = new DummyFragment();
        return result;
    }

    @Override
    public int getCount() {
        return 5;
    }

}

Above code shows FragmentStatePagerAdapter, getItem(...) and super(...) as deprecated.

Body:
The constructor with only FragmentManager as a paramaeter is duplicated and changed to

public FragmentStatePagerAdapter(@NonNull FragmentManager fm,
        @Behavior int behavior)

but you can achieve the same by using the below constructor, you should also inject your tabsNumber via constructor to avoid using hard codded numbers, and return it via getCount().

public PagerAdapter(FragmentManager fm, int NumOfTabs) {
    super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
    this.numberOfTabs= NumOfTabs;
}

@Override
    public int getCount() {

        return numberOfTabs;
    }

for more details check the official documentation for AndroidX


问:
Is it possible to display a wpf window without an icon in the title bar?
As we all know, if the icon for a wpf window is undefined then the default icon is displayed. I want to display a window without any icon in the title bar. I realise that I could use a blank image, however this would cause the text in the title bar to be offset to the right.

Does anyone know of a way to completely remove the icon?

(I tried searching for a similar question but couldn't find anything.)

答:
I know this is answered, however Dan Rigsby's blog has an article that shows how to do this without hiding the minimize/maximize boxes.

I found this was frustrating me as I was using the articles (here and here but it kept hiding all the buttons when the sysmenu was hidden, to help I created this helper which as shown above call in OnSourceInitialized.

```<code>public static class WpfWindowHelper {

    [DllImport("user32.dll")]
    public static extern int GetWindowLong(IntPtr hwnd, int index);
    [DllImport("user32.dll")]
    public static extern int SetWindowLong(IntPtr hwnd, int index, int newStyle);
    [DllImport("user32.dll")]
    public static extern bool SetWindowPos(IntPtr hwnd, IntPtr hwndInsertAfter, int x, int y, int width, int height, uint flags);

    public const int GWL_EXSTYLE = -20;
    public const int WS_EX_DLGMODALFRAME = 0x0001;
    public const int SWP_NOSIZE = 0x0001;
    public const int SWP_NOMOVE = 0x0002;
    public const int SWP_NOZORDER = 0x0004;
    public const int SWP_FRAMECHANGED = 0x0020;
    public const int GWL_STYLE = -16;
    public const int WS_MAXIMIZEBOX = 0x00010000;
    public const int WS_MINIMIZEBOX = 0x00020000;
    public const int WS_SYSMENU = 0x00080000;

    public static void HideSysMenu(this Window w) {
        IntPtr hwnd = new WindowInteropHelper(w).Handle;
        int extendedStyle = GetWindowLong(hwnd, GWL_EXSTYLE);
        SetWindowLong(hwnd, GWL_EXSTYLE, extendedStyle | WS_EX_DLGMODALFRAME);
        SetWindowPos(hwnd, IntPtr.Zero, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);
    }

    public static void HideMinimizeBox(this Window w) {
        IntPtr hwnd = new WindowInteropHelper(w).Handle;
        SetWindowLong(hwnd, GWL_STYLE,
            GetWindowLong(hwnd, GWL_STYLE) & ~(WS_MINIMIZEBOX));
    }

    public static void HideMaximizeBox(this Window w) {
        IntPtr hwnd = new WindowInteropHelper(w).Handle;
        SetWindowLong(hwnd, GWL_STYLE,
            GetWindowLong(hwnd, GWL_STYLE) & ~(WS_MAXIMIZEBOX));
    }

    public static void HideMinimizeAndMaximizeBoxes(this Window w) {
        IntPtr hwnd = new WindowInteropHelper(w).Handle;
        SetWindowLong(hwnd, GWL_STYLE,
            GetWindowLong(hwnd, GWL_STYLE) & ~(WS_MAXIMIZEBOX | WS_MINIMIZEBOX));
    }

}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I know this is answered, however Dan Rigsby's blog has an article that shows how to do this without hiding the minimize/maximize boxes.

I found this was frustrating me as I was using the articles (here and here but it kept hiding all the buttons when the sysmenu was hidden, to help I created this helper which as shown above call in OnSourceInitialized.

public static class WpfWindowHelper {

    [DllImport("user32.dll")]
    public static extern int GetWindowLong(IntPtr hwnd, int index);
    [DllImport("user32.dll")]
    public static extern int SetWindowLong(IntPtr hwnd, int index, int newStyle);
    [DllImport("user32.dll")]
    public static extern bool SetWindowPos(IntPtr hwnd, IntPtr hwndInsertAfter, int x, int y, int width, int height, uint flags);

    public const int GWL_EXSTYLE = -20;
    public const int WS_EX_DLGMODALFRAME = 0x0001;
    public const int SWP_NOSIZE = 0x0001;
    public const int SWP_NOMOVE = 0x0002;
    public const int SWP_NOZORDER = 0x0004;
    public const int SWP_FRAMECHANGED = 0x0020;
    public const int GWL_STYLE = -16;
    public const int WS_MAXIMIZEBOX = 0x00010000;
    public const int WS_MINIMIZEBOX = 0x00020000;
    public const int WS_SYSMENU = 0x00080000;

    public static void HideSysMenu(this Window w) {
        IntPtr hwnd = new WindowInteropHelper(w).Handle;
        int extendedStyle = GetWindowLong(hwnd, GWL_EXSTYLE);
        SetWindowLong(hwnd, GWL_EXSTYLE, extendedStyle | WS_EX_DLGMODALFRAME);
        SetWindowPos(hwnd, IntPtr.Zero, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);
    }

    public static void HideMinimizeBox(this Window w) {
        IntPtr hwnd = new WindowInteropHelper(w).Handle;
        SetWindowLong(hwnd, GWL_STYLE,
            GetWindowLong(hwnd, GWL_STYLE) & ~(WS_MINIMIZEBOX));
    }

    public static void HideMaximizeBox(this Window w) {
        IntPtr hwnd = new WindowInteropHelper(w).Handle;
        SetWindowLong(hwnd, GWL_STYLE,
            GetWindowLong(hwnd, GWL_STYLE) & ~(WS_MAXIMIZEBOX));
    }

    public static void HideMinimizeAndMaximizeBoxes(this Window w) {
        IntPtr hwnd = new WindowInteropHelper(w).Handle;
        SetWindowLong(hwnd, GWL_STYLE,
            GetWindowLong(hwnd, GWL_STYLE) & ~(WS_MAXIMIZEBOX | WS_MINIMIZEBOX));
    }

}


问:
Run Docker on Ubuntu on Windows Subsystem for Linux
I've tried to run Docker on WSL unsuccessfully. I've installed Docker on WSL following the steps given to install Docker on Ubuntu but when I execute docker ps I get the following error:

```<code>docker ps
Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
</code>```

Watching docker logs I found this:

```<code>level=warning msg="Running modprobe nf_nat failed with message: `modprobe: ERROR: ../libkmod/libkmod.c:586 kmod_search_moddep() could not open moddep file '/lib/modules/4.4.0-43-Microsoft/modules.dep.bin'\nmodprobe: WARNING: Module nf_nat not found in directory /lib/modules/4.4.0-43-Microsoft`, error: exit status 1"
time="2017-12-28T12:07:23.227671600+01:00" level=warning msg="Running modprobe xt_conntrack failed with message: `modprobe: ERROR: ../libkmod/libkmod.c:586 kmod_search_moddep() could not open moddep file '/lib/modules/4.4.0-43-Microsoft/modules.dep.bin'\nmodprobe: WARNING: Module xt_conntrack not found in directory /lib/modules/4.4.0-43-Microsoft`, error: exit status 1"
Error starting daemon: Error initializing network controller: error obtaining controller instance: failed to create NAT chain: iptables failed: iptables -t nat -N DOCKER: iptables v1.6.0: can't initialize iptables table `nat': Table does not exist (do you need to insmod?)
Perhaps iptables or your kernel needs to be upgraded.
 (exit status 3)
</code>```

Any idea how can I run Docker on WSL?

答:
For Window 10 -  Build 1909

This worked for me. Run these commands inside WLS Ubuntu.

```<code>$ sudo ln -s /mnt/c/Program\ Files/Docker/Docker/resources/bin/docker.exe /usr/bin/docker
$ alias docker='docker.exe'
$ alias docker-compose=docker-compose.exe
</code>```

Windows doesn't let WSL to use TCP for Docker, so you need to link docker file to the docker.exe in windows.

Body:
I've tried to run Docker on WSL unsuccessfully. I've installed Docker on WSL following the steps given to install Docker on Ubuntu but when I execute docker ps I get the following error:

docker ps
Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?

Watching docker logs I found this:

level=warning msg="Running modprobe nf_nat failed with message: `modprobe: ERROR: ../libkmod/libkmod.c:586 kmod_search_moddep() could not open moddep file '/lib/modules/4.4.0-43-Microsoft/modules.dep.bin'\nmodprobe: WARNING: Module nf_nat not found in directory /lib/modules/4.4.0-43-Microsoft`, error: exit status 1"
time="2017-12-28T12:07:23.227671600+01:00" level=warning msg="Running modprobe xt_conntrack failed with message: `modprobe: ERROR: ../libkmod/libkmod.c:586 kmod_search_moddep() could not open moddep file '/lib/modules/4.4.0-43-Microsoft/modules.dep.bin'\nmodprobe: WARNING: Module xt_conntrack not found in directory /lib/modules/4.4.0-43-Microsoft`, error: exit status 1"
Error starting daemon: Error initializing network controller: error obtaining controller instance: failed to create NAT chain: iptables failed: iptables -t nat -N DOCKER: iptables v1.6.0: can't initialize iptables table `nat': Table does not exist (do you need to insmod?)
Perhaps iptables or your kernel needs to be upgraded.
 (exit status 3)

Any idea how can I run Docker on WSL?

Body:
For Window 10 -  Build 1909

This worked for me. Run these commands inside WLS Ubuntu.

$ sudo ln -s /mnt/c/Program\ Files/Docker/Docker/resources/bin/docker.exe /usr/bin/docker
$ alias docker='docker.exe'
$ alias docker-compose=docker-compose.exe

Windows doesn't let WSL to use TCP for Docker, so you need to link docker file to the docker.exe in windows.


问:
TypeError: __init__() missing 3 required positional arguments?
I have recently started python and tried to write simple program but this error keep showing up. What am i doing wrong?

```<code>class Store:

 def __init__(self,name, id, price):
    self.name=name
    self.id=id
    self.price=price
    print("------------")

Store()
item1=Store(Chips, 10, 500)
</code>```

OUTPUT

Traceback (most recent call last):
  File "C:/Users/aqsa/PycharmProjects/untitled5/list.py", line 8, in <module>
    Store()
TypeError: __init__() missing 3 required positional arguments: 'name', 'id', and 'price'

Process finished with exit code 1
```

Thanks in advance.

答:
You define your constructor for the Store class as

```<code> def __init__(self,name, id, price):
    self.name=name
    self.id=id
    self.price=price
    print("------------")
</code>```

Then call it with Store() which expects a constructor like

```<code> def __init__():
    self.name='default'
    self.id=0
    self.price=0
    print("------------")
</code>```

Get rid of the Store() call!

Also, did you mean to call the other constructor as Store('Chips', 10, 500)?

Giving us

```<code>class Store:

 def __init__(self,name, id, price):
    self.name=name
    self.id=id
    self.price=price
    print("------------")

item1=Store('Chips', 10, 500)
</code>```

Body:
I have recently started python and tried to write simple program but this error keep showing up. What am i doing wrong?

class Store:

 def __init__(self,name, id, price):
    self.name=name
    self.id=id
    self.price=price
    print("------------")

Store()
item1=Store(Chips, 10, 500)

OUTPUT

Traceback (most recent call last):
  File "C:/Users/aqsa/PycharmProjects/untitled5/list.py", line 8, in <module>
    Store()
TypeError: __init__() missing 3 required positional arguments: 'name', 'id', and 'price'

Process finished with exit code 1

Thanks in advance.

Body:
You define your constructor for the Store class as

 def __init__(self,name, id, price):
    self.name=name
    self.id=id
    self.price=price
    print("------------")

Then call it with Store() which expects a constructor like

 def __init__():
    self.name='default'
    self.id=0
    self.price=0
    print("------------")

Get rid of the Store() call!

Also, did you mean to call the other constructor as Store('Chips', 10, 500)?

Giving us

class Store:

 def __init__(self,name, id, price):
    self.name=name
    self.id=id
    self.price=price
    print("------------")

item1=Store('Chips', 10, 500)


问:
Unable to click an element within iframe in IE
I want to click on an element as follows:

```<code>//select[@name='instructionSelection']
</code>```

But its not clicking with Selenium on IE 11.

HTML:

答:
You have to switch to iframe using name=InvoiceDeatils before interacting with the element.

Not sure which language you are using. Providing the snippet in python below.

```<code>driver.switch_to.frame(driver.find_element_by_name('InvoiceDeatils'))
# now click on the element
driver.find_element_by_xpath("//select[@name='instructionSelection']").click()
</code>```

Body:
I want to click on an element as follows:

//select[@name='instructionSelection']

But its not clicking with Selenium on IE 11.

HTML:

Body:
You have to switch to iframe using name=InvoiceDeatils before interacting with the element.

Not sure which language you are using. Providing the snippet in python below.

driver.switch_to.frame(driver.find_element_by_name('InvoiceDeatils'))
# now click on the element
driver.find_element_by_xpath("//select[@name='instructionSelection']").click()


问:
Start cfn-init in Ubuntu instance with cloudformation (yaml)
I try to start the cfn-init with:

```<code>Fn::Base64: !Sub |
  #!/bin/bash
  sudo apt-get -y install python-setuptools
  mkdir aws-cfn-bootstrap-latest
  curl https://s3.amazonaws.com/cloudformation-examples/aws-cfn-bootstrap-latest.tar.gz | tar xz -C aws-cfn-bootstrap-latest --strip-components 1
  sudo easy_install aws-cfn-bootstrap-latest
  sudo /usr/local/bin/cfn-init --stack !Ref 'AWS::StackName' --resource xxx --region !Ref 'AWS::Region'
</code>```

The first steps work. I can access the instance and cfn-init is installed. When I execute the cfn-init --stack.. command inside my ec2 instance it works fine when I hardcode the values for stackname and region.

How to make it work in the yaml script? It seems it can not read the values for StackName and region.

答:
```<code>Fn::Base64: !Sub |
  #!/bin/bash
  sudo apt-get -y install python-setuptools
  mkdir aws-cfn-bootstrap-latest
  curl https://s3.amazonaws.com/cloudformation-examples/aws-cfn-bootstrap-latest.tar.gz | tar xz -C aws-cfn-bootstrap-latest --strip-components 1
  sudo easy_install aws-cfn-bootstrap-latest
  sudo /usr/local/bin/cfn-init --stack ${AWS::StackName} --resource xxx --region ${AWS::Region}

</code>```

IF easy_install didn't work for ubuntu 18.04 then use this following command:

```<code>python /usr/lib/python2.7/dist-packages/easy_install.py aws-cfn-bootstrap-latest
</code>```

Body:
I try to start the cfn-init with:

Fn::Base64: !Sub |
  #!/bin/bash
  sudo apt-get -y install python-setuptools
  mkdir aws-cfn-bootstrap-latest
  curl https://s3.amazonaws.com/cloudformation-examples/aws-cfn-bootstrap-latest.tar.gz | tar xz -C aws-cfn-bootstrap-latest --strip-components 1
  sudo easy_install aws-cfn-bootstrap-latest
  sudo /usr/local/bin/cfn-init --stack !Ref 'AWS::StackName' --resource xxx --region !Ref 'AWS::Region'

The first steps work. I can access the instance and cfn-init is installed. When I execute the cfn-init --stack.. command inside my ec2 instance it works fine when I hardcode the values for stackname and region.

How to make it work in the yaml script? It seems it can not read the values for StackName and region.

Body:
Fn::Base64: !Sub |
  #!/bin/bash
  sudo apt-get -y install python-setuptools
  mkdir aws-cfn-bootstrap-latest
  curl https://s3.amazonaws.com/cloudformation-examples/aws-cfn-bootstrap-latest.tar.gz | tar xz -C aws-cfn-bootstrap-latest --strip-components 1
  sudo easy_install aws-cfn-bootstrap-latest
  sudo /usr/local/bin/cfn-init --stack ${AWS::StackName} --resource xxx --region ${AWS::Region}

IF easy_install didn't work for ubuntu 18.04 then use this following command:

python /usr/lib/python2.7/dist-packages/easy_install.py aws-cfn-bootstrap-latest


问:
Ranking newer items fairly?
Using StackOverflow itself as an example, if you had any such system where entries were voted and viewed in order of rank based on this, how do you compensate to sort newer entries fairly? That is, if ten bad answers are given and upvoted, how do you make sure people see the new entry that might be better, but hasn't had time to gather votes or even been seen all the way at the bottom?</p>

答: Provide a "Sort by Newest" function.</p>

OwnerDisplayName: ironfroggy

Title: Ranking newer items fairly?

LastEditorDisplayName: Pete Kirkham

Body: Provide a "Sort by Newest" function.

OwnerDisplayName: Jason Punyon