问:
Edit/delete not working symfony 3
My edit/delete was working and as I continued to work on my project it stopped working somewhere along the way. I get this message when I try to edit or delete.

"No route found for "DELETE /shrubs/1/edit": Method Not Allowed (Allow: GET, POST, HEAD)"

I thought the controller handled this or do I need something in the routing.yml too?

I have this in my controller:

```<code>/**
     * Displays a form to edit an existing Shrubs entity.
     *
     * @Route("/{id}/edit", name="shrubs_edit")
     * @Method({"GET", "POST"})
     */
    public function editAction(Request $request, Shrubs $shrub)
    {
    $deleteForm = $this->createDeleteForm($shrub);
    $editForm = $this->createForm('AppBundle\Form\ShrubsType', $shrub);
    $editForm->handleRequest($request);

    if ($editForm->isSubmitted() && $editForm->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $em->persist($shrub);
        $em->flush();

        return $this->redirectToRoute('shrubs_edit', array('id' => $shrub->getId()));
    }

    return $this->render('shrubs/edit.html.twig', array(
        'shrub' => $shrub,
        'edit_form' => $editForm->createView(),
        'delete_form' => $deleteForm->createView(),
    ));
}

/**
 * Deletes a Shrubs entity.
 *
 * @Route("/{id}", name="shrubs_delete")
 * @Method("DELETE")
 */
public function deleteAction(Request $request, Shrubs $shrub)
{
    $form = $this->createDeleteForm($shrub);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $em->remove($shrub);
        $em->flush();
    }

    return $this->redirectToRoute('shrubs_index');
}

/**
 * Creates a form to delete a Shrubs entity.
 *
 * @param Shrubs $shrub The Shrubs entity
 *
 * @return \Symfony\Component\Form\Form The form
 */
private function createDeleteForm(Shrubs $shrub)
{
    return $this->createFormBuilder()
        ->setAction($this->generateUrl('shrubs_delete', array('id' => $shrub->getId())))
        ->setMethod('DELETE')
        ->getForm()
    ;
}
</code>```

My edit page has this:

```<code> <button type="submit" id="register-submit-btn" class="btn btn-success">Edit</button>

    {{ form_start(delete_form) }}
    <input type="submit" value="Delete">
    {{ form_end(delete_form) }}
</code>```

If I need something for my routing.yml what would I add?

答:
Try to add the DELETE method in your routing, this is what the error message is saying.
You use a DELETE method but you only allow GET, POST.

```<code>/**
 * Displays a form to edit an existing Shrubs entity.
 *
 * @Route("/{id}/edit", name="shrubs_edit")
 * @Method({"DELETE", "GET", "POST"})
*/
public function editAction(Request $request, Shrubs $shrub)
</code>```

Title: Edit/delete not working symfony 3

Body:
My edit/delete was working and as I continued to work on my project it stopped working somewhere along the way. I get this message when I try to edit or delete.

"No route found for "DELETE /shrubs/1/edit": Method Not Allowed (Allow: GET, POST, HEAD)"

I thought the controller handled this or do I need something in the routing.yml too?

I have this in my controller:

/**
     * Displays a form to edit an existing Shrubs entity.
     *
     * @Route("/{id}/edit", name="shrubs_edit")
     * @Method({"GET", "POST"})
     */
    public function editAction(Request $request, Shrubs $shrub)
    {
    $deleteForm = $this->createDeleteForm($shrub);
    $editForm = $this->createForm('AppBundle\Form\ShrubsType', $shrub);
    $editForm->handleRequest($request);

    if ($editForm->isSubmitted() && $editForm->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $em->persist($shrub);
        $em->flush();

        return $this->redirectToRoute('shrubs_edit', array('id' => $shrub->getId()));
    }

    return $this->render('shrubs/edit.html.twig', array(
        'shrub' => $shrub,
        'edit_form' => $editForm->createView(),
        'delete_form' => $deleteForm->createView(),
    ));
}

/**
 * Deletes a Shrubs entity.
 *
 * @Route("/{id}", name="shrubs_delete")
 * @Method("DELETE")
 */
public function deleteAction(Request $request, Shrubs $shrub)
{
    $form = $this->createDeleteForm($shrub);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $em->remove($shrub);
        $em->flush();
    }

    return $this->redirectToRoute('shrubs_index');
}

/**
 * Creates a form to delete a Shrubs entity.
 *
 * @param Shrubs $shrub The Shrubs entity
 *
 * @return \Symfony\Component\Form\Form The form
 */
private function createDeleteForm(Shrubs $shrub)
{
    return $this->createFormBuilder()
        ->setAction($this->generateUrl('shrubs_delete', array('id' => $shrub->getId())))
        ->setMethod('DELETE')
        ->getForm()
    ;
}

My edit page has this:

 <button type="submit" id="register-submit-btn" class="btn btn-success">Edit</button>

    {{ form_start(delete_form) }}
    <input type="submit" value="Delete">
    {{ form_end(delete_form) }}

If I need something for my routing.yml what would I add?

Body:
Try to add the DELETE method in your routing, this is what the error message is saying.
You use a DELETE method but you only allow GET, POST.

/**
 * Displays a form to edit an existing Shrubs entity.
 *
 * @Route("/{id}/edit", name="shrubs_edit")
 * @Method({"DELETE", "GET", "POST"})
*/
public function editAction(Request $request, Shrubs $shrub)


来源: stackexchange

问:
generate 0 and 1 with 25% and 75 probability
i  have seen  the following problem one one site :

```<code> how to  generate 0 and  1  with 25% and  75% probability, here is corresponding code in c++

int rand50()
{
    // rand() function will generate odd or even
    // number with equal probability. If rand()
    // generates odd number, the function will
    // return 1 else it will return 0.
    return rand() & 1;
}
 bool rand75()
{
    return rand50() | rand50();
}
</code>```

but unfortunately i can't do

```<code>>> bitand(rand,1)
Error using bitand
Double inputs must have integer values in the range of ASSUMEDTYPE.
</code>```

therefore i used following  algorithms
1. rand50

```<code>function boolean=rand50()

        probability=rand;

        if  probability <=0.5
            boolean=0;
        else
            boolean=1;
        end

        end
</code>```

2.rand75

```<code>function  boolean=rand75()
boolean=bitor(rand50(),rand50());

end
</code>```

i think they are equivalent right?or at least well approximated

答:
rand in C/C++ returns an integer whereas in MATLAB it returns a double between 0 and 1. As you've shown, you can construct a function which will give you a value of true or false with equal probability using 0.5, although it can be shortened to:

```<code>function bool = rand50()
    bool = rand() < 0.5;
end
</code>```

That being said, I think I would recommend modifying your function a little bit to accept a dimension as input such that you can generate an arbitrary number of random samples at once. You can then test the output to make sure it is as expected

```<code>function bool = rand50(sz)
    bool = rand(sz) < 0.5;
end

function bool = rand75(sz)
    bool = rand50(sz) | rand50(sz);
end
</code>```

Now we can test this

```<code>samples = rand75([10000, 1]);
mean(samples)
%   0.7460
</code>```

Now if you ignore the code that you've shown, the better way to generate random numbers with a given frequency would be to create a function where you specify the percentage of 0's or 1's that you want and use that to compare to the output of rand

```<code>function bool = myrand(sz, percentage)
    bool = rand(sz) < percentage;
end

% Get 10 samples with 25% 1's
values = myrand([10, 1], 0.25);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
i  have seen  the following problem one one site :

 how to  generate 0 and  1  with 25% and  75% probability, here is corresponding code in c++

int rand50()
{
    // rand() function will generate odd or even
    // number with equal probability. If rand()
    // generates odd number, the function will
    // return 1 else it will return 0.
    return rand() & 1;
}
 bool rand75()
{
    return rand50() | rand50();
}

but unfortunately i can't do

>> bitand(rand,1)
Error using bitand
Double inputs must have integer values in the range of ASSUMEDTYPE.

therefore i used following  algorithms
1. rand50

function boolean=rand50()

        probability=rand;

        if  probability <=0.5
            boolean=0;
        else
            boolean=1;
        end

        end

2.rand75

function  boolean=rand75()
boolean=bitor(rand50(),rand50());

end

i think they are equivalent right?or at least well approximated

Body:
rand in C/C++ returns an integer whereas in MATLAB it returns a double between 0 and 1. As you've shown, you can construct a function which will give you a value of true or false with equal probability using 0.5, although it can be shortened to:

function bool = rand50()
    bool = rand() < 0.5;
end

That being said, I think I would recommend modifying your function a little bit to accept a dimension as input such that you can generate an arbitrary number of random samples at once. You can then test the output to make sure it is as expected

function bool = rand50(sz)
    bool = rand(sz) < 0.5;
end

function bool = rand75(sz)
    bool = rand50(sz) | rand50(sz);
end

Now we can test this

samples = rand75([10000, 1]);
mean(samples)
%   0.7460

Now if you ignore the code that you've shown, the better way to generate random numbers with a given frequency would be to create a function where you specify the percentage of 0's or 1's that you want and use that to compare to the output of rand

function bool = myrand(sz, percentage)
    bool = rand(sz) < percentage;
end

% Get 10 samples with 25% 1's
values = myrand([10, 1], 0.25);


问:
MSC00001: Failed to start service jboss.deployment.unit
I have problem with my project using Jboss 7.0
I can't build that.

This is my problem

```<code>19:00:38,809 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-3) MSC00001: Failed to start service jboss.deployment.unit."brangista.war".INSTALL: org.jboss.msc.service.StartException in service jboss.deployment.unit."brangista.war".INSTALL: Failed to process phase INSTALL of deployment "brangista.war"
at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:121)
at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1824)
at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1759)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) [:1.6.0_35]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) [:1.6.0_35]
at java.lang.Thread.run(Thread.java:662) [:1.6.0_35]
Caused by: java.lang.RuntimeException: Failed to load class com.brangista.base.filter.CharacterEncodingFilter
at org.jboss.as.ee.component.deployers.EEClassConfigurationProcessor$1.compute(EEClassConfigurationProcessor.java:141)
at org.jboss.as.ee.component.deployers.EEClassConfigurationProcessor$1.compute(EEClassConfigurationProcessor.java:122)
at org.jboss.as.ee.component.LazyValue.get(LazyValue.java:40)
at org.jboss.as.ee.component.EEApplicationDescription.getClassConfiguration(EEApplicationDescription.java:183)
at org.jboss.as.ee.component.ComponentDescription.createConfiguration(ComponentDescription.java:153)
at org.jboss.as.ee.component.deployers.EEModuleConfigurationProcessor.deploy(EEModuleConfigurationProcessor.java:70)
at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:115)
... 5 more
Caused by: java.lang.ClassNotFoundException: com.brangista.base.filter.CharacterEncodingFilter from [Module "deployment.brangista.war:main" from Service Module Loader]
at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:191)
at org.jboss.modules.ConcurrentClassLoader.performLoadClassChecked(ConcurrentClassLoader.java:361)
at org.jboss.modules.ConcurrentClassLoader.performLoadClassChecked(ConcurrentClassLoader.java:333)
at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:310)
at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:103)
at java.lang.Class.forName0(Native Method) [:1.6.0_35]
at java.lang.Class.forName(Class.java:247) [:1.6.0_35]
at org.jboss.as.ee.component.deployers.EEClassConfigurationProcessor$1.compute(EEClassConfigurationProcessor.java:139)
... 11 more

19:00:39,017 INFO  [org.jboss.as.server.controller] (DeploymentScanner-threads - 2) Deployment of "brangista.war" was rolled back with failure message {"Failed services" => {"jboss.deployment.unit.\"brangista.war\".INSTALL" => "org.jboss.msc.service.StartException in service jboss.deployment.unit.\"brangista.war\".INSTALL: Failed to process phase INSTALL of deployment \"brangista.war\""},"Services with missing/unavailable dependencies" => ["jboss.naming.context.java.module.brangista.brangista.ValidatorFactory missing [ jboss.naming.context.java.module.brangista.brangista ]","jboss.naming.context.java.module.brangista.brangista.Validator missing [ jboss.naming.context.java.module.brangista.brangista ]"]}
19:00:39,240 INFO  [org.jboss.as.server.deployment] (MSC service thread 1-3) Stopped deployment brangista.war in 223ms
19:00:39,242 ERROR [org.jboss.as.deployment] (DeploymentScanner-threads - 1) {"Composite operation failed and was rolled back. Steps that failed:" => {"Operation step-2" => {"Failed services" => {"jboss.deployment.unit.\"brangista.war\".INSTALL" => "org.jboss.msc.service.StartException in service jboss.deployment.unit.\"brangista.war\".INSTALL: Failed to process phase INSTALL of deployment \"brangista.war\""},"Services with missing/unavailable dependencies" => ["jboss.naming.context.java.module.brangista.brangista.ValidatorFactory missing [ jboss.naming.context.java.module.brangista.brangista ]","jboss.naming.context.java.module.brangista.brangista.Validator missing [ jboss.naming.context.java.module.brangista.brangista ]"]}}}
</code>```

答:
To solve this error,

check your database source setup with Jboss is well define(I mean in JBOSS_Home/modules/com/mysql/main/module.xml and JBOSS_Home/modules/org/your source setup )

define your database in standalone.xml

Set up persistent.xml

clean server and start server.

for guidelines: How to configure Hibernate in JBoss

If still a same problem then check your project structure.

Body:
I have problem with my project using Jboss 7.0
I can't build that.

This is my problem

19:00:38,809 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-3) MSC00001: Failed to start service jboss.deployment.unit."brangista.war".INSTALL: org.jboss.msc.service.StartException in service jboss.deployment.unit."brangista.war".INSTALL: Failed to process phase INSTALL of deployment "brangista.war"
at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:121)
at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1824)
at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1759)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) [:1.6.0_35]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) [:1.6.0_35]
at java.lang.Thread.run(Thread.java:662) [:1.6.0_35]
Caused by: java.lang.RuntimeException: Failed to load class com.brangista.base.filter.CharacterEncodingFilter
at org.jboss.as.ee.component.deployers.EEClassConfigurationProcessor$1.compute(EEClassConfigurationProcessor.java:141)
at org.jboss.as.ee.component.deployers.EEClassConfigurationProcessor$1.compute(EEClassConfigurationProcessor.java:122)
at org.jboss.as.ee.component.LazyValue.get(LazyValue.java:40)
at org.jboss.as.ee.component.EEApplicationDescription.getClassConfiguration(EEApplicationDescription.java:183)
at org.jboss.as.ee.component.ComponentDescription.createConfiguration(ComponentDescription.java:153)
at org.jboss.as.ee.component.deployers.EEModuleConfigurationProcessor.deploy(EEModuleConfigurationProcessor.java:70)
at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:115)
... 5 more
Caused by: java.lang.ClassNotFoundException: com.brangista.base.filter.CharacterEncodingFilter from [Module "deployment.brangista.war:main" from Service Module Loader]
at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:191)
at org.jboss.modules.ConcurrentClassLoader.performLoadClassChecked(ConcurrentClassLoader.java:361)
at org.jboss.modules.ConcurrentClassLoader.performLoadClassChecked(ConcurrentClassLoader.java:333)
at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:310)
at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:103)
at java.lang.Class.forName0(Native Method) [:1.6.0_35]
at java.lang.Class.forName(Class.java:247) [:1.6.0_35]
at org.jboss.as.ee.component.deployers.EEClassConfigurationProcessor$1.compute(EEClassConfigurationProcessor.java:139)
... 11 more

19:00:39,017 INFO  [org.jboss.as.server.controller] (DeploymentScanner-threads - 2) Deployment of "brangista.war" was rolled back with failure message {"Failed services" => {"jboss.deployment.unit.\"brangista.war\".INSTALL" => "org.jboss.msc.service.StartException in service jboss.deployment.unit.\"brangista.war\".INSTALL: Failed to process phase INSTALL of deployment \"brangista.war\""},"Services with missing/unavailable dependencies" => ["jboss.naming.context.java.module.brangista.brangista.ValidatorFactory missing [ jboss.naming.context.java.module.brangista.brangista ]","jboss.naming.context.java.module.brangista.brangista.Validator missing [ jboss.naming.context.java.module.brangista.brangista ]"]}
19:00:39,240 INFO  [org.jboss.as.server.deployment] (MSC service thread 1-3) Stopped deployment brangista.war in 223ms
19:00:39,242 ERROR [org.jboss.as.deployment] (DeploymentScanner-threads - 1) {"Composite operation failed and was rolled back. Steps that failed:" => {"Operation step-2" => {"Failed services" => {"jboss.deployment.unit.\"brangista.war\".INSTALL" => "org.jboss.msc.service.StartException in service jboss.deployment.unit.\"brangista.war\".INSTALL: Failed to process phase INSTALL of deployment \"brangista.war\""},"Services with missing/unavailable dependencies" => ["jboss.naming.context.java.module.brangista.brangista.ValidatorFactory missing [ jboss.naming.context.java.module.brangista.brangista ]","jboss.naming.context.java.module.brangista.brangista.Validator missing [ jboss.naming.context.java.module.brangista.brangista ]"]}}}


问:
Invoking ranges::for_each with lambda and global function
The following code works as expected:

```<code>void foo(auto const &){}

auto const rng{ranges::view::all(v)};
ranges::for_each(rng, [](auto const & r){
    foo(r);
});
</code>```

But the following:

```<code>void foo(auto const &){}

auto const rng{ranges::view::all(v)};
ranges::for_each(rng, &foo);
</code>```

Gives the compilation error:

```<code>template argument deduction/substitution failed:
couldn't deduce template parameter 'F'
</code>```

I took a look at the source but to be honest I couldn't understand the problem.

答:
You cannot take the address of an overloaded or template function by without explicitly specifying the overload/instantiation you desire.

Passing a lambda expression as in your first snippet is a good solution to this issue.

Alternatively, if you have access to foo, you could turn it into a function object:

```<code>namespace detail
{
    struct foo_t
    {
        template <typename T>
        void operator()(const T&) const { /* ... */ }
    };
}

constexpr detail::foo_t foo{};
</code>```

This allows you to write:

```<code>ranges::for_each(rng, foo);
</code>```

Body:
The following code works as expected:

void foo(auto const &){}

auto const rng{ranges::view::all(v)};
ranges::for_each(rng, [](auto const & r){
    foo(r);
});

But the following:

void foo(auto const &){}

auto const rng{ranges::view::all(v)};
ranges::for_each(rng, &foo);

Gives the compilation error:

template argument deduction/substitution failed:
couldn't deduce template parameter 'F'

I took a look at the source but to be honest I couldn't understand the problem.

Body:
You cannot take the address of an overloaded or template function by without explicitly specifying the overload/instantiation you desire.

Passing a lambda expression as in your first snippet is a good solution to this issue.

Alternatively, if you have access to foo, you could turn it into a function object:

namespace detail
{
    struct foo_t
    {
        template <typename T>
        void operator()(const T&) const { /* ... */ }
    };
}

constexpr detail::foo_t foo{};

This allows you to write:

ranges::for_each(rng, foo);


问:
How to force StrToInt, StrToIntDef to ignore hex values?
I have variable that can hold either a string or an integer. So, I use If StrToIntDef(Value) > 0 to decide either I am processing strings or integers. But this fails, when the string starts with 'x' or 'X'. I assume because it thinks it's a hex number and converts it to integer:

```<code>procedure TForm1.Button1Click(Sender: TObject);
var
  Value:integer;
  Str:string;
begin

  Str:='string';
  Value:=StrToIntDef(Str,0); // Value = 0  OK

  Str:='xa';
  Value:=StrToIntDef(Str,0); // Value = 10 - NOT OK! Shuold be 0!

  Str:='XDBA';
  Value:=StrToIntDef(Str,0); // Value = 3514 - NOT OK! Shuold be 0!

end;
</code>```

How can I make conversion function to ignore hex values?

答:
I think to be on the safe side you should validate that each character is a digit.

```<code>function StrToIntDefDecimal(const S: string; Default: Integer): Integer;
var
  C: Char;
begin
  for C in S do
    if ((C < '0') or (C > '9')) and (C <> '-') then
    begin
      Result := Default;
      exit;
    end;
  Result := StrToDef(S, Default);
end;
</code>```

However, if you simply wish to detect whether or not the string is numeric, then you can do so like this:

```<code>function IsDecimalInteger(const S: string): Boolean;
var
  C: Char;
begin
  for C in S do
    if ((C < '0') or (C > '9')) and (C <> '-') then
    begin
      Result := False;
      exit;
    end;
  Result := True;
end;
</code>```

Even this is imperfect because it will allow a value like '1-2'. But I am sure that you could modify the code to only accept '-' as the first character.

Note also that your existing test for a number, StrToIntDef(Value) > 0, will treat zero or negative numbers as strings. Is that really what you intend.

Body:
I have variable that can hold either a string or an integer. So, I use If StrToIntDef(Value) > 0 to decide either I am processing strings or integers. But this fails, when the string starts with 'x' or 'X'. I assume because it thinks it's a hex number and converts it to integer:

procedure TForm1.Button1Click(Sender: TObject);
var
  Value:integer;
  Str:string;
begin

  Str:='string';
  Value:=StrToIntDef(Str,0); // Value = 0  OK

  Str:='xa';
  Value:=StrToIntDef(Str,0); // Value = 10 - NOT OK! Shuold be 0!

  Str:='XDBA';
  Value:=StrToIntDef(Str,0); // Value = 3514 - NOT OK! Shuold be 0!

end;

How can I make conversion function to ignore hex values?

Body:
I think to be on the safe side you should validate that each character is a digit.

function StrToIntDefDecimal(const S: string; Default: Integer): Integer;
var
  C: Char;
begin
  for C in S do
    if ((C < '0') or (C > '9')) and (C <> '-') then
    begin
      Result := Default;
      exit;
    end;
  Result := StrToDef(S, Default);
end;

However, if you simply wish to detect whether or not the string is numeric, then you can do so like this:

function IsDecimalInteger(const S: string): Boolean;
var
  C: Char;
begin
  for C in S do
    if ((C < '0') or (C > '9')) and (C <> '-') then
    begin
      Result := False;
      exit;
    end;
  Result := True;
end;

Even this is imperfect because it will allow a value like '1-2'. But I am sure that you could modify the code to only accept '-' as the first character.

Note also that your existing test for a number, StrToIntDef(Value) > 0, will treat zero or negative numbers as strings. Is that really what you intend.


问:
Pipe Input on a timer
I have a program that asks for input but it takes a while to load up.

I need a bash script that will pipe out the output into a named pipe.

I need a command that will cause my echo to insert my input after the program prompts for input. This is my command right now but it pipes in the input before my prompt.

```<code>echo "R" | nc localhost 123 > fifo
</code>```

This will result in the following output:

```<code>usernname@name:
R
Please enter in an input (R, Q, T):
</code>```

So my command needs to "wait" until my program prompts then pipe in the input. Any ideas? This needs to be in a bash script

答:
You can use sleep:

```<code>(sleep 3; echo "R") | nc localhost 123 > fifo
</code>```

Obviously this has a race condition, and so for industrial applications you should use expect instead.

Title: Pipe Input on a timer

Body:
I have a program that asks for input but it takes a while to load up.

I need a bash script that will pipe out the output into a named pipe.

I need a command that will cause my echo to insert my input after the program prompts for input. This is my command right now but it pipes in the input before my prompt.

echo "R" | nc localhost 123 > fifo

This will result in the following output:

usernname@name:
R
Please enter in an input (R, Q, T):

So my command needs to "wait" until my program prompts then pipe in the input. Any ideas? This needs to be in a bash script

Body:
You can use sleep:

(sleep 3; echo "R") | nc localhost 123 > fifo

Obviously this has a race condition, and so for industrial applications you should use expect instead.


问:
UWP C#: Where does VS remember inheritance in a project
I was playing around trying to design a button and I came up with using a Border with a Button on it. Then I changed my MyClass to derive from Border. Border is a sealed class so the compiler flagged an error. So I removed the ": Border" from the class definition. Now however I still get a

Error   CS0509  'NumberedButton': cannot derive from sealed type 'Border'

As it's a partial class I wondered where else in the bowels of the project there is a memory of this? I've searched all the textfiles (I think) and come up empty-handed. See the snip on Imgur

答:
The problem, as usual, was newbie stupidity. The root object of the Xaml was still Border, whereas the code behind Class was NumberedButton.

I leave this here for others who may fall into the same trap.


问:
Comparing object properties in c#
This is what I've come up with as a method on a class inherited by many of my other classes. The idea is that it allows the simple comparison between properties of Objects of the same Type.

Now, this does work - but in the interest of improving the quality of my code I thought I'd throw it out for scrutiny. How can it be better/more efficient/etc.?

```<code>/// <summary>
/// Compare property values (as strings)
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public bool PropertiesEqual(object comparisonObject)
{

    Type sourceType = this.GetType();
    Type destinationType = comparisonObject.GetType();

    if (sourceType == destinationType)
    {
        PropertyInfo[] sourceProperties = sourceType.GetProperties();
        foreach (PropertyInfo pi in sourceProperties)
        {
            if ((sourceType.GetProperty(pi.Name).GetValue(this, null) == null && destinationType.GetProperty(pi.Name).GetValue(comparisonObject, null) == null))
            {
                // if both are null, don't try to compare  (throws exception)
            }
            else if (!(sourceType.GetProperty(pi.Name).GetValue(this, null).ToString() == destinationType.GetProperty(pi.Name).GetValue(comparisonObject, null).ToString()))
            {
                // only need one property to be different to fail Equals.
                return false;
            }
        }
    }
    else
    {
        throw new ArgumentException("Comparison object must be of the same type.","comparisonObject");
    }

    return true;
}
</code>```

答:
my solution inspired from Aras Alenin answer above where I added one level of object comparison and a custom object for comparison results. I am also interested to get property name with object name:

```<code>    public static IEnumerable<ObjectPropertyChanged> GetPublicSimplePropertiesChanged<T>(this T previous, T proposedChange,
     string[] namesOfPropertiesToBeIgnored) where T : class
    {
        return GetPublicGenericPropertiesChanged(previous, proposedChange, namesOfPropertiesToBeIgnored, true, null, null);
    }

    public static IReadOnlyList<ObjectPropertyChanged> GetPublicGenericPropertiesChanged<T>(this T previous, T proposedChange,
        string[] namesOfPropertiesToBeIgnored) where T : class
    {
        return GetPublicGenericPropertiesChanged(previous, proposedChange, namesOfPropertiesToBeIgnored, false, null, null);
    }

    /// <summary>
    /// Gets the names of the public properties which values differs between first and second objects.
    /// Considers 'simple' properties AND for complex properties without index, get the simple properties of the children objects.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="previous">The previous object.</param>
    /// <param name="proposedChange">The second object which should be the new one.</param>
    /// <param name="namesOfPropertiesToBeIgnored">The names of the properties to be ignored.</param>
    /// <param name="simpleTypeOnly">if set to <c>true</c> consider simple types only.</param>
    /// <param name="parentTypeString">The parent type string. Meant only for recursive call with simpleTypeOnly set to <c>true</c>.</param>
    /// <param name="secondType">when calling recursively, the current type of T must be clearly defined here, as T will be more generic (using base class).</param>
    /// <returns>
    /// the names of the properties
    /// </returns>
    private static IReadOnlyList<ObjectPropertyChanged> GetPublicGenericPropertiesChanged<T>(this T previous, T proposedChange,
        string[] namesOfPropertiesToBeIgnored, bool simpleTypeOnly, string parentTypeString, Type secondType) where T : class
    {
        List<ObjectPropertyChanged> propertiesChanged = new List<ObjectPropertyChanged>();

        if (previous != null && proposedChange != null)
        {
            var type = secondType == null ? typeof(T) : secondType;
            string typeStr = parentTypeString + type.Name + ".";
            var ignoreList = namesOfPropertiesToBeIgnored.CreateList();
            IEnumerable<IEnumerable<ObjectPropertyChanged>> genericPropertiesChanged =
                from pi in type.GetProperties(BindingFlags.Public | BindingFlags.Instance)
                where !ignoreList.Contains(pi.Name) && pi.GetIndexParameters().Length == 0
                    && (!simpleTypeOnly || simpleTypeOnly && pi.PropertyType.IsSimpleType())
                let firstValue = type.GetProperty(pi.Name).GetValue(previous, null)
                let secondValue = type.GetProperty(pi.Name).GetValue(proposedChange, null)
                where firstValue != secondValue && (firstValue == null || !firstValue.Equals(secondValue))
                let subPropertiesChanged = simpleTypeOnly || pi.PropertyType.IsSimpleType()
                    ? null
                    : GetPublicGenericPropertiesChanged(firstValue, secondValue, namesOfPropertiesToBeIgnored, true, typeStr, pi.PropertyType)
                let objectPropertiesChanged = subPropertiesChanged != null && subPropertiesChanged.Count() > 0
                    ? subPropertiesChanged
                    : (new ObjectPropertyChanged(proposedChange.ToString(), typeStr + pi.Name, firstValue.ToStringOrNull(), secondValue.ToStringOrNull())).CreateList()
                select objectPropertiesChanged;

            if (genericPropertiesChanged != null)
            {   // get items from sub lists
                genericPropertiesChanged.ForEach(a => propertiesChanged.AddRange(a));
            }
        }
        return propertiesChanged;
    }
</code>```

Using the following class to store comparison results

```<code>[System.Serializable]
public class ObjectPropertyChanged
{
    public ObjectPropertyChanged(string objectId, string propertyName, string previousValue, string changedValue)
    {
        ObjectId = objectId;
        PropertyName = propertyName;
        PreviousValue = previousValue;
        ProposedChangedValue = changedValue;
    }

    public string ObjectId { get; set; }

    public string PropertyName { get; set; }

    public string PreviousValue { get; set; }

    public string ProposedChangedValue { get; set; }
}
</code>```

And a sample unit test:

```<code>    [TestMethod()]
    public void GetPublicGenericPropertiesChangedTest1()
    {
        // Define objects to test
        Function func1 = new Function { Id = 1, Description = "func1" };
        Function func2 = new Function { Id = 2, Description = "func2" };
        FunctionAssignment funcAss1 = new FunctionAssignment
        {
            Function = func1,
            Level = 1
        };
        FunctionAssignment funcAss2 = new FunctionAssignment
        {
            Function = func2,
            Level = 2
        };

        // Main test: read properties changed
        var propertiesChanged = Utils.GetPublicGenericPropertiesChanged(funcAss1, funcAss2, null);

        Assert.IsNotNull(propertiesChanged);
        Assert.IsTrue(propertiesChanged.Count == 3);
        Assert.IsTrue(propertiesChanged[0].PropertyName == "FunctionAssignment.Function.Description");
        Assert.IsTrue(propertiesChanged[1].PropertyName == "FunctionAssignment.Function.Id");
        Assert.IsTrue(propertiesChanged[2].PropertyName == "FunctionAssignment.Level");
    }
</code>```

OwnerDisplayName: nailitdown

ContentLicense: CC BY-SA 2.5

Title: Comparing object properties in c#

Body:
This is what I've come up with as a method on a class inherited by many of my other classes. The idea is that it allows the simple comparison between properties of Objects of the same Type.

Now, this does work - but in the interest of improving the quality of my code I thought I'd throw it out for scrutiny. How can it be better/more efficient/etc.?

///
/// Compare property values (as strings)
///
/// <param name="obj"></param>
/// <returns></returns>
public bool PropertiesEqual(object comparisonObject)
{

    Type sourceType = this.GetType();
    Type destinationType = comparisonObject.GetType();

    if (sourceType == destinationType)
    {
        PropertyInfo[] sourceProperties = sourceType.GetProperties();
        foreach (PropertyInfo pi in sourceProperties)
        {
            if ((sourceType.GetProperty(pi.Name).GetValue(this, null) == null && destinationType.GetProperty(pi.Name).GetValue(comparisonObject, null) == null))
            {
                // if both are null, don't try to compare  (throws exception)
            }
            else if (!(sourceType.GetProperty(pi.Name).GetValue(this, null).ToString() == destinationType.GetProperty(pi.Name).GetValue(comparisonObject, null).ToString()))
            {
                // only need one property to be different to fail Equals.
                return false;
            }
        }
    }
    else
    {
        throw new ArgumentException("Comparison object must be of the same type.","comparisonObject");
    }

    return true;
}

Body:
my solution inspired from Aras Alenin answer above where I added one level of object comparison and a custom object for comparison results. I am also interested to get property name with object name:

    public static IEnumerable<ObjectPropertyChanged> GetPublicSimplePropertiesChanged<T>(this T previous, T proposedChange,
     string[] namesOfPropertiesToBeIgnored) where T : class
    {
        return GetPublicGenericPropertiesChanged(previous, proposedChange, namesOfPropertiesToBeIgnored, true, null, null);
    }

    public static IReadOnlyList<ObjectPropertyChanged> GetPublicGenericPropertiesChanged<T>(this T previous, T proposedChange,
        string[] namesOfPropertiesToBeIgnored) where T : class
    {
        return GetPublicGenericPropertiesChanged(previous, proposedChange, namesOfPropertiesToBeIgnored, false, null, null);
    }

    /// <summary>
    /// Gets the names of the public properties which values differs between first and second objects.
    /// Considers 'simple' properties AND for complex properties without index, get the simple properties of the children objects.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="previous">The previous object.</param>
    /// <param name="proposedChange">The second object which should be the new one.</param>
    /// <param name="namesOfPropertiesToBeIgnored">The names of the properties to be ignored.</param>
    /// <param name="simpleTypeOnly">if set to <c>true</c> consider simple types only.</param>
    /// <param name="parentTypeString">The parent type string. Meant only for recursive call with simpleTypeOnly set to <c>true</c>.</param>
    /// <param name="secondType">when calling recursively, the current type of T must be clearly defined here, as T will be more generic (using base class).</param>
    /// <returns>
    /// the names of the properties
    /// </returns>
    private static IReadOnlyList<ObjectPropertyChanged> GetPublicGenericPropertiesChanged<T>(this T previous, T proposedChange,
        string[] namesOfPropertiesToBeIgnored, bool simpleTypeOnly, string parentTypeString, Type secondType) where T : class
    {
        List<ObjectPropertyChanged> propertiesChanged = new List<ObjectPropertyChanged>();

        if (previous != null && proposedChange != null)
        {
            var type = secondType == null ? typeof(T) : secondType;
            string typeStr = parentTypeString + type.Name + ".";
            var ignoreList = namesOfPropertiesToBeIgnored.CreateList();
            IEnumerable<IEnumerable<ObjectPropertyChanged>> genericPropertiesChanged =
                from pi in type.GetProperties(BindingFlags.Public | BindingFlags.Instance)
                where !ignoreList.Contains(pi.Name) && pi.GetIndexParameters().Length == 0
                    && (!simpleTypeOnly || simpleTypeOnly && pi.PropertyType.IsSimpleType())
                let firstValue = type.GetProperty(pi.Name).GetValue(previous, null)
                let secondValue = type.GetProperty(pi.Name).GetValue(proposedChange, null)
                where firstValue != secondValue && (firstValue == null || !firstValue.Equals(secondValue))
                let subPropertiesChanged = simpleTypeOnly || pi.PropertyType.IsSimpleType()
                    ? null
                    : GetPublicGenericPropertiesChanged(firstValue, secondValue, namesOfPropertiesToBeIgnored, true, typeStr, pi.PropertyType)
                let objectPropertiesChanged = subPropertiesChanged != null && subPropertiesChanged.Count() > 0
                    ? subPropertiesChanged
                    : (new ObjectPropertyChanged(proposedChange.ToString(), typeStr + pi.Name, firstValue.ToStringOrNull(), secondValue.ToStringOrNull())).CreateList()
                select objectPropertiesChanged;

            if (genericPropertiesChanged != null)
            {   // get items from sub lists
                genericPropertiesChanged.ForEach(a => propertiesChanged.AddRange(a));
            }
        }
        return propertiesChanged;
    }

Using the following class to store comparison results

[System.Serializable]
public class ObjectPropertyChanged
{
    public ObjectPropertyChanged(string objectId, string propertyName, string previousValue, string changedValue)
    {
        ObjectId = objectId;
        PropertyName = propertyName;
        PreviousValue = previousValue;
        ProposedChangedValue = changedValue;
    }

    public string ObjectId { get; set; }

    public string PropertyName { get; set; }

    public string PreviousValue { get; set; }

    public string ProposedChangedValue { get; set; }
}

And a sample unit test:

    [TestMethod()]
    public void GetPublicGenericPropertiesChangedTest1()
    {
        // Define objects to test
        Function func1 = new Function { Id = 1, Description = "func1" };
        Function func2 = new Function { Id = 2, Description = "func2" };
        FunctionAssignment funcAss1 = new FunctionAssignment
        {
            Function = func1,
            Level = 1
        };
        FunctionAssignment funcAss2 = new FunctionAssignment
        {
            Function = func2,
            Level = 2
        };

        // Main test: read properties changed
        var propertiesChanged = Utils.GetPublicGenericPropertiesChanged(funcAss1, funcAss2, null);

        Assert.IsNotNull(propertiesChanged);
        Assert.IsTrue(propertiesChanged.Count == 3);
        Assert.IsTrue(propertiesChanged[0].PropertyName == "FunctionAssignment.Function.Description");
        Assert.IsTrue(propertiesChanged[1].PropertyName == "FunctionAssignment.Function.Id");
        Assert.IsTrue(propertiesChanged[2].PropertyName == "FunctionAssignment.Level");
    }


问:
Issues with wrapping PrismForms NavigationService
In PrismForms we got the problem, that the NavigationStack is empty after navigating to a new page. That means after using the hardware back-button on the SecondPage, the app is closed. Although the back-arrow in the header on Android isnt shown. If looking closely you can see the back-arrow for a short moment after the page is switched. I guess thats before the NavigationStack gets cleared.

To the first page we navigate with the following command in OnInitialized() in our App.xaml.cs which derives from PrismApplication.

```<code>    NavigationService.NavigateAsync("NavigationPage/StartPage");
</code>```

(If only Navigating to „StartPage“ here, the Stack doesnt get cleared.)

That has do to with PageNavigationService.ProcessNavigationForNavigationPage(...) calling
        bool clearNavStack = GetClearNavigationPageNavigationStack(currentPage); and PageNavigationService.ProcessNavigationForContentPage(...) not.

From the StartPage to the next we navigate with NavigateAsync("SecondPage")“. Here the described behaviour appears.

For navigation we use a class which wraps the Prism NavigationService. We hold him as a property and get him via Unity in our constructor:

```<code>    this.PrismNavigation = prismNavigation ?? throw new ArgumentNullException(nameof(prismNavigation));
</code>```

The methods „NavigateAsync“ and „GoBackAsync“, etc. we just pass through.

This way we want to seperate our ViewModel-Project from references to XamarinForms to later be able to use the same ViewModels for for example a WPF-GUI.

Why is the stack beeing cleared by our own NavigationService? If we register the original Prism NavigationService in App.xaml.cs instead, navigating back works as expected again. We found the point in the framework and could avoid the clearing with a drity hack, but that’s against the navigation-logic implemented in PrismForms, but we don’t understand how to do it the correct way.

Every help appreciated!

答:
We edited a few things to get it working after finding some interesting information by Brian Lagunas in the forlast-post here:

https://github.com/PrismLibrary/Prism/issues/591

Although the topic was about something else, it led to improvements for overwriting the Navigation Service.

Remember that in your viewModels the Navigation Service must be named "navigationService" by convention. Also we switched from just holding the Prism Navigation Service as a parameter to deriving from it as suggested in the link above.

```<code>    public class MyNavigationService : UnityPageNavigationService
</code>```

Body:
In PrismForms we got the problem, that the NavigationStack is empty after navigating to a new page. That means after using the hardware back-button on the SecondPage, the app is closed. Although the back-arrow in the header on Android isnt shown. If looking closely you can see the back-arrow for a short moment after the page is switched. I guess thats before the NavigationStack gets cleared.

To the first page we navigate with the following command in OnInitialized() in our App.xaml.cs which derives from PrismApplication.

    NavigationService.NavigateAsync("NavigationPage/StartPage");

(If only Navigating to „StartPage“ here, the Stack doesnt get cleared.)

That has do to with PageNavigationService.ProcessNavigationForNavigationPage(...) calling
        bool clearNavStack = GetClearNavigationPageNavigationStack(currentPage); and PageNavigationService.ProcessNavigationForContentPage(...) not.

From the StartPage to the next we navigate with NavigateAsync("SecondPage")“. Here the described behaviour appears.

For navigation we use a class which wraps the Prism NavigationService. We hold him as a property and get him via Unity in our constructor:

    this.PrismNavigation = prismNavigation ?? throw new ArgumentNullException(nameof(prismNavigation));

The methods „NavigateAsync“ and „GoBackAsync“, etc. we just pass through.

This way we want to seperate our ViewModel-Project from references to XamarinForms to later be able to use the same ViewModels for for example a WPF-GUI.

Why is the stack beeing cleared by our own NavigationService? If we register the original Prism NavigationService in App.xaml.cs instead, navigating back works as expected again. We found the point in the framework and could avoid the clearing with a drity hack, but that’s against the navigation-logic implemented in PrismForms, but we don’t understand how to do it the correct way.

Every help appreciated!

Body:
We edited a few things to get it working after finding some interesting information by Brian Lagunas in the forlast-post here:

https://github.com/PrismLibrary/Prism/issues/591

Although the topic was about something else, it led to improvements for overwriting the Navigation Service.

Remember that in your viewModels the Navigation Service must be named "navigationService" by convention. Also we switched from just holding the Prism Navigation Service as a parameter to deriving from it as suggested in the link above.

    public class MyNavigationService : UnityPageNavigationService


问:
.Exist doesn't wait as per the given timeout in UFT14
I am trying to play my QTP11 scripts in the UFT14 (trail) but for some reason .Exist doesn't wait for the given timeout. Rather it is waiting as per the Object sync timeout project settings if the object doesn't exist. Any reason why?

Like my project's object sync timeout is set at 60 seconds. And when I use something like If ErrorObject.Exist(10) Then ErrorObject.Close -- this should wait for 10 seconds only but rather UFT14 is waiting for full 60 seconds. Is it a bug or is there any extra setting which I have to apply in UFT14 for Exist to wait for the given timeout only?

Edit - On further inspection I found out that this is an issue with Java objects only. So might be a bug in Java addin. Can anyone verify or provide a workaround.

Edit - HP acknowledged that this is an issue. Here is the link if anyone is interested.

https://softwaresupport.hpe.com/group/softwaresupport/search-result/-/facetsearch/document/KM02764499

答:
This is because of the default timeout in UFT.You can change that default timeout as below

```<code>Test Settings -> Run -> Object synchronization timeout
</code>```

Change the "Object synchronization timeout" in seconds.

Or You can do this directly through vbscript code

```<code>Setting("DefaultTimeout") = 5000(This value is in milliseconds)
</code>```

Body:
This is because of the default timeout in UFT.You can change that default timeout as below

Test Settings -> Run -> Object synchronization timeout

Change the "Object synchronization timeout" in seconds.

Or You can do this directly through vbscript code

Setting("DefaultTimeout") = 5000(This value is in milliseconds)


问:
How to get $HOME directory when switching to a different user in bash?
I need to execute part of a bash script as a different user, and inside that user's $HOME directory. However, I'm not sure how to determine this variable. Switching to that user and calling $HOME does not provide the correct location:

```<code># running script as root, but switching to a different user...
su - $different_user
echo $HOME
# returns /root/ but should be /home/myuser
</code>```

Update:

It appears that the issue is with the way that I am trying to switch users in my script:

```<code>$different_user=deploy

# create user
useradd -m -s /bin/bash $different_user

echo "Current user: `whoami`"
# Current user: root

echo "Switching user to $different_user"
# Switching user to deploy

su - $different_user
echo "Current user: `whoami`"
# Current user: root
echo "Current user: `id`"
# Current user: uid=0(root) gid=0(root) groups=0(root)

sudo su $different_user
# Current user: root
# Current user: uid=0(root) gid=0(root) groups=0(root)
</code>```

What is the correct way to switch users and execute commands as a different user in a bash script?

答:
If the user doesn't exist, getent will return an error.

Here's a small shell function that doesn't ignore the exit code of getent:

```<code>get_home() {
  local result; result="$(getent passwd "$1")" || return
  echo $result | cut -d : -f 6
}
</code>```

Here's a usage example:

```<code>da_home="$(get_home missing_user)" || {
  echo 'User does NOT exist!'; exit 1
}

# Now do something with $da_home
echo "Home directory is: '$da_home'"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I need to execute part of a bash script as a different user, and inside that user's $HOME directory. However, I'm not sure how to determine this variable. Switching to that user and calling $HOME does not provide the correct location:

# running script as root, but switching to a different user...
su - $different_user
echo $HOME
# returns /root/ but should be /home/myuser

Update:

It appears that the issue is with the way that I am trying to switch users in my script:

$different_user=deploy

# create user
useradd -m -s /bin/bash $different_user

echo "Current user: `whoami`"
# Current user: root

echo "Switching user to $different_user"
# Switching user to deploy

su - $different_user
echo "Current user: `whoami`"
# Current user: root
echo "Current user: `id`"
# Current user: uid=0(root) gid=0(root) groups=0(root)

sudo su $different_user
# Current user: root
# Current user: uid=0(root) gid=0(root) groups=0(root)

What is the correct way to switch users and execute commands as a different user in a bash script?

Body:
If the user doesn't exist, getent will return an error.

Here's a small shell function that doesn't ignore the exit code of getent:

get_home() {
  local result; result="$(getent passwd "$1")" || return
  echo $result | cut -d : -f 6
}

Here's a usage example:

da_home="$(get_home missing_user)" || {
  echo 'User does NOT exist!'; exit 1
}

# Now do something with $da_home
echo "Home directory is: '$da_home'"


问:
couldn't use variable from included file
this is my code beetwen script tag :
```
        function open()
        {
            file = "Test1.js";
            document.write("<script type='text/javascript' src='"+file+"'></scr"+"ipt>");
            document.getElementById("id").innerHTML = doc;
        }
```
content of Test1.js is "var doc = hello wolrd' ".But why it doesn't showed..

any one can help me??

答:
doc won't be assigned until Test1.js is executed, and that won't be executed until your current script has finished executing.

If you want something to happen after Test1.js has loaded an executed, you'll need to check for its load event.

Body:
this is my code beetwen script tag :

        function open()
        {
            file = "Test1.js";
            document.write("


问:
Why Quality of service set to background runs in main thread?
Why is the below code running in main thread although i have specified qos to background thread?

```<code>func testQueue(){

    let queue = DispatchQueue(label: "com.appcoda.myqueue",qos:.background)
    queue.sync {

        if Thread.isMainThread{
            print("is in main thread")
        }else{
            print("is i background thread")
        }
        for i in 100..<110 {
            print("Ⓜ", i)
        }
    }
}

testQueue()
</code>```

Whenever i try to run the method i get msg in console as is in main threadwhich should not be the case..I am reading in this article.

http://www.appcoda.com/grand-central-dispatch/

See the Getting Started with dispatch queues section.

答:
Here is the Solution :-

Default for main thread is always sync, so no matter what queue you have created with what properties, it will always run in main thread when it is declared as sync.

Refer this Image

Second thing Main thread can run in async as well and it will guarantees that this new task will execute sometime after the current method finishes.

Third thing is when you will try the same code with async then it will work fine.

Refer this image

See the following code and figure it out :-

```<code>func testQueue(){

    let queue = DispatchQueue(label: "com.appcoda.myqueue",qos:.background, attributes:DispatchQueue.Attributes.concurrent)

    queue.sync {   //Sync will always create main thread

        if Thread.isMainThread{
            print("is in main thread")
        }else{
            print("is i background thread")
        }
    }

    DispatchQueue.main.async { //Main thread can be async
        if Thread.isMainThread{
            print("is in main thread")
        }else{
            print("is i background thread")
        }

    }

    if Thread.isMainThread { //default is Main thread sync
        for i in 100..<110 {
            print("Ⓜ", i)
        }
    }
    else{
        print("is i background thread")
    }

    queue.async {   //Here your custom async thread will work
        if Thread.isMainThread{
            print("is in main thread")
        }else{
            print("is i background thread")
        }
    }

}

testQueue()
</code>```

Body:
Why is the below code running in main thread although i have specified qos to background thread?

func testQueue(){

    let queue = DispatchQueue(label: "com.appcoda.myqueue",qos:.background)
    queue.sync {

        if Thread.isMainThread{
            print("is in main thread")
        }else{
            print("is i background thread")
        }
        for i in 100..<110 {
            print("Ⓜ", i)
        }
    }
}

testQueue()

Whenever i try to run the method i get msg in console as is in main threadwhich should not be the case..I am reading in this article.

http://www.appcoda.com/grand-central-dispatch/

See the Getting Started with dispatch queues section.

Body:
Here is the Solution :-

Default for main thread is always sync, so no matter what queue you have created with what properties, it will always run in main thread when it is declared as sync.

Refer this Image

Second thing Main thread can run in async as well and it will guarantees that this new task will execute sometime after the current method finishes.

Third thing is when you will try the same code with async then it will work fine.

Refer this image

See the following code and figure it out :-

func testQueue(){

    let queue = DispatchQueue(label: "com.appcoda.myqueue",qos:.background, attributes:DispatchQueue.Attributes.concurrent)

    queue.sync {   //Sync will always create main thread

        if Thread.isMainThread{
            print("is in main thread")
        }else{
            print("is i background thread")
        }
    }

    DispatchQueue.main.async { //Main thread can be async
        if Thread.isMainThread{
            print("is in main thread")
        }else{
            print("is i background thread")
        }

    }

    if Thread.isMainThread { //default is Main thread sync
        for i in 100..<110 {
            print("Ⓜ", i)
        }
    }
    else{
        print("is i background thread")
    }

    queue.async {   //Here your custom async thread will work
        if Thread.isMainThread{
            print("is in main thread")
        }else{
            print("is i background thread")
        }
    }

}

testQueue()


问:
How to access performance object of every resource in a web page?
I can see, in Chrome Developer tools, loading time, time it took to get a particular resource from server and other info, for all of the resources in a webpage.

I want to capture these stats using JavaScript. How is it possible?

there is window.performance object available, but only for the requested page, not for page resources.
Is there any way to access performance object of all of the page resources.

答:
window.performance.getEntries()
may return not all resources. after bufferful some records is disapear
need check it before it happend

head code part

```<code>var storedEntries = [];
var updateStoredEntries = p => {
  storedEntries.concat(
    p.getEntries().filter(rec => /yourRegExp/.test(rec.name))
  )
};
performance.addEventListener('resourcetimingbufferfull', e => {
  updateStoredEntries(e.target)
});
</code>```

...
later part

```<code>updateStoredEntries(performance)
</code>```

Body:
window.performance.getEntries()
may return not all resources. after bufferful some records is disapear
need check it before it happend

head code part

var storedEntries = [];
var updateStoredEntries = p => {
  storedEntries.concat(
    p.getEntries().filter(rec => /yourRegExp/.test(rec.name))
  )
};
performance.addEventListener('resourcetimingbufferfull', e => {
  updateStoredEntries(e.target)
});

...
later part

updateStoredEntries(performance)


问:
Showing Splash screen in android apps
Have you ever seen the page in many apps that before launching the first activity appears and somehow it is like a waiting page ?! I am beginner to android and when I click on my apps , first a blank white page appears then after 3 seconds main activity comes out . but in many apps there is a kind of customised page before the first activity that is like a progress bar or sth . how can I customise that not so beautiful blank page before starting my app?! Thanx in advance . </p>

答:
Technically thing you are talking about is called splash screen.

Splash screen is used to show cold start where we can make our things ready to run an application. Google advocated to use it.

There are few approaches to show splash screen.

You can use CountDownTimer like this. In SplashActivity.java

```<code>private int TIME_OUT = 3000;</p>

```CountDownTimer countDownTimer = new CountDownTimer(TIME_OUT, TIME_OUT) {

@Override
public void onTick(long millisUntilFinished)
{
    // Leave this
}

@Override
public void onFinish()
{
    // Start your app main activity
    Intent i = new Intent(SplashScreen.this, MainActivity.class);
    startActivity(i);

    // close this activity
    finish();
}
```

<p>}.start();</code>```

You can use Handler like this. In SplashActivity.java

```<code>private static int TIME_OUT = 3000;

new Handler().postDelayed(new Runnable()
{
    @Override
    public void run() {
            Intent i = new Intent(SplashScreen.this, MainActivity.class);
            startActivity(i);

            finish();
        }
</code>```

}, TIME_OUT);

Using theme - correct way of doing

Add background_splash.xml file in drawable folder

```<code><layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:drawable="@color/gray"/>
    <item>
       <bitmap
          android:gravity="center"
          android:src="@mipmap/ic_launcher"/>
    </item>
</layer-list>
</code>```

Add these lines in styles.xml

```<code><style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
</style>

<style name="SplashTheme" parent="Theme.AppCompat.NoActionBar">
    <item name="android:windowBackground">@drawable/background_splash</item>
</style>
</code>```

Add these lines in AndroidManifest.xml

```<code><activity
    android:name=".SplashActivity"
    android:theme="@style/SplashTheme">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>
</code>```

Finally add an activity called SplashActivity.java and add these code

```<code>public class SplashActivity extends AppCompatActivity
{
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();
    }
}
</code>```

Title: Showing Splash screen in android apps

Body:
Technically thing you are talking about is called splash screen.

Splash screen is used to show cold start where we can make our things ready to run an application. Google advocated to use it.

There are few approaches to show splash screen.

You can use CountDownTimer like this. In SplashActivity.java

private int TIME_OUT = 3000;

CountDownTimer countDownTimer = new CountDownTimer(TIME_OUT, TIME_OUT) {

@Override
public void onTick(long millisUntilFinished)
{
    // Leave this
}

@Override
public void onFinish()
{
    // Start your app main activity
    Intent i = new Intent(SplashScreen.this, MainActivity.class);
    startActivity(i);

    // close this activity
    finish();
}

}.start();

You can use Handler like this. In SplashActivity.java

private static int TIME_OUT = 3000;

new Handler().postDelayed(new Runnable()
{
    @Override
    public void run() {
            Intent i = new Intent(SplashScreen.this, MainActivity.class);
            startActivity(i);

            finish();
        }

}, TIME_OUT);

Using theme - correct way of doing

Add background_splash.xml file in drawable folder

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:drawable="@color/gray"/>
    <item>
       <bitmap
          android:gravity="center"
          android:src="@mipmap/ic_launcher"/>
    </item>
</layer-list>

Add these lines in styles.xml

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
</style>

<style name="SplashTheme" parent="Theme.AppCompat.NoActionBar">
    <item name="android:windowBackground">@drawable/background_splash</item>
</style>

Add these lines in AndroidManifest.xml

<activity
    android:name=".SplashActivity"
    android:theme="@style/SplashTheme">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

Finally add an activity called SplashActivity.java and add these code

public class SplashActivity extends AppCompatActivity
{
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();
    }
}


问:
How can I optimise this eloquent query to remove similar queries
An appointment can have many statuses, but the last created relation between appointment and status is the current status of the appointment. In my Appointment Datatable I want to display the related Agent, InstructionType, SignUpCustomer and the latest status. I want to paginate those records at 10 per page.

The relevant models are:

Appointment ( belongsTo agent, instruction_type and sign_up_customer, belongsToMany status)

Agent

InstructionType

SignUpCustomer

I have this query in my controller, which produces a result I send to Datatables.

```<code>$query = Appointment::with(['agent', 'instruction_type', 'sign_up_customer']);
            $query->with(['statuses' => function ($query) {
                $query->latest()->first();
            }]);
            $table = Datatables::of($query);
</code>```

It is producing these two statements, the first one is fine, I don't need the last one. How can I optimise the query to remove that last statement?

```<code>select `statuses`.*, `appointment_status`.`appointment_id` as `pivot_appointment_id`, `appointment_status`.`status_id` as `pivot_status_id`, `appointment_status`.`created_at` as `pivot_created_at`, `appointment_status`.`updated_at` as `pivot_updated_at` from `statuses` inner join `appointment_status` on `statuses`.`id` = `appointment_status`.`status_id` where `appointment_status`.`appointment_id` in ('2') order by `created_at` desc limit 1

select `statuses`.*, `appointment_status`.`appointment_id` as `pivot_appointment_id`, `appointment_status`.`status_id` as `pivot_status_id`, `appointment_status`.`created_at` as `pivot_created_at`, `appointment_status`.`updated_at` as `pivot_updated_at`, `appointment_status`.`appointment_id` as `pivot_appointment_id`, `appointment_status`.`status_id` as `pivot_status_id`, `appointment_status`.`created_at` as `pivot_created_at`, `appointment_status`.`updated_at` as `pivot_updated_at` from `statuses` inner join `appointment_status` on `statuses`.`id` = `appointment_status`.`status_id` where `appointment_status`.`appointment_id` in ('2') order by `created_at` desc limit 1
</code>```

I've also tried this:

Model:

```<code>/**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function statuses()
    {
        return $this->belongsToMany(Status::class, 'appointment_status')->withTimestamps();
    }

    public function latestStatus()
    {
        return $this->statuses()->latest()->first();
    }
</code>```

Controller:

```<code>$query = Appointment::with(['agent', 'instruction_type', 'sign_up_customer', 'latestStatus']);
            $table = Datatables::of($query);
</code>```

But i get this error: BadMethodCallException in Builder.php line 2445:
Call to undefined method Illuminate\Database\Query\Builder::addEagerConstraints()

答:
Can you not do this using a local scope? https://laravel.com/docs/5.4/eloquent#local-scopes

```<code>public function scopeLatest($query)
{
    return $query->orderBy('created_at', 'DESC')->offset(0)->limit(1);
}
</code>```

I've not actually done this before, but I see no reason why it wouldn't work (I also have no idea how optimised the resulting query would be).

Body:
An appointment can have many statuses, but the last created relation between appointment and status is the current status of the appointment. In my Appointment Datatable I want to display the related Agent, InstructionType, SignUpCustomer and the latest status. I want to paginate those records at 10 per page.

The relevant models are:

Appointment ( belongsTo agent, instruction_type and sign_up_customer, belongsToMany status)

Agent

InstructionType

SignUpCustomer

I have this query in my controller, which produces a result I send to Datatables.

$query = Appointment::with(['agent', 'instruction_type', 'sign_up_customer']);
            $query->with(['statuses' => function ($query) {
                $query->latest()->first();
            }]);
            $table = Datatables::of($query);

It is producing these two statements, the first one is fine, I don't need the last one. How can I optimise the query to remove that last statement?

select `statuses`.*, `appointment_status`.`appointment_id` as `pivot_appointment_id`, `appointment_status`.`status_id` as `pivot_status_id`, `appointment_status`.`created_at` as `pivot_created_at`, `appointment_status`.`updated_at` as `pivot_updated_at` from `statuses` inner join `appointment_status` on `statuses`.`id` = `appointment_status`.`status_id` where `appointment_status`.`appointment_id` in ('2') order by `created_at` desc limit 1

select `statuses`.*, `appointment_status`.`appointment_id` as `pivot_appointment_id`, `appointment_status`.`status_id` as `pivot_status_id`, `appointment_status`.`created_at` as `pivot_created_at`, `appointment_status`.`updated_at` as `pivot_updated_at`, `appointment_status`.`appointment_id` as `pivot_appointment_id`, `appointment_status`.`status_id` as `pivot_status_id`, `appointment_status`.`created_at` as `pivot_created_at`, `appointment_status`.`updated_at` as `pivot_updated_at` from `statuses` inner join `appointment_status` on `statuses`.`id` = `appointment_status`.`status_id` where `appointment_status`.`appointment_id` in ('2') order by `created_at` desc limit 1

I've also tried this:

Model:

/**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function statuses()
    {
        return $this->belongsToMany(Status::class, 'appointment_status')->withTimestamps();
    }

    public function latestStatus()
    {
        return $this->statuses()->latest()->first();
    }

Controller:

$query = Appointment::with(['agent', 'instruction_type', 'sign_up_customer', 'latestStatus']);
            $table = Datatables::of($query);

But i get this error: BadMethodCallException in Builder.php line 2445:
Call to undefined method Illuminate\Database\Query\Builder::addEagerConstraints()

Body:
Can you not do this using a local scope? https://laravel.com/docs/5.4/eloquent#local-scopes

public function scopeLatest($query)
{
    return $query->orderBy('created_at', 'DESC')->offset(0)->limit(1);
}

I've not actually done this before, but I see no reason why it wouldn't work (I also have no idea how optimised the resulting query would be).


问:
Can't catch NullReferenceException
First post here, so sorry if I've got some of the niceties wrong. I'm trying to catch an exception where the user enters an invalid (non-existent) employee. I've tried many different variations, but the error is never raised. Instead the code just terminates, in this case it will drop out after the following lines:

```<code> MyPostSalary = Convert.ToDouble(Console.ReadLine());
 Console.WriteLine();
</code>```

Can anyone see what I'm doing wrong?

Complete code:

```<code>       Console.Write("Employee ID: ");
        myEID = Console.ReadLine();

        try
        {
            Console.Write("Post ID: ");
            myPID = Console.ReadLine();

            if ((myEmployees[myEID] is MonthlyPaidEmployee) || (myEmployees[myEID] isWeeklyPaidEmployee))
            {

                Console.Write("Post Name: ");
                MyPostName = Console.ReadLine();
                Console.Write("Post Start Date: ");
                MyPostStartDate = Convert.ToDateTime(Console.ReadLine());
                Console.Write("Post End Date: ");
                MyPostEndDate = Convert.ToDateTime(Console.ReadLine());
                Console.Write("Post Salary: ");
                MyPostSalary = Convert.ToDouble(Console.ReadLine());
                Console.WriteLine();

                myPost = new Post(myPID, MyPostName, MyPostStartDate, MyPostEndDate, MyPostSalary);

                if (myEmployees[myEID] is MonthlyPaidEmployee)
                {
                    myMonthlyEmp = (MonthlyPaidEmployee)myEmployees[myEID];
                    myMonthlyEmp.PostHistory.Add(myPID, myPost);
                }

                if (myEmployees[myEID] is WeeklyPaidEmployee)
                {
                    myWeeklyEmp = (WeeklyPaidEmployee)myEmployees[myEID];
                    myWeeklyEmp.WeeklyPaidEmployeePostHistory.Add(myPID, myPost);
                }

            }

        }
        catch (NullReferenceException ex)
        {

            Console.WriteLine("Employee ID does not exist.");
            Console.WriteLine(ex.Message);
            Console.WriteLine();
            Console.WriteLine("Press any key to continue");
            Console.ReadLine();

        }
</code>```

答:
Are you in debug on Visual Studio (or your IDE)?
If yes, it maybe you are catching the exception but the IDE is set to show a warning message when the exception raises...
Try to run your application outside the IDE, if it works you can disable warning when NullReferenceExceptions raise , but it is quite dangerous. To do this look for "Exceptions settings" in Visual Studio (or something like this, I'm not sure because I use the italian version).</p>

Title: Can't catch NullReferenceException

Body:
First post here, so sorry if I've got some of the niceties wrong. I'm trying to catch an exception where the user enters an invalid (non-existent) employee. I've tried many different variations, but the error is never raised. Instead the code just terminates, in this case it will drop out after the following lines:

 MyPostSalary = Convert.ToDouble(Console.ReadLine());
 Console.WriteLine();

Can anyone see what I'm doing wrong?

Complete code:

       Console.Write("Employee ID: ");
        myEID = Console.ReadLine();

        try
        {
            Console.Write("Post ID: ");
            myPID = Console.ReadLine();

            if ((myEmployees[myEID] is MonthlyPaidEmployee) || (myEmployees[myEID] isWeeklyPaidEmployee))
            {

                Console.Write("Post Name: ");
                MyPostName = Console.ReadLine();
                Console.Write("Post Start Date: ");
                MyPostStartDate = Convert.ToDateTime(Console.ReadLine());
                Console.Write("Post End Date: ");
                MyPostEndDate = Convert.ToDateTime(Console.ReadLine());
                Console.Write("Post Salary: ");
                MyPostSalary = Convert.ToDouble(Console.ReadLine());
                Console.WriteLine();

                myPost = new Post(myPID, MyPostName, MyPostStartDate, MyPostEndDate, MyPostSalary);

                if (myEmployees[myEID] is MonthlyPaidEmployee)
                {
                    myMonthlyEmp = (MonthlyPaidEmployee)myEmployees[myEID];
                    myMonthlyEmp.PostHistory.Add(myPID, myPost);
                }

                if (myEmployees[myEID] is WeeklyPaidEmployee)
                {
                    myWeeklyEmp = (WeeklyPaidEmployee)myEmployees[myEID];
                    myWeeklyEmp.WeeklyPaidEmployeePostHistory.Add(myPID, myPost);
                }

            }

        }
        catch (NullReferenceException ex)
        {

            Console.WriteLine("Employee ID does not exist.");
            Console.WriteLine(ex.Message);
            Console.WriteLine();
            Console.WriteLine("Press any key to continue");
            Console.ReadLine();

        }


问:
QRCode scanning issue
I am using Zxing SDK for scanning(decoding) QRCodes, it works well, but it does not scan some QRCode especially for smaller size QRCodes.

Any help?

答:
add these types of codes to the scanning class , it will support all types of codes. let supportedCodeTypes = [AVMetadataObjectTypeUPCECode,
                              AVMetadataObjectTypeCode39Code,
                              AVMetadataObjectTypeCode39Mod43Code,
                              AVMetadataObjectTypeCode93Code,
                              AVMetadataObjectTypeCode128Code,
                              AVMetadataObjectTypeEAN8Code,
                              AVMetadataObjectTypeEAN13Code,
                              AVMetadataObjectTypeAztecCode,
                              AVMetadataObjectTypePDF417Code,
                              AVMetadataObjectTypeQRCode]

Title: QRCode scanning issue


问:
XML schema error with Jetty
I got a problem with my spring configuration when I run it in jetty. I used the exact same file in tomcat without any problems. The error i get is the following.

```<code>org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 6 in XML document from ServletContext resource [/WEB-INF/web-application-context.xml] is invalid; nested exception is org.xml.sax.SAXParseException: s4s-elt-character: Non-whitespace characters are not allowed in schema elements other than 'xs:appinfo' and 'xs:documentation'. Saw 'SpringSource.org | '.
Caused by: org.xml.sax.SAXParseException: s4s-elt-character: Non-whitespace characters are not allowed in schema elements other than 'xs:appinfo' and 'xs:documentation'. Saw 'SpringSource.org | '.
</code>```

My schema looks like this.

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.0.5.xsd">
</code>```

I have no idea what can be wrong. Have tested it with 2 different configurations and both gave this error.

答:
The following URL seems invalid, and redirects to springsource.org

```<code>http://www.springframework.org/schema/security/spring-security-3.0.5.xsd
</code>```

Can you try that one?

```<code>http://www.springframework.org/schema/security/spring-security-3.0.4.xsd
</code>```

Title: XML schema error with Jetty

Body:
I got a problem with my spring configuration when I run it in jetty. I used the exact same file in tomcat without any problems. The error i get is the following.

org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 6 in XML document from ServletContext resource [/WEB-INF/web-application-context.xml] is invalid; nested exception is org.xml.sax.SAXParseException: s4s-elt-character: Non-whitespace characters are not allowed in schema elements other than 'xs:appinfo' and 'xs:documentation'. Saw 'SpringSource.org | '.
Caused by: org.xml.sax.SAXParseException: s4s-elt-character: Non-whitespace characters are not allowed in schema elements other than 'xs:appinfo' and 'xs:documentation'. Saw 'SpringSource.org | '.

My schema looks like this.

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.0.5.xsd">

I have no idea what can be wrong. Have tested it with 2 different configurations and both gave this error.

Body:
The following URL seems invalid, and redirects to springsource.org

http://www.springframework.org/schema/security/spring-security-3.0.5.xsd

Can you try that one?

http://www.springframework.org/schema/security/spring-security-3.0.4.xsd


问:
Why Is my "If Else" statement getting skipped?
I am working on a script to allow my sys admins to make changes to an ACL without having to drill down to the folder level.  So far, everything is executing as intended except for my first "If..Else" statement in my first switch.  It gets skipped entirely and moves on to asking for the account name and I cannot figure out why.

Does anyone have any ideas?

```<code>$account     = $null
$accesslevel = $null
$accesstype  = $null
$acl = $null

$title  = Write-Host "Modify ACL" -ForegroundColor Green
$message  = Write-Host "Select the action to initiate:" -ForegroundColor Cyan

$add         = New-Object System.Management.Automation.Host.ChoiceDescription "&Add Permissions", "Add Permissions"
$remove      = New-Object System.Management.Automation.Host.ChoiceDescription "&Remove Permissions", "Remove Permissions"

$options  = [System.Management.Automation.Host.ChoiceDescription[]]($add, $remove)

$selectAction = $Host.UI.PromptForChoice($title, $message, $options, 0)
switch($selectAction){
    0{
        $pathPrompt  = Write-Host "Please enter path to file/folder:" -ForegroundColor Green
        $path        = Read-Host
        $test        = Test-Path $path | Out-Null

        if($test -eq $false){
            Write-Host "ERROR! Invalid Path!" -ForegroundColor Red
            Break
        }Else{
            Write-Host "Getting ACL on`r"$path -ForegroundColor Green
            $acl = get-acl $path
        }

        if($account -eq $null){
            Write-Host "Enter Account (ex. Domain\Account)" -ForegroundColor Green
            $account = Read-Host
            }

        $title2   = Write-Host "Permission Levels" -ForegroundColor Green
        $message2 = Write-Host "Select the appropriate permissions to apply:" -ForegroundColor Cyan

        $fullControl = New-Object System.Management.Automation.Host.ChoiceDescription "&FullControl", "FullControl"
        $modify      = New-Object System.Management.Automation.Host.ChoiceDescription "&Modify", "Modify"
        $readExecute = New-Object System.Management.Automation.Host.ChoiceDescription "&ReadAndExecute", "ReadAndExecute"
        $read        = New-Object System.Management.Automation.Host.ChoiceDescription "&Read", "Read"
        $write       = New-Object System.Management.Automation.Host.ChoiceDescription "&Write", "Write"
        $readWrite   = New-Object System.Management.Automation.Host.ChoiceDescription "&Read, Write", "Read, Write"
        $list        = New-Object System.Management.Automation.Host.ChoiceDescription "&List", "List"

        $options2 = [System.Management.Automation.Host.ChoiceDescription[]]($fullControl, $modify, $readExecute, $read, $write, $readWrite, $list)

        do{
            $selectAction2 = $Host.UI.PromptForChoice($title2, $message2, $options2, 1)
                switch($selectAction2){
                    0{$accesslevel = 'FullControl'}
                    1{$accesslevel = 'Modify'}
                    2{$accesslevel = 'ReadandExecute'}
                    3{$accesslevel = 'Read'}
                    4{$accesslevel = 'Write'}
                    5{$accesslevel = 'Read, Write'}
                    6{$accesslevel = 'List'}
                }
        }Until($accesslevel -ne $null)

        $title3   = Write-Host "Access Type" -ForegroundColor Green
        $message3 = Write-Host "Select the type of access:" -ForegroundColor Cyan

        $allow = New-Object System.Management.Automation.Host.ChoiceDescription "&Allow", "Allow"
        $deny  = New-Object System.Management.Automation.Host.ChoiceDescription "&Deny", "Deny"

        $options3 = [System.Management.Automation.Host.ChoiceDescription[]]($allow, $deny)

        do{
            $selectAction3 = $Host.UI.PromptForChoice($title3, $message3, $options3, 0)
                switch($selectAction3){
                    0{$accesstype = 'Allow'}
                    1{$accesstype = 'Deny'}
                }
        }Until($accesstype -ne $null)

        Write-Host "Setting ACL on"$path -ForegroundColor Yellow

        $arguments = $account, $accesslevel, $accesstype

        Try{
            $accessrule = New-Object System.Security.AccessControl.FileSystemAccessRule $arguments
                $acl.SetAccessRule($accessrule)
        }Catch{
            Write-Host "Exception thrown : $($error[0].exception.message)"
        }Finally{
            $acl | set-acl $path
        }

        Write-Host "ACL settings have been completed." -ForegroundColor Cyan
    }
    1{
        $pathPrompt
        $path
        $test | Out-Null

        if($test -eq $false){
            Write-Host "ERROR! Invalid Path!" -ForegroundColor Red
            Break
        }Else{
            Write-Host "Getting ACL on`r"$path -ForegroundColor Green
            $acl = get-acl $path
        }
        if($account -eq $null){
            $account = Read-Host "Enter Account (ex. Domain\Account)" -ForegroundColor Green
            }
    }
}
</code>```

答:
Your if-else is working correctly as you have written it. What you have written, however, is not what you want.

First: In the Write-Host in the else clause, you do not want to use the escaped `r</code>; you want to use an escaped <code>`n, or perhaps nothing at all. `r</code> indicates a return-to-start-of-line but not go-to-next-line; <code>`n indicates return-to-start-of-line-and-go-to-next-line. The repeating of the entered path in green in your example above is a strong hint that that Write-Host is being executed.

Second, your Test-Path causes $test to have no value, because you are sending the results to the null device instead of allowing it to be returned to the statement for assignment to the variable. Remove the | Out-Null.

Body:
I am working on a script to allow my sys admins to make changes to an ACL without having to drill down to the folder level.  So far, everything is executing as intended except for my first "If..Else" statement in my first switch.  It gets skipped entirely and moves on to asking for the account name and I cannot figure out why.

Does anyone have any ideas?

$account     = $null
$accesslevel = $null
$accesstype  = $null
$acl = $null

$title  = Write-Host "Modify ACL" -ForegroundColor Green
$message  = Write-Host "Select the action to initiate:" -ForegroundColor Cyan

$add         = New-Object System.Management.Automation.Host.ChoiceDescription "&Add Permissions", "Add Permissions"
$remove      = New-Object System.Management.Automation.Host.ChoiceDescription "&Remove Permissions", "Remove Permissions"

$options  = [System.Management.Automation.Host.ChoiceDescription[]]($add, $remove)

$selectAction = $Host.UI.PromptForChoice($title, $message, $options, 0)
switch($selectAction){
    0{
        $pathPrompt  = Write-Host "Please enter path to file/folder:" -ForegroundColor Green
        $path        = Read-Host
        $test        = Test-Path $path | Out-Null

        if($test -eq $false){
            Write-Host "ERROR! Invalid Path!" -ForegroundColor Red
            Break
        }Else{
            Write-Host "Getting ACL on`r"$path -ForegroundColor Green
            $acl = get-acl $path
        }

        if($account -eq $null){
            Write-Host "Enter Account (ex. Domain\Account)" -ForegroundColor Green
            $account = Read-Host
            }

        $title2   = Write-Host "Permission Levels" -ForegroundColor Green
        $message2 = Write-Host "Select the appropriate permissions to apply:" -ForegroundColor Cyan

        $fullControl = New-Object System.Management.Automation.Host.ChoiceDescription "&FullControl", "FullControl"
        $modify      = New-Object System.Management.Automation.Host.ChoiceDescription "&Modify", "Modify"
        $readExecute = New-Object System.Management.Automation.Host.ChoiceDescription "&ReadAndExecute", "ReadAndExecute"
        $read        = New-Object System.Management.Automation.Host.ChoiceDescription "&Read", "Read"
        $write       = New-Object System.Management.Automation.Host.ChoiceDescription "&Write", "Write"
        $readWrite   = New-Object System.Management.Automation.Host.ChoiceDescription "&Read, Write", "Read, Write"
        $list        = New-Object System.Management.Automation.Host.ChoiceDescription "&List", "List"

        $options2 = [System.Management.Automation.Host.ChoiceDescription[]]($fullControl, $modify, $readExecute, $read, $write, $readWrite, $list)

        do{
            $selectAction2 = $Host.UI.PromptForChoice($title2, $message2, $options2, 1)
                switch($selectAction2){
                    0{$accesslevel = 'FullControl'}
                    1{$accesslevel = 'Modify'}
                    2{$accesslevel = 'ReadandExecute'}
                    3{$accesslevel = 'Read'}
                    4{$accesslevel = 'Write'}
                    5{$accesslevel = 'Read, Write'}
                    6{$accesslevel = 'List'}
                }
        }Until($accesslevel -ne $null)

        $title3   = Write-Host "Access Type" -ForegroundColor Green
        $message3 = Write-Host "Select the type of access:" -ForegroundColor Cyan

        $allow = New-Object System.Management.Automation.Host.ChoiceDescription "&Allow", "Allow"
        $deny  = New-Object System.Management.Automation.Host.ChoiceDescription "&Deny", "Deny"

        $options3 = [System.Management.Automation.Host.ChoiceDescription[]]($allow, $deny)

        do{
            $selectAction3 = $Host.UI.PromptForChoice($title3, $message3, $options3, 0)
                switch($selectAction3){
                    0{$accesstype = 'Allow'}
                    1{$accesstype = 'Deny'}
                }
        }Until($accesstype -ne $null)

        Write-Host "Setting ACL on"$path -ForegroundColor Yellow

        $arguments = $account, $accesslevel, $accesstype

        Try{
            $accessrule = New-Object System.Security.AccessControl.FileSystemAccessRule $arguments
                $acl.SetAccessRule($accessrule)
        }Catch{
            Write-Host "Exception thrown : $($error[0].exception.message)"
        }Finally{
            $acl | set-acl $path
        }

        Write-Host "ACL settings have been completed." -ForegroundColor Cyan
    }
    1{
        $pathPrompt
        $path
        $test | Out-Null

        if($test -eq $false){
            Write-Host "ERROR! Invalid Path!" -ForegroundColor Red
            Break
        }Else{
            Write-Host "Getting ACL on`r"$path -ForegroundColor Green
            $acl = get-acl $path
        }
        if($account -eq $null){
            $account = Read-Host "Enter Account (ex. Domain\Account)" -ForegroundColor Green
            }
    }
}


问:
How to get Chef api credentials?
I am trying to use following script:
https://github.com/evanlok/chef-node-cleaner

Here the following variables are required:

CHEF_API_ENDPOINT
CHEF_API_CLIENT
CHEF_API_KEY

I could not find what would be the value of these variables.
CHEF_API_ENDPOINT may be the chef server url and CHEF_API_KEY is validator key. Not sure about these.
Please suggest what would be the value of these variables or how to get the value of these variables.
Thanks in advance!

答:
You would get them from the configuration of your CHEF server.

Please see the chef server api setup at https://docs.chef.io/api_chef_server.html

Title: How to get Chef api credentials?


问:
Can't display characters
I have a piece of code that should output some text, but when I run it an empty window pops up. I want to create characters on a window. Can someone tell me why this doesn't happen?

Here is the code:

```<code>#include "stdafx.h"
#include <iostream>

using namespace std;

int main() {
    char str[] = "Hello C++";

    cout << "Value of str is : " << str << endl;

    return 0;
}
</code>```

Thanks

答:
Your code is fine -- but the window will automatically close when the code finishes its execution.

Consider adding a cin at the end of your code to prevent the window from closing.

```<code>int t;
cin >> t;
</code>```

Title: Can't display characters

Body:
I have a piece of code that should output some text, but when I run it an empty window pops up. I want to create characters on a window. Can someone tell me why this doesn't happen?

Here is the code:

#include "stdafx.h"
#include <iostream>

using namespace std;

int main() {
    char str[] = "Hello C++";

    cout << "Value of str is : " << str << endl;

    return 0;
}

Thanks

Body:
Your code is fine -- but the window will automatically close when the code finishes its execution.

Consider adding a cin at the end of your code to prevent the window from closing.

int t;
cin >> t;


问:
ASP.NET email validator regex
Does anyone know what the regex used by the email validator in ASP.NET is?</p>

答:
Apart from the client side validation with a Validator, I also recommend doing server side validation as well.</p>

```<code>bool isValidEmail(string input)
{
    try
    {
        var email = new System.Net.Mail.MailAddress(input);
        return true;
    }
    catch
    {
        return false;
    }
}
</code>```

Title: ASP.NET email validator regex

Body:
Apart from the client side validation with a Validator, I also recommend doing server side validation as well.

bool isValidEmail(string input)
{
    try
    {
        var email = new System.Net.Mail.MailAddress(input);
        return true;
    }
    catch
    {
        return false;
    }
}


问:
My syntax error when i want to make if conditional sql
why this is happen to me? I dont know why my syntax get wrong when i want to make if conditional in my sql

```<code>IF quantity <= 0
    UPDATE tbl_books
    SET status = 'Not Available'
ELSE
    UPDATE tbl_books
    SET quantity = quantity -1
    WHERE isbn = 'tes1'
</code>```

I got an error like this

```<code>#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'IF 'quantity' <= 0 UPDATE tbl_books SET status = 'Not Available' ELSE UPDA' at line 1
</code>```

答:
Yes, that's cause you can't use IF .. ELSE procedural construct in a normal SQL query other than in a stored procedure or stored function. You can use a conditional SET like

```<code>UPDATE tbl_books
SET status = case when quantity <= 0 then 'Not Available' else status end,
quantity = case when quantity > 0 then quantity -1 else quantity end
WHERE isbn = 'tes1';
</code>```

Body:
why this is happen to me? I dont know why my syntax get wrong when i want to make if conditional in my sql

IF quantity <= 0
    UPDATE tbl_books
    SET status = 'Not Available'
ELSE
    UPDATE tbl_books
    SET quantity = quantity -1
    WHERE isbn = 'tes1'

I got an error like this

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'IF 'quantity' <= 0 UPDATE tbl_books SET status = 'Not Available' ELSE UPDA' at line 1

Body:
Yes, that's cause you can't use IF .. ELSE procedural construct in a normal SQL query other than in a stored procedure or stored function. You can use a conditional SET like

UPDATE tbl_books
SET status = case when quantity <= 0 then 'Not Available' else status end,
quantity = case when quantity > 0 then quantity -1 else quantity end
WHERE isbn = 'tes1';