问:
Exception with background task on Sonar6.5
I'm using onarQube 6.5 (6.5.0.27846) and after a successful analysis it's time to sonar backgroud task to compute but I encounter this excetpion:</p>

```<code>org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned by selectOne(), but found: 2
    at org.apache.ibatis.session.defaults.DefaultSqlSession.selectOne(DefaultSqlSession.java:81)
    at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:82)
    at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:59)
    at com.sun.proxy.$Proxy41.select(Unknown Source)
    at org.sonar.db.source.FileSourceDao.selectSourceByFileUuid(FileSourceDao.java:44)
    at org.sonar.server.computation.task.projectanalysis.filemove.FileMoveDetectionStep.getFile(FileMoveDetectionStep.java:233)
    at org.sonar.server.computation.task.projectanalysis.filemove.FileMoveDetectionStep.computeScoreMatrix(FileMoveDetectionStep.java:206)
    at org.sonar.server.computation.task.projectanalysis.filemove.FileMoveDetectionStep.execute(FileMoveDetectionStep.java:127)
    at org.sonar.server.computation.task.step.ComputationStepExecutor.executeSteps(ComputationStepExecutor.java:64)
    at org.sonar.server.computation.task.step.ComputationStepExecutor.execute(ComputationStepExecutor.java:52)
    at org.sonar.server.computation.task.projectanalysis.taskprocessor.ReportTaskProcessor.process(ReportTaskProcessor.java:75)
    at org.sonar.ce.taskprocessor.CeWorkerImpl.executeTask(CeWorkerImpl.java:92)
    at org.sonar.ce.taskprocessor.CeWorkerImpl.call(CeWorkerImpl.java:59)
    at org.sonar.ce.taskprocessor.CeWorkerImpl.call(CeWorkerImpl.java:35)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
</code>```

答:
Bumped into the same issue. It is caused by 'invalid' records in FILE_SOURCES
table :

having an already used FILE_UUID

referencing a project that is not a Sonar 'top project'

Fixed with this query :

```<code>delete
from FILE_SOURCES
where PROJECT_UUID not in
(
  select distinct PROJECT_UUID from PROJECTS
  where SCOPE = 'PRJ' and QUALIFIER = 'TRK'
);
</code>```

Body:
I'm using onarQube 6.5 (6.5.0.27846) and after a successful analysis it's time to sonar backgroud task to compute but I encounter this excetpion:

org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned by selectOne(), but found: 2
    at org.apache.ibatis.session.defaults.DefaultSqlSession.selectOne(DefaultSqlSession.java:81)
    at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:82)
    at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:59)
    at com.sun.proxy.$Proxy41.select(Unknown Source)
    at org.sonar.db.source.FileSourceDao.selectSourceByFileUuid(FileSourceDao.java:44)
    at org.sonar.server.computation.task.projectanalysis.filemove.FileMoveDetectionStep.getFile(FileMoveDetectionStep.java:233)
    at org.sonar.server.computation.task.projectanalysis.filemove.FileMoveDetectionStep.computeScoreMatrix(FileMoveDetectionStep.java:206)
    at org.sonar.server.computation.task.projectanalysis.filemove.FileMoveDetectionStep.execute(FileMoveDetectionStep.java:127)
    at org.sonar.server.computation.task.step.ComputationStepExecutor.executeSteps(ComputationStepExecutor.java:64)
    at org.sonar.server.computation.task.step.ComputationStepExecutor.execute(ComputationStepExecutor.java:52)
    at org.sonar.server.computation.task.projectanalysis.taskprocessor.ReportTaskProcessor.process(ReportTaskProcessor.java:75)
    at org.sonar.ce.taskprocessor.CeWorkerImpl.executeTask(CeWorkerImpl.java:92)
    at org.sonar.ce.taskprocessor.CeWorkerImpl.call(CeWorkerImpl.java:59)
    at org.sonar.ce.taskprocessor.CeWorkerImpl.call(CeWorkerImpl.java:35)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

Body:
Bumped into the same issue. It is caused by 'invalid' records in FILE_SOURCES
table :

having an already used FILE_UUID

referencing a project that is not a Sonar 'top project'

Fixed with this query :

delete
from FILE_SOURCES
where PROJECT_UUID not in
(
  select distinct PROJECT_UUID from PROJECTS
  where SCOPE = 'PRJ' and QUALIFIER = 'TRK'
);


来源: stackexchange

问:
HTML Purifier - what to purify?
I am using HTML Purifier to protect my application from XSS attacks. Currently I am purifying content from WYSIWYG editors because that is the only place where users are allowed to use XHTML markup.

My question is, should I use HTML Purifier also on username and password in a login authentication system (or on input fields of sign up page such as email, name, address etc)? Is there a chance of XSS attack there?

答:
HTML Purifier takes HTML as input, and produces HTML as output. Its purpose is to allow the user to enter html with some tags, attributes, and values, while filtering out others. This uses a whitelist to prevent any data that can contain scripts. So this is useful for something like a WYSIWYG editor.

Usernames and passwords on the other hand are not HTML. They're plain text, so HTML purifier is not an option. Trying to use HTML Purifier here would either corrupt the data, or allow XSS attacks.

For example, it lets the following through unchanged, which can cause XSS issues when inserted as an attribute value in some elements:

```<code>" onclick="javascript:alert()" href="
</code>```

Or if someone tried to use special symbols in their password, and entered:

```<code><password
</code>```

then their password would become blank, and make it much easier to guess.

Instead, you should encode the text. The encoding required depends on the context, but you can use htmlentities when outputting these values if you stick to rule #0 and rule #1, at the OWASP XSS Prevention Cheat Sheet

ContentLicense: CC BY-SA 2.5

Title: HTML Purifier - what to purify?

Body:
HTML Purifier takes HTML as input, and produces HTML as output. Its purpose is to allow the user to enter html with some tags, attributes, and values, while filtering out others. This uses a whitelist to prevent any data that can contain scripts. So this is useful for something like a WYSIWYG editor.

Usernames and passwords on the other hand are not HTML. They're plain text, so HTML purifier is not an option. Trying to use HTML Purifier here would either corrupt the data, or allow XSS attacks.

For example, it lets the following through unchanged, which can cause XSS issues when inserted as an attribute value in some elements:

" onclick="javascript:alert()" href="

Or if someone tried to use special symbols in their password, and entered:

<password

then their password would become blank, and make it much easier to guess.

Instead, you should encode the text. The encoding required depends on the context, but you can use htmlentities when outputting these values if you stick to rule #0 and rule #1, at the OWASP XSS Prevention Cheat Sheet

ContentLicense: CC BY-SA 3.0


问:
Tmux refresh client call from fish shell alias
I want tmux pane title to refresh immediately after I start htop, so I added alias in my config.fish:

```<code>alias h "htop;tmux refresh-client -S"
</code>```

But it does nothing. I also tried with delay:

```<code>alias h "htop;sleep 0.1;tmux refresh-client -S"
</code>```

That also did nothing - tmux still refreshes only after default interval, which is too long for me, and you can only decrease it to 1 second and not less.

What did I do wrong and is it even possible what I want to do?

答:
Maybe this is a bit easier to see when we remove the alias from the equation:

```<code>echo banana; sleep 5s; echo sausage
</code>```

will echo "banana", wait for 5 seconds and only then print "sausage", so

```<code>htop; tmux refresh-client -S
</code>```

will run htop, wait until it is finished and then run tmux refresh-client -S, at which point fish will be the foreground process again.

What would have to be done instead is to get the shell to integrate with tmux. Now, apparently tmux has an escape sequence for Names and titles, so

```<code>printf '\ekhtop\e\\' # \e is \033 - the escape character
</code>```

changes the window title to "htop".

Fish has events that functions can be bound to, so something like

```<code>function tmux_name --on-event fish_preexec
    printf '\ek%s\e\\' "$argv" # the argument for preexec is the commandline about to be executed
end
</code>```

will set the tmux window name always to the command line. This won't reset it when the command has finished, so we need a second function

```<code>function tmux_reset_name --on-event fish_postexec
     # $argv for postexec is also the commandline
     # so we can't use it. Just hardcode "fish".
     printf '\ek%s\e\\' fish
end
</code>```

Not that this is perfect or anything - it'll still set the title even for very short-running commands, it'll use the full commandline even for long commands (maybe using just $argv[1] would be better).

Note that these functions will have to be defined in config.fish or a file explicitly sourced by it (or ~/.config/fish/conf.d/), because function files are autoloaded, so fish won't know about the event.

Body:
I want tmux pane title to refresh immediately after I start htop, so I added alias in my config.fish:

alias h "htop;tmux refresh-client -S"

But it does nothing. I also tried with delay:

alias h "htop;sleep 0.1;tmux refresh-client -S"

That also did nothing - tmux still refreshes only after default interval, which is too long for me, and you can only decrease it to 1 second and not less.

What did I do wrong and is it even possible what I want to do?

Body:
Maybe this is a bit easier to see when we remove the alias from the equation:

echo banana; sleep 5s; echo sausage

will echo "banana", wait for 5 seconds and only then print "sausage", so

htop; tmux refresh-client -S

will run htop, wait until it is finished and then run tmux refresh-client -S, at which point fish will be the foreground process again.

What would have to be done instead is to get the shell to integrate with tmux. Now, apparently tmux has an escape sequence for Names and titles, so

printf '\ekhtop\e\\' # \e is \033 - the escape character

changes the window title to "htop".

Fish has events that functions can be bound to, so something like

function tmux_name --on-event fish_preexec
    printf '\ek%s\e\\' "$argv" # the argument for preexec is the commandline about to be executed
end

will set the tmux window name always to the command line. This won't reset it when the command has finished, so we need a second function

function tmux_reset_name --on-event fish_postexec
     # $argv for postexec is also the commandline
     # so we can't use it. Just hardcode "fish".
     printf '\ek%s\e\\' fish
end

Not that this is perfect or anything - it'll still set the title even for very short-running commands, it'll use the full commandline even for long commands (maybe using just $argv[1] would be better).

Note that these functions will have to be defined in config.fish or a file explicitly sourced by it (or ~/.config/fish/conf.d/), because function files are autoloaded, so fish won't know about the event.


问:
How use return statement?
I have such code:

```<code>class test(){
   #some operation to get $data
   function test1($data){
      #save some part of data
      return $save
   }
   function test2($data, $save(!!!)){
   #some operation
   }
}
</code>```

Question: how use variable $save in test2() which return from test1()?

答:
write code this way

```<code><?php
class test{ //class no reuqire ()
  function test1($data)
  {
          $save=$data+10;    //$data assign in $save
          #save some part of data
          return $save; //return $save value
  }
   function test2($data){
        $data=$this->test1($data); //call a test1() function from test2()
        echo $data; //print return data from test1()
   }
}
$new=new test(); //create object of class test
$new->test2(20);//call test2() function using class object $new
</code>```

demo:run demo code

Title: How use return statement?

Body:
I have such code:

class test(){
   #some operation to get $data
   function test1($data){
      #save some part of data
      return $save
   }
   function test2($data, $save(!!!)){
   #some operation
   }
}

Question: how use variable $save in test2() which return from test1()?

Body:
write code this way

<?php
class test{ //class no reuqire ()
  function test1($data)
  {
          $save=$data+10;    //$data assign in $save
          #save some part of data
          return $save; //return $save value
  }
   function test2($data){
        $data=$this->test1($data); //call a test1() function from test2()
        echo $data; //print return data from test1()
   }
}
$new=new test(); //create object of class test
$new->test2(20);//call test2() function using class object $new

demo:run demo code


问:
Bash - Adding titles into to a piped table command
I have a simple script to output the content of the file students.txt as a basic table to the print file, which is then displayed.

```<code>#!/bin/bash

cat students.txt | column -t -s',' | sort -u -k3 > print.txt
cat print.txt
</code>```

The output looks like as follows:

```<code>Consoling  ST  DWC  0900
Scribing   RA  DWC  1000
Gloater    AU  DWC  1100
Crimp      DI  DWC  1200
</code>```

and so on. However I also want to be able to add headings for each column and have them align perfectly, as well as not being sorted. I have tried to use printf and echo but when piped into the command they do not display and I cannot align the columns correctly by printing the heading names outside of the pipe. The desired output I am looking for would look like this:

```<code>Family Name  Initials  Interviewer Initials  Interview Time
Consoling    ST        DWC                   0900
Scribing     RA        DWC                   1000
Gloater      AU        DWC                   1100
Crimp        DI        DWC                   1200
</code>```

How could I achieve this?

答:
There is a oneliner:

```<code>cat <(echo "Family Name,Initials,Interviewer Initials,Interview Time") <(sort -u -k3 -t ',' students.txt) | column -s ',' -t > print.txt
</code>```

This makes use of Process Substitution. The command inside <() is run and it's output appears as a filename. cat concatenates the two "files", that contain the outputs of echo (for the headers) and sort (to sort your students.txt).

sort is run with option -t ',' to specifiy "," as the delimiter.

column is run with option -s ',' to specify "," as the delimiter.

EDIT (thanks to @tripleee for pointing it out):

The oneliner can be modified, such that Process Substitution and cat isn't necessary:

```<code>{ echo "Family Name,Initials,Interviewer Initials,Interview Time"; sort -u -k3 -t ',' students.txt; } | column -s ',' -t > print.txt
</code>```

echo and sort are grouped by {} and are executed in the current shell context. The redirection (pipe to column) is applied to the entire group. For reference: Grouping Commands.

Body:
I have a simple script to output the content of the file students.txt as a basic table to the print file, which is then displayed.

#!/bin/bash

cat students.txt | column -t -s',' | sort -u -k3 > print.txt
cat print.txt

The output looks like as follows:

Consoling  ST  DWC  0900
Scribing   RA  DWC  1000
Gloater    AU  DWC  1100
Crimp      DI  DWC  1200

and so on. However I also want to be able to add headings for each column and have them align perfectly, as well as not being sorted. I have tried to use printf and echo but when piped into the command they do not display and I cannot align the columns correctly by printing the heading names outside of the pipe. The desired output I am looking for would look like this:

Family Name  Initials  Interviewer Initials  Interview Time
Consoling    ST        DWC                   0900
Scribing     RA        DWC                   1000
Gloater      AU        DWC                   1100
Crimp        DI        DWC                   1200

How could I achieve this?

Body:
There is a oneliner:

cat <(echo "Family Name,Initials,Interviewer Initials,Interview Time") <(sort -u -k3 -t ',' students.txt) | column -s ',' -t > print.txt

This makes use of Process Substitution. The command inside <() is run and it's output appears as a filename. cat concatenates the two "files", that contain the outputs of echo (for the headers) and sort (to sort your students.txt).

sort is run with option -t ',' to specifiy "," as the delimiter.

column is run with option -s ',' to specify "," as the delimiter.

EDIT (thanks to @tripleee for pointing it out):

The oneliner can be modified, such that Process Substitution and cat isn't necessary:

{ echo "Family Name,Initials,Interviewer Initials,Interview Time"; sort -u -k3 -t ',' students.txt; } | column -s ',' -t > print.txt

echo and sort are grouped by {} and are executed in the current shell context. The redirection (pipe to column) is applied to the entire group. For reference: Grouping Commands.


问:
Add column to the right jQuery table
I have this code that I tried so far but it is not giving me the results that I want.

$(document).ready(function(){
  $(".get_attr").click(function (){
    var trow;//=$('.optionsForm tr:first').html();
    trow='
Class
sdfg

sdfg

sdfg

sdfg

';
    $('.optionsForm ').append(trow);
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>

  <table border="1" class='optionsForm'>
    <tr><th>Name</th></tr>
    <tr><td>sdg</td></tr>
    <tr><td>sdfg</td></tr>
    <tr><td>sdgds</td></tr>
  </table>

  <button type="button" data-id="5" class="get_attr" >Click Me</button>
</body></code>```

When I click the button the colon is added just fine the th and other td but I want all this to be added to the right side something like this

```<code>Name    Class
sdg     sdg
sdfg    sdfg
sdgds   sdfgds
</code>```

and not like this :

```<code>Name
sdg
sdfg
sdgds

Class
sdfg
sdfg
sdfg
sdfg
</code>```

Can someone please give me a little help with this.

答:
Here you go with a solution

$(document).ready(function(){
  $(".get_attr").click(function (){
    var trow;
    var columnContent = ['Class', 'sdfg', 'sdfg', 'sdfg'];

    for(var i=0; i<columnContent.length; i++){
      if(i==0){
        $('.optionsForm ').find('tr:eq(' + i + ')').append('' + columnContent[i] + '	');
      } else {
        $('.optionsForm ').find('tr:eq(' + i + ')').append('' + columnContent[i] + '	');
      }
    }

  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>

  <table border="1" class='optionsForm'>
    <tr><th>Name</th></tr>
    <tr><td>sdg</td></tr>
    <tr><td>sdfg</td></tr>
    <tr><td>sdgds</td></tr>
  </table>

  <button type="button" data-id="5" class="get_attr" >Click Me</button>
</body></code>```

Hope this will help you

Title: Add column to the right jQuery table

Body:
I have this code that I tried so far but it is not giving me the results that I want.

$(document).ready(function(){
  $(".get_attr").click(function (){
    var trow;//=$('.optionsForm tr:first').html();
    trow='
Class
sdfg

sdfg

sdfg

sdfg

';
    $('.optionsForm ').append(trow);
  });
});

Name

sdg

sdfg

sdgds

  <button type="button" data-id="5" class="get_attr" >Click Me</button>

When I click the button the colon is added just fine the th and other td but I want all this to be added to the right side something like this

Name    Class
sdg     sdg
sdfg    sdfg
sdgds   sdfgds

and not like this :

Name
sdg
sdfg
sdgds

Class
sdfg
sdfg
sdfg
sdfg

Can someone please give me a little help with this.

Body:
Here you go with a solution

$(document).ready(function(){
  $(".get_attr").click(function (){
    var trow;
    var columnContent = ['Class', 'sdfg', 'sdfg', 'sdfg'];

    for(var i=0; i<columnContent.length; i++){
      if(i==0){
        $('.optionsForm ').find('tr:eq(' + i + ')').append('<th>' + columnContent[i] + '</th>');
      } else {
        $('.optionsForm ').find('tr:eq(' + i + ')').append('<td>' + columnContent[i] + '</td>');
      }
    }

  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>

  <table border="1" class='optionsForm'>
    <tr><th>Name</th></tr>
    <tr><td>sdg</td></tr>
    <tr><td>sdfg</td></tr>
    <tr><td>sdgds</td></tr>
  </table>

  <button type="button" data-id="5" class="get_attr" >Click Me</button>
</body>

Hope this will help you


问:
Visual Studio 2017 Connection String Unable to Connect To Server
I just installed Visual Studio 2017 Community.  I am beginning a new ASP.net WebForms C# project, but I'm having an issue with my connection string.  Here's what I have done thus far:
Created a WebForms application with individual user accounts
Changed the DefaultConnection in the web.config file to

```<code><connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=s13.example.com;Initial Catalog=DB_9;User ID=DB_9_user;Password=myPwd;Integrated Security=False;"
  providerName="System.Data.SqlClient" />
</code>```

Then I add a SqlDataSource and attempt to use the DefaultConnection, but I get the following error:

Database schema could not be retrieved for this connection.  Please
  make sure the connection settings are correct and that the database is
  online.

  Failed to retrieve data for this request.

  Failed to connect to server (local).

  Login failed for user 'DB_9_user'.

Next, I verified that the server, username and password were correct.  I used the same credentials in Sql Server Management Studio 2012 to connect to the database successfully.  So next I pulled-up my old computer with Visual Studio 2013 Professional and recreated the project on there.  There were no issues at all changing the connection string and using it in a SqlDataSource control.  Is there something different about the VS 2017 Community Edition that is blocking my ability to connect to the Database?

答: Here was my workaround for this problem.  In Visual Studio, Tools->Connect to Database.  Use the same credentials and server name as your connection string.  Then when you go to create your new Datasource, select SQL Database as the Data Source Type.  When you Choose Your Data Connection, the connection you created earlier should be available to select from instead of using the Connection String. This will create a new Connection String and will be added to your web.config file.  This should look exactly like your previous connection string.  You can replace the old connection string with this one if you choose to mind you update anything using the old connection string.</p>

Body:
I just installed Visual Studio 2017 Community.  I am beginning a new ASP.net WebForms C# project, but I'm having an issue with my connection string.  Here's what I have done thus far:
Created a WebForms application with individual user accounts
Changed the DefaultConnection in the web.config file to

<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=s13.example.com;Initial Catalog=DB_9;User ID=DB_9_user;Password=myPwd;Integrated Security=False;"
  providerName="System.Data.SqlClient" />

Then I add a SqlDataSource and attempt to use the DefaultConnection, but I get the following error:

Database schema could not be retrieved for this connection.  Please
  make sure the connection settings are correct and that the database is
  online.

  Failed to retrieve data for this request.

  Failed to connect to server (local).

  Login failed for user 'DB_9_user'.

Next, I verified that the server, username and password were correct.  I used the same credentials in Sql Server Management Studio 2012 to connect to the database successfully.  So next I pulled-up my old computer with Visual Studio 2013 Professional and recreated the project on there.  There were no issues at all changing the connection string and using it in a SqlDataSource control.  Is there something different about the VS 2017 Community Edition that is blocking my ability to connect to the Database?


问:
vim + fzf.vim - specify project root in :Files
My question is about usage of vim-projectroot with fzf.vim

I have a key mapping which opens :Files at project root like this

nnoremap <leader>t :ProjectRootExe Files<CR>

But problem is it's interfering with set autochdir. Unless I force a new session with :e/:sp/:vsp current directory remains same as previous directory.

So I thought of passing directory as the second argument to :Files path like this

```<code>function Guess()
  return projectroot#guess()
endfunction

nnoremap <leader>t :Files Guess()<CR>
</code>```

But for obvious reasons which I can't figure out I am unable to get the usage working. How can I specify in a vim mapping that it should combine the command with output of a function?

What I want is :Files output_of_Guess() to be invoked.

答:
Vim's evaluation rules are different than most programming languages. You need to use :execute in order to evaluate a variable (or expression); otherwise, it's taken literally; i.e. Vim uses the function name itself as the argument.

```<code>nnoremap <leader>t :execute 'Files ' . Guess()<CR>
</code>```

An alternative for mappings is using :help :map-expr; that's basically :execute built into the variant of :map:

```<code>nnoremap <expr> <leader>t ':Files ' . Guess() . "\<lt>CR>"
</code>```

Body:
My question is about usage of vim-projectroot with fzf.vim

I have a key mapping which opens :Files at project root like this

nnoremap <leader>t :ProjectRootExe Files<CR>

But problem is it's interfering with set autochdir. Unless I force a new session with :e/:sp/:vsp current directory remains same as previous directory.

So I thought of passing directory as the second argument to :Files path like this

function Guess()
  return projectroot#guess()
endfunction

nnoremap <leader>t :Files Guess()<CR>

But for obvious reasons which I can't figure out I am unable to get the usage working. How can I specify in a vim mapping that it should combine the command with output of a function?

What I want is :Files output_of_Guess() to be invoked.

Body:
Vim's evaluation rules are different than most programming languages. You need to use :execute in order to evaluate a variable (or expression); otherwise, it's taken literally; i.e. Vim uses the function name itself as the argument.

nnoremap <leader>t :execute 'Files ' . Guess()<CR>

An alternative for mappings is using :help :map-expr; that's basically :execute built into the variant of :map:

nnoremap <expr> <leader>t ':Files ' . Guess() . "\<lt>CR>"


问:
SQL group by with descending id order
I'm using Laravel for a radio website. Every song played is stored as a row in a table called last_played. We have a page called Top 20 which basically should display the Top 20 most played songs and when they were last played.

Table

```<code>+----+--------+-------------+
| id |  song  | time_played |
+----+--------+-------------+
|  1 | song_1 |  1510837544 |
|  2 | song_2 |  1510837545 |
|  3 | song_3 |  1510837546 |
|  4 | song_2 |  1510837547 |
|  5 | song_1 |  1510837548 |
|  6 | song_2 |  1510837549 |
+----+--------+-------------+
</code>```

Expected result like this

```<code>+--------+-------------+-------+
|  song  | time_played | count |
+--------+-------------+-------+
| song_2 |  1510837549 |     3 |
| song_1 |  1510837548 |     2 |
| song_3 |  1510837546 |     1 |
+--------+-------------+-------+
</code>```

And the query we use is as following:

```<code>$top20 = DB::select(DB::raw('SELECT *,
  COUNT(*) AS count FROM last_played
   GROUP BY song ORDER BY COUNT(*) DESC LIMIT 20'));
</code>```

Everything goes well until we display the songs. They are displayed correctly by the number of times they have been played, but each song returned are the ones with the lowest ID. We want to group everything and get the count of the songs played the most, and return the last id of that song too.

A link to the top20 page is here, and as you can see "Sist spillt / last played" is showing the first time the song where played, not the last.

Anyone know how to solve this?

答:
```<code>SELECT
    song, COUNT(*) AS count, MAX(time_played) AS timeplayed
FROM
    song
GROUP BY song
ORDER BY timeplayed DESC, count DESC
LIMIT 20;
</code>```

I'm not sure if I get your problem.

But this works with your current example data.

ContentLicense: CC BY-SA 4.0

Title: SQL group by with descending id order

Body:
I'm using Laravel for a radio website. Every song played is stored as a row in a table called last_played. We have a page called Top 20 which basically should display the Top 20 most played songs and when they were last played.

Table

+----+--------+-------------+
| id |  song  | time_played |
+----+--------+-------------+
|  1 | song_1 |  1510837544 |
|  2 | song_2 |  1510837545 |
|  3 | song_3 |  1510837546 |
|  4 | song_2 |  1510837547 |
|  5 | song_1 |  1510837548 |
|  6 | song_2 |  1510837549 |
+----+--------+-------------+

Expected result like this

+--------+-------------+-------+
|  song  | time_played | count |
+--------+-------------+-------+
| song_2 |  1510837549 |     3 |
| song_1 |  1510837548 |     2 |
| song_3 |  1510837546 |     1 |
+--------+-------------+-------+

And the query we use is as following:

$top20 = DB::select(DB::raw('SELECT *,
  COUNT(*) AS count FROM last_played
   GROUP BY song ORDER BY COUNT(*) DESC LIMIT 20'));

Everything goes well until we display the songs. They are displayed correctly by the number of times they have been played, but each song returned are the ones with the lowest ID. We want to group everything and get the count of the songs played the most, and return the last id of that song too.

A link to the top20 page is here, and as you can see "Sist spillt / last played" is showing the first time the song where played, not the last.

Anyone know how to solve this?

Body:
SELECT
    song, COUNT(*) AS count, MAX(time_played) AS timeplayed
FROM
    song
GROUP BY song
ORDER BY timeplayed DESC, count DESC
LIMIT 20;

I'm not sure if I get your problem.

But this works with your current example data.


问:
Is it better to use the column name or column index on .Net DataSets?
When retrieving values from a DataRow is it better to use the column name or column index?

The column name is more readable and easier to maintain:

```<code>int price = (int)dr["Price"];
</code>```

While column index is just faster (I think):

```<code>int price = (int)dr[3];
</code>```

Would using column names break if you decide to obfuscate the database?

答:
I opt for strings for ease of reading and maintainability. I use string contstants to define the values of the column names. Ex:

```<code>public class ExampleDataColumns
{
    public const string ID = "example_id";
    public const string Name = "example_name";
    ....
}
</code>```

Then I can reference it later like this:

```<code>row[ExampleDataColumns.ID]
</code>```

OwnerDisplayName: tpower

Body:
When retrieving values from a DataRow is it better to use the column name or column index?

The column name is more readable and easier to maintain:

int price = (int)dr["Price"];

While column index is just faster (I think):

int price = (int)dr[3];

Would using column names break if you decide to obfuscate the database?

LastEditorDisplayName: tpower

Body:
I opt for strings for ease of reading and maintainability. I use string contstants to define the values of the column names. Ex:

public class ExampleDataColumns
{
    public const string ID = "example_id";
    public const string Name = "example_name";
    ....
}

Then I can reference it later like this:

row[ExampleDataColumns.ID]

OwnerDisplayName: Jim Petkus


问:
Continuing in Python's unittest when an assertion fails
EDIT: switched to a better example, and clarified why this is a real problem.

I'd like to write unit tests in Python that continue executing when an assertion fails, so that I can see multiple failures in a single test. For example:

```<code>class Car(object):
  def __init__(self, make, model):
    self.make = make
    self.model = make  # Copy and paste error: should be model.
    self.has_seats = True
    self.wheel_count = 3  # Typo: should be 4.

class CarTest(unittest.TestCase):
  def test_init(self):
    make = "Ford"
    model = "Model T"
    car = Car(make=make, model=model)
    self.assertEqual(car.make, make)
    self.assertEqual(car.model, model)  # Failure!
    self.assertTrue(car.has_seats)
    self.assertEqual(car.wheel_count, 4)  # Failure!
</code>```

Here, the purpose of the test is to ensure that Car's __init__ sets its fields correctly. I could break it up into four methods (and that's often a great idea), but in this case I think it's more readable to keep it as a single method that tests a single concept ("the object is initialized correctly").

If we assume that it's best here to not break up the method, then I have a new problem: I can't see all of the errors at once. When I fix the model error and re-run the test, then the wheel_count error appears. It would save me time to see both errors when I first run the test.

For comparison, Google's C++ unit testing framework distinguishes between between non-fatal EXPECT_* assertions and fatal ASSERT_* assertions:

The assertions come in pairs that test the same thing but have different effects on the current function. ASSERT_* versions generate fatal failures when they fail, and abort the current function. EXPECT_* versions generate nonfatal failures, which don't abort the current function. Usually EXPECT_* are preferred, as they allow more than one failures to be reported in a test. However, you should use ASSERT_* if it doesn't make sense to continue when the assertion in question fails.

Is there a way to get EXPECT_*-like behavior in Python's unittest? If not in unittest, then is there another Python unit test framework that does support this behavior?

Incidentally, I was curious about how many real-life tests might benefit from non-fatal assertions, so I looked at some code examples (edited 2014-08-19 to use searchcode instead of Google Code Search, RIP). Out of 10 randomly selected results from the first page, all contained tests that made multiple independent assertions in the same test method. All would benefit from non-fatal assertions.

答:
It is considered an anti-pattern to have multiple asserts in a single unit test. A single unit test is expected to test only one thing. Perhaps you are testing too much. Consider splitting this test up into multiple tests. This way you can name each test properly.

Sometimes however, it is okay to check multiple things at the same time. For instance when you are asserting properties of the same object. In that case you are in fact asserting whether that object is correct. A way to do this is to write a custom helper method that knows how to assert on that object. You can write that method in such a way that it shows all failing properties or for instance shows the complete state of the expected object and the complete state of the actual object when an assert fails.

Body:
EDIT: switched to a better example, and clarified why this is a real problem.

I'd like to write unit tests in Python that continue executing when an assertion fails, so that I can see multiple failures in a single test. For example:

class Car(object):
  def __init__(self, make, model):
    self.make = make
    self.model = make  # Copy and paste error: should be model.
    self.has_seats = True
    self.wheel_count = 3  # Typo: should be 4.

class CarTest(unittest.TestCase):
  def test_init(self):
    make = "Ford"
    model = "Model T"
    car = Car(make=make, model=model)
    self.assertEqual(car.make, make)
    self.assertEqual(car.model, model)  # Failure!
    self.assertTrue(car.has_seats)
    self.assertEqual(car.wheel_count, 4)  # Failure!

Here, the purpose of the test is to ensure that Car's __init__ sets its fields correctly. I could break it up into four methods (and that's often a great idea), but in this case I think it's more readable to keep it as a single method that tests a single concept ("the object is initialized correctly").

If we assume that it's best here to not break up the method, then I have a new problem: I can't see all of the errors at once. When I fix the model error and re-run the test, then the wheel_count error appears. It would save me time to see both errors when I first run the test.

For comparison, Google's C++ unit testing framework distinguishes between between non-fatal EXPECT_* assertions and fatal ASSERT_* assertions:

The assertions come in pairs that test the same thing but have different effects on the current function. ASSERT_* versions generate fatal failures when they fail, and abort the current function. EXPECT_* versions generate nonfatal failures, which don't abort the current function. Usually EXPECT_* are preferred, as they allow more than one failures to be reported in a test. However, you should use ASSERT_* if it doesn't make sense to continue when the assertion in question fails.

Is there a way to get EXPECT_*-like behavior in Python's unittest? If not in unittest, then is there another Python unit test framework that does support this behavior?

Incidentally, I was curious about how many real-life tests might benefit from non-fatal assertions, so I looked at some code examples (edited 2014-08-19 to use searchcode instead of Google Code Search, RIP). Out of 10 randomly selected results from the first page, all contained tests that made multiple independent assertions in the same test method. All would benefit from non-fatal assertions.


问:
"Cannot set session ID after the session has started" when generating csrf token within Behat test
I'm trying to test that a user with the wrong permissions sees the correct response when visting a page that has a csrf token in the path.

I've added a Behat context step to create a csrf token using the 'security.csrf.token_manager', however then visit the page with this token in the path, I get a "Cannot set session ID after the session has started" 500 error.

Can anyone advise what I'm doing wrong, or how I work around this, please?

```<code>/**
 * @When /^I go to the application admin archive page for "(?P<status>[^"]*)" application (?P<number>\d+) with a valid token$/
 *
 * @param string $status
 * @param int    $number
 */
public function iGoToTheApplicationAdminArchivePageForApplicationWithAValidToken($status, $number)
{
    $tokenManager = $this->kernel->getContainer()->get('security.csrf.token_manager');
    $token        = $tokenManager->getToken(ApplicationAdminController::CSRF_ARCHIVE);
    var_dump($token);

    $this->visitAdminPage('archive', $status, $number, ['token' => $token]);
}
</code>```

答:
I still got this error at this moment. I fixed this issue by checking your file config of env at

```<code>app/config/config_test.yml
</code>```

I found this configuration under framework section

```<code>framework:
    test: ~
    session:
        storage_id: session.storage.mock_file
    profiler:
        collect: false
</code>```

All what you have to do just remove this line test: ~
to be as below:

```<code>framework:
    session:
        storage_id: session.storage.mock_file
    profiler:
        collect: false
</code>```

Then clear the cache by

```<code>php bin/console cache:clear --env=test --no-debug
</code>```

Refresh and Enjoy ;)

Body:
I'm trying to test that a user with the wrong permissions sees the correct response when visting a page that has a csrf token in the path.

I've added a Behat context step to create a csrf token using the 'security.csrf.token_manager', however then visit the page with this token in the path, I get a "Cannot set session ID after the session has started" 500 error.

Can anyone advise what I'm doing wrong, or how I work around this, please?

/**
 * @When /^I go to the application admin archive page for "(?P<status>[^"]*)" application (?P<number>\d+) with a valid token$/
 *
 * @param string $status
 * @param int    $number
 */
public function iGoToTheApplicationAdminArchivePageForApplicationWithAValidToken($status, $number)
{
    $tokenManager = $this->kernel->getContainer()->get('security.csrf.token_manager');
    $token        = $tokenManager->getToken(ApplicationAdminController::CSRF_ARCHIVE);
    var_dump($token);

    $this->visitAdminPage('archive', $status, $number, ['token' => $token]);
}

Body:
I still got this error at this moment. I fixed this issue by checking your file config of env at

app/config/config_test.yml

I found this configuration under framework section

framework:
    test: ~
    session:
        storage_id: session.storage.mock_file
    profiler:
        collect: false

All what you have to do just remove this line test: ~
to be as below:

framework:
    session:
        storage_id: session.storage.mock_file
    profiler:
        collect: false

Then clear the cache by

php bin/console cache:clear --env=test --no-debug

Refresh and Enjoy ;)


问:
Not able to insert the base64 data into the Word with Office Word add-in
I am trying to insert file which is formatted as Base64 using insertFileFromBase64() but I am getting this exception:

{
    "name": "OfficeExtension.Error",
    "code": "GeneralException",
    "message": "ooxmlIsMalformated",
    "traceMessages": [],
    "innerError": null,
    "debugInfo": {
        "code": "GeneralException",
        "message": "ooxmlIsMalformated",
        "errorLocation": "Body.insertFileFromBase64"
    }
}
```

<p>My code is:</p>

<pre class="lang-js prettyprint-override"><code>// documentData - is a base64 string.
// Encoded base64 string = "V29yZCBEb2N1bWVudCBpcyBub3QgZ2V0IGluc2VydGVkIHVzaW5nIGluc2VydEZpbGVCYXNlNjQ="
body.insertFileFromBase64(documentData,window.Word.InsertLocation.replace);
</code>```

I have tried other methods for HTML and text that are working, but getting the exception with insertFileFromBase64.

Can someone please guide me if I am missing anything here?

答:
From the documentation, the base64File parameter takes "The base64 encoded content of a .docx file."

The string your passing isn't an encoded .docx, it is simply an encoded string. The exception your getting is correct,  the OOXML you are passing is malformated (or more precisely, it isn't OOXML at all).

You will need to pass in a proper OOXML document that has been Base64 encoded for this method to work.

Body:
I am trying to insert file which is formatted as Base64 using insertFileFromBase64() but I am getting this exception:

{
    "name": "OfficeExtension.Error",
    "code": "GeneralException",
    "message": "ooxmlIsMalformated",
    "traceMessages": [],
    "innerError": null,
    "debugInfo": {
        "code": "GeneralException",
        "message": "ooxmlIsMalformated",
        "errorLocation": "Body.insertFileFromBase64"
    }
}

My code is:

// documentData - is a base64 string.
// Encoded base64 string = "V29yZCBEb2N1bWVudCBpcyBub3QgZ2V0IGluc2VydGVkIHVzaW5nIGluc2VydEZpbGVCYXNlNjQ="
body.insertFileFromBase64(documentData,window.Word.InsertLocation.replace);

I have tried other methods for HTML and text that are working, but getting the exception with insertFileFromBase64.

Can someone please guide me if I am missing anything here?


问:
how to mark row on gridview by any value?
i have gridview that contain:

```<code>Fname|Born
aa   |03/05
bb   |19/01
cc   |03/08
dd   |19/01
</code>```

if today is: 19/01/2011  how to mark in red color the 2 rows that Satisfies the condition ?

in C# asp.net

thanks for any help

答:
In my opinion a good place to start, if you want to change design-settings of a datagridview programmatically is using the datagridview.CellFormatting-Event

```<code>        private void _dgvDb_CellFormatting(Object sender, DataGridViewCellFormattingEventArgs e){
        if (e.Value != null && !String.IsNullOrEmpty(e.Value.ToString()))
        {
            switch (_dgvDb.Columns[e.ColumnIndex].Name)
            {
                case "YOUR_COLUMNNAME":
                    if("value==yourChosenValue"){

                    }
                break;
                case "else":
                }
         }
  }
</code>```

Body:
i have gridview that contain:

Fname|Born
aa   |03/05
bb   |19/01
cc   |03/08
dd   |19/01

if today is: 19/01/2011  how to mark in red color the 2 rows that Satisfies the condition ?

in C# asp.net

thanks for any help

Body:
In my opinion a good place to start, if you want to change design-settings of a datagridview programmatically is using the datagridview.CellFormatting-Event

        private void _dgvDb_CellFormatting(Object sender, DataGridViewCellFormattingEventArgs e){
        if (e.Value != null && !String.IsNullOrEmpty(e.Value.ToString()))
        {
            switch (_dgvDb.Columns[e.ColumnIndex].Name)
            {
                case "YOUR_COLUMNNAME":
                    if("value==yourChosenValue"){

                    }
                break;
                case "else":
                }
         }
  }


问:
Spring, Java - run many scheduled-tasks in parallel with one instance every one
I try to run many scheduled-tasks in parallel with one instance every one
I configure task like this

```<code><task:scheduled ref="PatchData" method="start" fixed-rate="1000"/>
</code>```

but there are many instances started every second while the first not finished. Is it possible to configure only one instance of the task run in same time ?
My beans configuration in spring-scheduler.xml

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

    <bean id="UpdateScheduler" class="org.ws.scheduled.UpdateScheduler" />
    <bean id="PatchData" class="org.ws.scheduled.PatchData" />

    <task:scheduled-tasks scheduler="myScheduler">
           <task:scheduled ref="UpdateScheduler" method="start" cron="0 30 14 * * *"/>
           <task:scheduled ref="PatchData" method="start" fixed-rate="1000"/>

    </task:scheduled-tasks>

    <task:scheduler id="scheduler" pool-size="10"/>
</code>```

答:
You can add profile setting in bean tag. Example :

```<code><beans profile="scheduledProfile">
 <bean id="UpdateScheduler" class="org.ws.scheduled.UpdateScheduler" />
 <bean id="PatchData" class="org.ws.scheduled.PatchData" />

 <task:scheduled-tasks scheduler="myScheduler">
      <task:scheduled ref="UpdateScheduler" method="start" cron="0 30 14 * * *"/>
      <task:scheduled ref="PatchData" method="start" fixed-rate="1000"/>
 </task:scheduled-tasks>
<bean />
</code>```

And, start your application  one machine with the scheduled profile activated = -Dspring.profiles.active=scheduledProfile

In this way, this Schedule works only one instance.

Body:
I try to run many scheduled-tasks in parallel with one instance every one
I configure task like this

<task:scheduled ref="PatchData" method="start" fixed-rate="1000"/>

but there are many instances started every second while the first not finished. Is it possible to configure only one instance of the task run in same time ?
My beans configuration in spring-scheduler.xml

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

    <bean id="UpdateScheduler" class="org.ws.scheduled.UpdateScheduler" />
    <bean id="PatchData" class="org.ws.scheduled.PatchData" />

    <task:scheduled-tasks scheduler="myScheduler">
           <task:scheduled ref="UpdateScheduler" method="start" cron="0 30 14 * * *"/>
           <task:scheduled ref="PatchData" method="start" fixed-rate="1000"/>

    </task:scheduled-tasks>

    <task:scheduler id="scheduler" pool-size="10"/>

Body:
You can add profile setting in bean tag. Example :

<beans profile="scheduledProfile">
 <bean id="UpdateScheduler" class="org.ws.scheduled.UpdateScheduler" />
 <bean id="PatchData" class="org.ws.scheduled.PatchData" />

 <task:scheduled-tasks scheduler="myScheduler">
      <task:scheduled ref="UpdateScheduler" method="start" cron="0 30 14 * * *"/>
      <task:scheduled ref="PatchData" method="start" fixed-rate="1000"/>
 </task:scheduled-tasks>
<bean />

And, start your application  one machine with the scheduled profile activated = -Dspring.profiles.active=scheduledProfile

In this way, this Schedule works only one instance.


问:
Maven not discovering ScalaTest unit tests
I have the following unit tests:

```<code>import org.scalatest.FunSpec
import org.scalatest.Matchers._

class MyClassSpec extends FunSpec {

  describe("MyClass"){
    describe("Scenario 1"){
      it("Condition 1") {
        true shouldEqual false
      }

      it("Condition 2"){
        true shouldEqual false
      }
    }
  }

}
</code>```

When I run maven test, this compiles fine but the tests are not found. Here is the output:

```<code>[INFO] --- maven-surefire-plugin:2.7:test (default-test) @ project-name ---
[INFO] Tests are skipped.
[INFO]
[INFO] --- scalatest-maven-plugin:1.0:test (test) @ project-name ---
Discovery starting.
Discovery completed in 202 milliseconds.
Run starting. Expected test count is: 0
DiscoverySuite:
Run completed in 236 milliseconds.
Total number of tests run: 0
Suites: completed 1, aborted 0
Tests: succeeded 0, failed 0, canceled 0, ignored 0, pending 0
No tests were executed.
</code>```

As the output shows, I'm using the scalatest plugin for maven. Here is the relevant section of my pom.xml:

```<code><!-- disable surefire -->
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.7</version>
    <configuration>
        <skipTests>true</skipTests>
    </configuration>
</plugin>
<!-- enable scalatest -->
<plugin>
    <groupId>org.scalatest</groupId>
    <artifactId>scalatest-maven-plugin</artifactId>
    <version>1.0</version>
    <configuration>
        <reportsDirectory>${project.build.directory}/scalatest-reports</reportsDirectory>
        <junitxml>junit</junitxml>
        <filereports>report.txt</filereports>
    </configuration>
    <executions>
        <execution>
            <id>test</id>
            <goals>
                <goal>test</goal>
            </goals>
        </execution>
    </executions>
</plugin>
</code>```

I'm pretty new to getting this stuff set up, so I'm not sure if there is some other thing I'm not checking. I get the exact same results if I run maven clean and then maven test. I'm using ScalaTest version 3.0.1. I have another project with tests running successfully also using 3.0.1 (I've copied everything I can find between the two projects that seems even remotely related).

答:
Naturally, the problem seems to have stemmed from some information I didn't think was relevant, so I didn't include it my original post.

The source code I wrote was a tool for unit testing, so I put it in the namespace my.cool.package.testUtilities. The unit tests were thus in my.cool.package.testUtilities.test. Moving the source code out of testUtilities (to just my.cool.package) and moving the tests to just my.cool.package.test allowed the tests to be discovered.

Being new to the java ecosystem (previous experience in .NET), I'm not sure if this is some weird bug with the test runner, expected behavior, or if the act of moving the files to new namespaces did something else, and the namespaces themselves are irrelevant. So I'm not sure what I learned from this.

Body:
I have the following unit tests:

import org.scalatest.FunSpec
import org.scalatest.Matchers._

class MyClassSpec extends FunSpec {

  describe("MyClass"){
    describe("Scenario 1"){
      it("Condition 1") {
        true shouldEqual false
      }

      it("Condition 2"){
        true shouldEqual false
      }
    }
  }

}

When I run maven test, this compiles fine but the tests are not found. Here is the output:

[INFO] --- maven-surefire-plugin:2.7:test (default-test) @ project-name ---
[INFO] Tests are skipped.
[INFO]
[INFO] --- scalatest-maven-plugin:1.0:test (test) @ project-name ---
Discovery starting.
Discovery completed in 202 milliseconds.
Run starting. Expected test count is: 0
DiscoverySuite:
Run completed in 236 milliseconds.
Total number of tests run: 0
Suites: completed 1, aborted 0
Tests: succeeded 0, failed 0, canceled 0, ignored 0, pending 0
No tests were executed.

As the output shows, I'm using the scalatest plugin for maven. Here is the relevant section of my pom.xml:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.7</version>
    <configuration>
        <skipTests>true</skipTests>
    </configuration>
</plugin>

<plugin>
    <groupId>org.scalatest</groupId>
    <artifactId>scalatest-maven-plugin</artifactId>
    <version>1.0</version>
    <configuration>
        <reportsDirectory>${project.build.directory}/scalatest-reports</reportsDirectory>
        <junitxml>junit</junitxml>
        <filereports>report.txt</filereports>
    </configuration>
    <executions>
        <execution>
            <id>test</id>
            <goals>
                <goal>test</goal>
            </goals>
        </execution>
    </executions>
</plugin>

I'm pretty new to getting this stuff set up, so I'm not sure if there is some other thing I'm not checking. I get the exact same results if I run maven clean and then maven test. I'm using ScalaTest version 3.0.1. I have another project with tests running successfully also using 3.0.1 (I've copied everything I can find between the two projects that seems even remotely related).


问:
Spring data rest method not able to search on DbRef Id field
I am using mongodb and spring boot in my appliation. In Area collection city is DBRef but spring data rest method is unable to search using city's Id. It's returning empty JSON although for that city I have area's in my database.My Area collection and repository are as below.

```<code>@Document(collection = "area")
    public class Area  {

      private String name;

      private String areaCode;

      private String postalCode;

      private String latitude;

      private String longitude;

      private String category;

      @DBRef(lazy = false)
      private City city;

public interface AreaRepo extends MongoRepository<Area, String> {

  @RestResource(path = "byCityId")
  List<Area> findByCityId(@Param(value = "cityId") String cityId);
</code>```

Same kind of relationship in other collection is working file.

答:
Could you try searching by City </p>

```<code>@Autowired
private CityRepository cityRepository;

List<Area> findByCity(cityRepository.findByCityId(cityId));
</code>```

Body:
I am using mongodb and spring boot in my appliation. In Area collection city is DBRef but spring data rest method is unable to search using city's Id. It's returning empty JSON although for that city I have area's in my database.My Area collection and repository are as below.

@Document(collection = "area")
    public class Area  {

      private String name;

      private String areaCode;

      private String postalCode;

      private String latitude;

      private String longitude;

      private String category;

      @DBRef(lazy = false)
      private City city;

public interface AreaRepo extends MongoRepository<Area, String> {

  @RestResource(path = "byCityId")
  List<Area> findByCityId(@Param(value = "cityId") String cityId);

Same kind of relationship in other collection is working file.

Body:
Could you try searching by City

@Autowired
private CityRepository cityRepository;

List<Area> findByCity(cityRepository.findByCityId(cityId));


问:
db.table doesn't bring updated value ,When I update table manually from sql database
I am working on mvc c# , with sql database at backend. My problem is when I update a table's data manually from sql table at backend. It is not updated on the frontend until I open the website again after closing the webpage.

Here is the Image of database table where am updating it manually.

here am retrieving data from database.

```<code>  public ActionResult AddQuiz()
    {

        ViewBag.quizes_List = db.EntityFrameWorkConnection.Zasa_Quiz.OrderByDescending(mm => mm.quiz_code).ToList();
        return View();
    }
</code>```

This is where am using my ViewBag to display quizes list

```<code> @foreach (var item in @ViewBag.quizes_List)
                        {
                            <tr>
                                <td>
                                    <span class="badge bg-blue">@item.quiz_code</span>
                                </td>
                                <td>
                                    @item.quiz_title
                                </td>

                                <td><span class="badge bg-blue">@item.quiz_date.ToString().Substring(0, 10)</span></td>
                            </tr>
                        }
</code>```

EntityFrameWorkConnection is in constants class.
and db is declared like this in controller: and all this is working fine.

```<code> private static Constants db = new Constants();

 public class Constants
{
    public ZASA_AK_DBEntity EntityFrameWorkConnection = new ZASA_AK_DBEntity();
    public SqlConnection ADOConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["adocon"].ConnectionString);
    public string ConnectionString = ConfigurationManager.ConnectionStrings["adocon"].ConnectionString;

}
</code>```

答:
Entity framework catches the data. You have to use Using block.</p>

```<code>using(var context = new DBEntities())
{

}
</code>```

Body:
I am working on mvc c# , with sql database at backend. My problem is when I update a table's data manually from sql table at backend. It is not updated on the frontend until I open the website again after closing the webpage.

Here is the Image of database table where am updating it manually.

here am retrieving data from database.

  public ActionResult AddQuiz()
    {

        ViewBag.quizes_List = db.EntityFrameWorkConnection.Zasa_Quiz.OrderByDescending(mm => mm.quiz_code).ToList();
        return View();
    }

This is where am using my ViewBag to display quizes list

 @foreach (var item in @ViewBag.quizes_List)
                        {

                                    @item.quiz_code

                                    @item.quiz_title

                                @item.quiz_date.ToString().Substring(0, 10)

                        }

EntityFrameWorkConnection is in constants class.
and db is declared like this in controller: and all this is working fine.

 private static Constants db = new Constants();

 public class Constants
{
    public ZASA_AK_DBEntity EntityFrameWorkConnection = new ZASA_AK_DBEntity();
    public SqlConnection ADOConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["adocon"].ConnectionString);
    public string ConnectionString = ConfigurationManager.ConnectionStrings["adocon"].ConnectionString;

}

Body:
Entity framework catches the data. You have to use Using block.

using(var context = new DBEntities())
{

}


问:
Enable Google API OAuth Scope
For one of the application created using Google Apps Script, some scopes are automatically added as follows in my app:

https://www.googleapis.com/auth/drive

https://www.googleapis.com/auth/script.external_request

https://www.googleapis.com/auth/script.send_mail

https://www.googleapis.com/auth/spreadsheets

I've followed all the steps for OAuth Client Verification according to this documentation. But still, my verification process is pending and support team said that I need to add https://www.googleapis.com/auth/drive.file scope to my project.

Anybody know how to add/enable https://www.googleapis.com/auth/drive.file scope in the existing project.

答:
When you authenticate your application you should request the additional scope

Open the script project in the Apps Script editor.

In the menu, select File > Project properties.

Select the Scopes tab.

Review the scopes your script currently requires and determine what changes need to be made. Click Cancel when finished.

If the manifest file appsscript.json isn't visible in the left nav bar, select the View > Show manifest file menu item.

Select the appsscript.json file in the left nav to open it.

Locate the top-level field labeled oauthScopes. If it is not present, you can add it.

The oauthScopes field specifies an array of strings.

example

```<code>{
  ...
  "oauthScopes": [
    " https://www.googleapis.com/auth/drive.file",
    "https://www.googleapis.com/auth/userinfo.email"
  ],
}
</code>```

check the documentation here

Title: Enable Google API OAuth Scope

Body:
When you authenticate your application you should request the additional scope

Open the script project in the Apps Script editor.

In the menu, select File > Project properties.

Select the Scopes tab.

Review the scopes your script currently requires and determine what changes need to be made. Click Cancel when finished.

If the manifest file appsscript.json isn't visible in the left nav bar, select the View > Show manifest file menu item.

Select the appsscript.json file in the left nav to open it.

Locate the top-level field labeled oauthScopes. If it is not present, you can add it.

The oauthScopes field specifies an array of strings.

example

{
  ...
  "oauthScopes": [
    " https://www.googleapis.com/auth/drive.file",
    "https://www.googleapis.com/auth/userinfo.email"
  ],
}

check the documentation here


问:
Docker windows containers file access permission issues

Windows Server 2016 host, running Docker EE through the default MSFTdocker provider.

Docker version 17.06.2-ee-5, build 508bb92

docker-compose version 1.17.1, build 6d101fb0

I have a Windows container based on microsoft/windowsservercore:latest, and am attempting to setup an image for Bamboo server. During creation of a build plan, the server generates a cipher to communicate between Bamboo and Bitbucket. In the running container, the cipher folder/file generation fails with the following error:

```<code>java.nio.file.AccessDeniedException: C:\bamboo-home\xml-data\configuration\cipher\cipher.key_0
</code>```

I have tried with the volume C:\bamboo-home both attached to my Windows host, and fully contained inside the container. Same error both times.

Windows containers run with an admininstrator account named 'containeradministrator'; this is the case both in the default image, and when using an entrypoint, as demonstrated below.

Standard image run:

```<code>PS C:\> docker run -it microsoft/windowsservercore:latest powershell
Windows PowerShell Copyright (C) 2016 Microsoft Corporation. All
rights reserved.

PS C:\> whoami
user manager\containeradministrator
</code>```

And on the custom-built image to test entrypoint:

```<code>PS C:\test> docker-compose build
Building testentrypoint
Step 1/2 : FROM microsoft/windowsservercore:latest
---> 2cddde20d95d
Step 2/2 : ENTRYPOINT whoami
---> Running in 7fe31f02e45f
---> 60822e1907f1
Removing intermediate container 7fe31f02e45f
Successfully built 60822e1907f1
Successfully tagged test/entrypoint:latest
PS C:\test> docker-compose up
Creating network "test_default" with the default driver
Creating test_testentrypoint_1 ...
Creating test_testentrypoint_1 ... done
Attaching to test_testentrypoint_1
testentrypoint_1 | user manager\containeradministrator
test_testentrypoint_1 exited with code 0
</code>```

This user is an alias to Administrator from what I can tell, although interestingly it doesn't show up in net user as this name:

```<code>PS C:\> net user

User accounts for \\

-------------------------------------------------------------------------------
Administrator            DefaultAccount           Guest
The command completed with one or more errors.
</code>```

So this is potentially an issue, but regardless, the user has full admin permissions from what I can tell:

```<code>PS C:\> $user = [Security.Principal.WindowsIdentity]::GetCurrent()
PS C:\> $user

AuthenticationType : Negotiate
ImpersonationLevel : None
IsAuthenticated    : True
IsGuest            : False
IsSystem           : False
IsAnonymous        : False
Name               : User Manager\ContainerAdministrator
Owner              : S-1-5-93-2-1
User               : S-1-5-93-2-1
Groups             : {S-1-1-0, S-1-5-32-545, S-1-5-6, S-1-2-1...}
Token              : 3052
AccessToken        : Microsoft.Win32.SafeHandles.SafeAccessTokenHandle
UserClaims         : {http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name: User Manager\ContainerAdministrator, http://schemas.microsoft.com/ws/2008/06/identity/claims/primarysid: S-1-5-93-2-1, http://schemas.microsoft.com/ws/2008/06/identity/claims/groupsid:
                     S-1-1-0, http://schemas.microsoft.com/ws/2008/06/identity/claims/groupsid: S-1-5-32-545...}
DeviceClaims       : {}
Claims             : {http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name: User Manager\ContainerAdministrator, http://schemas.microsoft.com/ws/2008/06/identity/claims/primarysid: S-1-5-93-2-1, http://schemas.microsoft.com/ws/2008/06/identity/claims/groupsid:
                     S-1-1-0, http://schemas.microsoft.com/ws/2008/06/identity/claims/groupsid: S-1-5-32-545...}
Actor              :
BootstrapContext   :
Label              :
NameClaimType      : http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name
RoleClaimType      : http://schemas.microsoft.com/ws/2008/06/identity/claims/groupsid

PS C:\> (New-Object Security.Principal.WindowsPrincipal $user).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
True
</code>```

So I've tried the following:

Run a build step in the container that sets the folder permissions to "Everyone - Full Access"

Run the script manually in the running container at startup that does the same

Connect to the container when running, and manually run the powershell to do the same

Each time, before attempting to generate the cipher file, the permissions look like this:

```<code>PS C:\> Get-ACL C:\bamboo-home\xml-data\configuration\ | fl

Path   : Microsoft.PowerShell.Core\FileSystem::C:\bamboo-home\xml-data\configuration\
Owner  : User Manager\ContainerAdministrator
Group  : User Manager\ContainerAdministrator
Access : Everyone Allow  FullControl
         NT AUTHORITY\SYSTEM Allow  FullControl
         BUILTIN\Administrators Allow  FullControl
         S-1-5-21-2465844383-291681238-1546083700-500 Allow  FullControl
Audit  :
Sddl   : O:S-1-5-93-2-1G:S-1-5-93-2-1D:AI(A;OICIID;FA;;;WD)(A;OICIID;FA;;;SY)(A;OICIID;FA;;;BA)(A;OICIID;FA;;;S-1-5-21-2465844383-291681238-1546083700-500)
</code>```

And the above error occurs after attempting the generation, and the permissions change to:

```<code>PS C:\> Get-ACL C:\bamboo-home\xml-data\configuration\ | fl

Path   : Microsoft.PowerShell.Core\FileSystem::C:\bamboo-home\xml-data\configuration\
Owner  : User Manager\ContainerAdministrator
Group  : User Manager\ContainerAdministrator
Access : Everyone Allow  FullControl
Audit  :
Sddl   : O:S-1-5-93-2-1G:S-1-5-93-2-1D:AI(A;OICI;FA;;;WD)
</code>```

Why does the default account (presumably an Administrator named containeradministrator) lose access to this directory when it seems to indicate it has ownership? And why can't it create the file (or folder, for that matter) in the first place, since in both cases, "Everyone" should have full access?

答:
I did not identify the issue between host/container permissions, but the way I brought up the container allowed the issue to happen. By changing my setup process, I was able to correct this.

Initial creation (that failed permissions on the created folder):

Create blank folder on host machine.

Link as volume with compose to container internal folder (all of C:\bamboo-home in this case). This is the folder that Bamboo will place all it's configuration/workspace stuff.

Setup product inside container, everything works except failure of the cipher folder. Didn't notice issue until this step.

New creation (that works properly):

Create blank folder on host machine.

Link as volume with compose to container internal folder (C:\empty, in this case). This does NOT link to C:\bamboo-home, which will be made internally in the running container as required.

Setup the product inside container. Once complete, copy all files from the container's folder to the new blank folder created. This way, the permissions are set in a consistent way inside the container itself, and the issues from before were mitigated.

Body:
Windows Server 2016 host, running Docker EE through the default MSFTdocker provider.

Docker version 17.06.2-ee-5, build 508bb92

docker-compose version 1.17.1, build 6d101fb0

I have a Windows container based on microsoft/windowsservercore:latest, and am attempting to setup an image for Bamboo server. During creation of a build plan, the server generates a cipher to communicate between Bamboo and Bitbucket. In the running container, the cipher folder/file generation fails with the following error:

java.nio.file.AccessDeniedException: C:\bamboo-home\xml-data\configuration\cipher\cipher.key_0

I have tried with the volume C:\bamboo-home both attached to my Windows host, and fully contained inside the container. Same error both times.

Windows containers run with an admininstrator account named 'containeradministrator'; this is the case both in the default image, and when using an entrypoint, as demonstrated below.

Standard image run:

PS C:\> docker run -it microsoft/windowsservercore:latest powershell
Windows PowerShell Copyright (C) 2016 Microsoft Corporation. All
rights reserved.

PS C:\> whoami
user manager\containeradministrator

And on the custom-built image to test entrypoint:

PS C:\test> docker-compose build
Building testentrypoint
Step 1/2 : FROM microsoft/windowsservercore:latest
---> 2cddde20d95d
Step 2/2 : ENTRYPOINT whoami
---> Running in 7fe31f02e45f
---> 60822e1907f1
Removing intermediate container 7fe31f02e45f
Successfully built 60822e1907f1
Successfully tagged test/entrypoint:latest
PS C:\test> docker-compose up
Creating network "test_default" with the default driver
Creating test_testentrypoint_1 ...
Creating test_testentrypoint_1 ... done
Attaching to test_testentrypoint_1
testentrypoint_1 | user manager\containeradministrator
test_testentrypoint_1 exited with code 0

This user is an alias to Administrator from what I can tell, although interestingly it doesn't show up in net user as this name:

PS C:\> net user

User accounts for \\

-------------------------------------------------------------------------------
Administrator            DefaultAccount           Guest
The command completed with one or more errors.

So this is potentially an issue, but regardless, the user has full admin permissions from what I can tell:

PS C:\> $user = [Security.Principal.WindowsIdentity]::GetCurrent()
PS C:\> $user

AuthenticationType : Negotiate
ImpersonationLevel : None
IsAuthenticated    : True
IsGuest            : False
IsSystem           : False
IsAnonymous        : False
Name               : User Manager\ContainerAdministrator
Owner              : S-1-5-93-2-1
User               : S-1-5-93-2-1
Groups             : {S-1-1-0, S-1-5-32-545, S-1-5-6, S-1-2-1...}
Token              : 3052
AccessToken        : Microsoft.Win32.SafeHandles.SafeAccessTokenHandle
UserClaims         : {http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name: User Manager\ContainerAdministrator, http://schemas.microsoft.com/ws/2008/06/identity/claims/primarysid: S-1-5-93-2-1, http://schemas.microsoft.com/ws/2008/06/identity/claims/groupsid:
                     S-1-1-0, http://schemas.microsoft.com/ws/2008/06/identity/claims/groupsid: S-1-5-32-545...}
DeviceClaims       : {}
Claims             : {http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name: User Manager\ContainerAdministrator, http://schemas.microsoft.com/ws/2008/06/identity/claims/primarysid: S-1-5-93-2-1, http://schemas.microsoft.com/ws/2008/06/identity/claims/groupsid:
                     S-1-1-0, http://schemas.microsoft.com/ws/2008/06/identity/claims/groupsid: S-1-5-32-545...}
Actor              :
BootstrapContext   :
Label              :
NameClaimType      : http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name
RoleClaimType      : http://schemas.microsoft.com/ws/2008/06/identity/claims/groupsid

PS C:\> (New-Object Security.Principal.WindowsPrincipal $user).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
True

So I've tried the following:

Run a build step in the container that sets the folder permissions to "Everyone - Full Access"

Run the script manually in the running container at startup that does the same

Connect to the container when running, and manually run the powershell to do the same

Each time, before attempting to generate the cipher file, the permissions look like this:

PS C:\> Get-ACL C:\bamboo-home\xml-data\configuration\ | fl

Path   : Microsoft.PowerShell.Core\FileSystem::C:\bamboo-home\xml-data\configuration\
Owner  : User Manager\ContainerAdministrator
Group  : User Manager\ContainerAdministrator
Access : Everyone Allow  FullControl
         NT AUTHORITY\SYSTEM Allow  FullControl
         BUILTIN\Administrators Allow  FullControl
         S-1-5-21-2465844383-291681238-1546083700-500 Allow  FullControl
Audit  :
Sddl   : O:S-1-5-93-2-1G:S-1-5-93-2-1D:AI(A;OICIID;FA;;;WD)(A;OICIID;FA;;;SY)(A;OICIID;FA;;;BA)(A;OICIID;FA;;;S-1-5-21-2465844383-291681238-1546083700-500)

And the above error occurs after attempting the generation, and the permissions change to:

PS C:\> Get-ACL C:\bamboo-home\xml-data\configuration\ | fl

Path   : Microsoft.PowerShell.Core\FileSystem::C:\bamboo-home\xml-data\configuration\
Owner  : User Manager\ContainerAdministrator
Group  : User Manager\ContainerAdministrator
Access : Everyone Allow  FullControl
Audit  :
Sddl   : O:S-1-5-93-2-1G:S-1-5-93-2-1D:AI(A;OICI;FA;;;WD)

Why does the default account (presumably an Administrator named containeradministrator) lose access to this directory when it seems to indicate it has ownership? And why can't it create the file (or folder, for that matter) in the first place, since in both cases, "Everyone" should have full access?


问:
CSS - Apply conditional style to table row
I have a requirement where i have to apply conditional style for my table rows but the style never gets applied.

.test1 {
  background-color: '#ffbf00';
}
.test2 {
  background-color: '#92D050';
}
.test3 {
  background-color: ' ';
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table id="testTable">
  <tr styleClass="test1">
    <td></td>
    <td></td>
  </tr>
</table></code>```

But the styling will never be applied. something i am missing?

答:
you need to add class name and styleClass="test1" not proper syntax

so update

```<code>styleClass="test1"
</code>```

to

```<code>class="test1"
</code>```

and one more thing your style code is not perfect
so also update

```<code>background-color: '#92D050';
</code>```

to

```<code>background-color: #92D050;
</code>```

cause this is also syntax error
other code is ok

  .test1 {
        background-color: #ffbf00;
    }
    .test2  {
        background-color: #92D050;
    }
    .test3  {
        background-color: rebeccapurple;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table id="testTable">
    <tr class="test1">
        <td>test1</td>
        <td>test1</td>
    </tr>
    <tr class="test2">
        <td>test2</td>
        <td>test3</td>
    </tr>
    <tr class="test3">
        <td>test4</td>
        <td>test5</td>
    </tr>
</table></code>```

Body:
I have a requirement where i have to apply conditional style for my table rows but the style never gets applied.

.test1 {
  background-color: '#ffbf00';
}
.test2 {
  background-color: '#92D050';
}
.test3 {
  background-color: ' ';
}

But the styling will never be applied. something i am missing?

Body:
you need to add class name and styleClass="test1" not proper syntax

so update

styleClass="test1"

to

class="test1"

and one more thing your style code is not perfect
so also update

background-color: '#92D050';

to

background-color: #92D050;

cause this is also syntax error
other code is ok

  .test1 {
        background-color: #ffbf00;
    }
    .test2  {
        background-color: #92D050;
    }
    .test3  {
        background-color: rebeccapurple;
    }

<table id="testTable">
    <tr class="test1">
        <td>test1</td>
        <td>test1</td>
    </tr>
    <tr class="test2">
        <td>test2</td>
        <td>test3</td>
    </tr>
    <tr class="test3">
        <td>test4</td>
        <td>test5</td>
    </tr>
</table>


问:
Web service client with Java application and SSL
I am developing a Java desktop application and I want to consume a web service in it. The web service requires two-way SSL connection with message level security using binarysecuritytoken. I am using NetBeans IDE 6.9.1 with JDK 1.6.0.23 and JAX-WS as ws wrapper. How can I communicate with the ws without using any web server on client machine. Most of the stuff I read needs to have tomcat or some other web server on client machine (configuring the keystore in tomcat or so...). Is it possible to do?  Please suggest some article for SSL based ws client for Java desktop application.

答:
Consuming web services in JavaSE - see NetBeans tutorial

Use BindingProvider to set your properties before you invoke the service. See example of using BindingProvider here


问:
I want to Run my php file depending on the client possibility
I have a php file called reportemail.php  file, And I have one drop down with 3 values like daily,weekly,monthly

If the client set time as daily I want to run the file(reportemail) and I want to send email every morning..and I want to do this is in localhost only,not in server.and I want this should be happen if the system is in shutdown mode also.

I already tried with cron.bat file it is working fine,but there manually I gave time..instead of giving manually I want to give dynamically.

Here is how I did in cron.bat file

```<code>E:\xampp\php\php.exe -f E:xampp/htdocs/custom/reportemail.php
</code>```

And in reportemail.php file i have my email code and script code like this

```<code><script>
    setTimeout(function () {
        window.location.reload();
    }, 5 * 60 * 1000);

    document.write(new Date());
</script>
</code>```

答:
Using cron is still the way to go here.  You just want to separate the scheduler from the scheduled events a little bit more.

Don't try to have the users create/modify the cron job scheduling itself.  Instead, schedule a universal cron job to execute at the narrowest time frame (daily).  That single job would:

Check for user reports scheduled to run.

Check when those reports were last successfully run and if it's time to do them again.

Run the reports.

So instead of scheduling cron jobs, your users are simply saving a record to a database indicating when to run their reports.  For example, consider a table like this:

```<code>UserReports
----------
ID (PK)
UserID (which user)
ReportID (which report to run)
ScheduleID (which frequency - daily, weekly, etc.)
LastRunDate (date of the last successful run)
</code>```

Any time the cron job executes, it would select from this table any records which meet the criteria:

ScheduleID is daily and LastRunDate is 1+ days ago, or

ScheduleID is weekly and LastRunDate is 7+ days ago, or

ScheduleID is monthly and LastRunDate is 1+ month ago

Loop through the records which meet those criteria, run the reports, update the records with a new LastRunDate of today.

Body:
I have a php file called reportemail.php  file, And I have one drop down with 3 values like daily,weekly,monthly

If the client set time as daily I want to run the file(reportemail) and I want to send email every morning..and I want to do this is in localhost only,not in server.and I want this should be happen if the system is in shutdown mode also.

I already tried with cron.bat file it is working fine,but there manually I gave time..instead of giving manually I want to give dynamically.

Here is how I did in cron.bat file

E:\xampp\php\php.exe -f E:xampp/htdocs/custom/reportemail.php

And in reportemail.php file i have my email code and script code like this

Body:
Using cron is still the way to go here.  You just want to separate the scheduler from the scheduled events a little bit more.

Don't try to have the users create/modify the cron job scheduling itself.  Instead, schedule a universal cron job to execute at the narrowest time frame (daily).  That single job would:

Check for user reports scheduled to run.

Check when those reports were last successfully run and if it's time to do them again.

Run the reports.

So instead of scheduling cron jobs, your users are simply saving a record to a database indicating when to run their reports.  For example, consider a table like this:

UserReports
----------
ID (PK)
UserID (which user)
ReportID (which report to run)
ScheduleID (which frequency - daily, weekly, etc.)
LastRunDate (date of the last successful run)

Any time the cron job executes, it would select from this table any records which meet the criteria:

ScheduleID is daily and LastRunDate is 1+ days ago, or

ScheduleID is weekly and LastRunDate is 7+ days ago, or

ScheduleID is monthly and LastRunDate is 1+ month ago

Loop through the records which meet those criteria, run the reports, update the records with a new LastRunDate of today.


问:
How to decode a bitmap from a local file deployed with Android application
I am going through http://developer.xamarin.com/guides/cross-platform/xamarin-forms/working-with/images/
and trying to get the Local Images working with Android however I am experiencing some issues when attempting to do something in normal monodroid just as a further test.  I'm using a SharedProject, just for reference.

I have added the test image at Resources/drawable (test1.png), and also setting the Build Action as AndroidResource as it describes, and if I do the following in Xamarin.Forms it works:-

```<code>Xamarin.Forms.Image myimage = new Image();
myimage.Source = ImageSource.FromFile("test1.png");
</code>```

However, if I try and retrieve the same file via the following it comes back as null.

```<code> Android.Graphics.Bitmap objBitmapImage = Android.Graphics.BitmapFactory.DecodeFile("test1.png")
</code>```

Does anyone know why this is null and how to correct?

答:
```<code>string scr = "@drawable/test1.png";
ImageView iv = new ImageView(context);
Bitmap bm = BitmapFactory.DecodeFile(src);
if (bm != null)
    iv.SetImageBitmap(bm);
</code>```

Body:
I am going through http://developer.xamarin.com/guides/cross-platform/xamarin-forms/working-with/images/
and trying to get the Local Images working with Android however I am experiencing some issues when attempting to do something in normal monodroid just as a further test.  I'm using a SharedProject, just for reference.

I have added the test image at Resources/drawable (test1.png), and also setting the Build Action as AndroidResource as it describes, and if I do the following in Xamarin.Forms it works:-

Xamarin.Forms.Image myimage = new Image();
myimage.Source = ImageSource.FromFile("test1.png");

However, if I try and retrieve the same file via the following it comes back as null.

 Android.Graphics.Bitmap objBitmapImage = Android.Graphics.BitmapFactory.DecodeFile("test1.png")

Does anyone know why this is null and how to correct?


问:
Allow "semi anonymous" authentication
I have a case where I need some controller methods to be accessible either by an authenticated user, or if the request contains a sort of "acccess token" in the url.

For example:

Either an authenticated user could make a call to:
https://example.com/some/resource

Or a non authenticated user could make the same call, but add some kind of token to the url (or as a header):
https://example.com/some/resource?token=123abc

The token does not have to be super secret, only something hard to guess.

```<code>[AllowSpecialToken]
[HttpGet]
[Route("some/resource")]
public async Task<string> GetSomeResource()
{
    return "some resource";
}
</code>```

What I'm struggling with is how to write the AllowSpecialTokenAttribute. And how to get that to run before the authentication (using OpenIddict) we have in place now.

Is this a stupid use case? Should I find another solution?

To give some context: We have a SPA that calls our API. Some pages of the SPA can be shared with others (non user) just by sending a link. That link will contain the token. The content of those pages are not critical security wise, but they shouldn't be completely open.

答:
You need to make your own authentication attribute. I've done something like that in the past, here is my stub at it:

```<code>public class TokenAuthenticationAttribute : AuthorizeAttribute
{
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        // this will read `token` parameter from your URL
        ValueProviderResult valueProvided = filterContext.Controller.ValueProvider.GetValue("token");
        if (valueProvided == null)
        {
            filterContext.Result = new System.Web.Mvc.HttpStatusCodeResult((int)System.Net.HttpStatusCode.Forbidden);
            return;
        }

        var providedToken = valueProvided.AttemptedValue;

        var storedToken = "12345"; // <-- get your token value from DB or something

        if (storedToken != providedToken)
        {
            filterContext.Result = new System.Web.Mvc.HttpStatusCodeResult((int)System.Net.HttpStatusCode.Forbidden);
            return;
        }
    }
}
</code>```

Then decorate your action with the attribute:

```<code>[TokenAuthentication]
[HttpGet]
[Route("some/resource")]
public async Task<string> GetSomeResource()
{
    return "some resource";
}
</code>```

And get your URI looking like https:\\www.example.com\api\some\resource?token=12345

Title: Allow "semi anonymous" authentication

Body:
I have a case where I need some controller methods to be accessible either by an authenticated user, or if the request contains a sort of "acccess token" in the url.

For example:

Either an authenticated user could make a call to:
https://example.com/some/resource

Or a non authenticated user could make the same call, but add some kind of token to the url (or as a header):
https://example.com/some/resource?token=123abc

The token does not have to be super secret, only something hard to guess.

[AllowSpecialToken]
[HttpGet]
[Route("some/resource")]
public async Task<string> GetSomeResource()
{
    return "some resource";
}

What I'm struggling with is how to write the AllowSpecialTokenAttribute. And how to get that to run before the authentication (using OpenIddict) we have in place now.

Is this a stupid use case? Should I find another solution?

To give some context: We have a SPA that calls our API. Some pages of the SPA can be shared with others (non user) just by sending a link. That link will contain the token. The content of those pages are not critical security wise, but they shouldn't be completely open.

Body:
You need to make your own authentication attribute. I've done something like that in the past, here is my stub at it:

public class TokenAuthenticationAttribute : AuthorizeAttribute
{
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        // this will read `token` parameter from your URL
        ValueProviderResult valueProvided = filterContext.Controller.ValueProvider.GetValue("token");
        if (valueProvided == null)
        {
            filterContext.Result = new System.Web.Mvc.HttpStatusCodeResult((int)System.Net.HttpStatusCode.Forbidden);
            return;
        }

        var providedToken = valueProvided.AttemptedValue;

        var storedToken = "12345"; // <-- get your token value from DB or something

        if (storedToken != providedToken)
        {
            filterContext.Result = new System.Web.Mvc.HttpStatusCodeResult((int)System.Net.HttpStatusCode.Forbidden);
            return;
        }
    }
}

Then decorate your action with the attribute:

[TokenAuthentication]
[HttpGet]
[Route("some/resource")]
public async Task<string> GetSomeResource()
{
    return "some resource";
}

And get your URI looking like https:\\www.example.com\api\some\resource?token=12345


问:
How to transpose this table in SQL Server 2012

I want to transpose this table which has only 1 row with client id and the response columns as response1, response2 and so on.

I tried with pivot but not able to apply correctly

答:
```<code>CREATE TABLE #table
(
    ClientID INT,
   Response VARCHAR(20)
);

INSERT INTO #table (ClientID, Response)
VALUES (3316, 'omellette'),
      (3316, 'mmer'),
      (3316, 'joy'),
      (3316, 'gift'),
      (3316, 'strong'),
      (3316, 'rrailores'),
      (3316, 'something else');

select * from #table

;with cte
as
(
select * ,ROW_NUMBER () over (Order by (select null)) as rank1
from #table
)

select ClientID,[1] as response1,[2] as response2,[3] as response3,
[4] as response4,[5] as response5,[6] as response6,[7] as response7
from cte
pivot (max(response) for rank1 in([1],[2],[3],[4],[5],[6],[7])) AS  d
</code>```


问:
How to pass a dynamic value in angular2-counto
I'm using the following library:

https://github.com/izupet/angular2-counto

I'm getting an error when I pass a dynamic value.

So in my component app.component.html:

If I use interpolation:

```<code><div counto [step]="30" [countTo]="'{{value}}'" [countFrom]="0 [duration]="4" (countoChange)="counto = $event" (countoEnd)="onCountoEnd()">{{counto | currency:'EUR':true:'1.2-2'}}</div>
</code>```

I get an error related with the double braces syntax:

```<code>[countTo]="'{{value}}'"
</code>```

Otherwise, without them it works:

```<code> [countTo]="10"
</code>```

Here for [countTo] attribute passing the value from component.

For app.component.ts

```<code>export class AppComponent {

  value=10;

}
</code>```

答:
Try to remove quotes from binding like this:

[countTo]="{{value}}"

or bind to change function like this:

(countoChange)="handleCountChange($event)"

and then in Component code:

handleCountChange(data) {
 return this.value; // or whatever you like
}

Body:
I'm using the following library:

https://github.com/izupet/angular2-counto

I'm getting an error when I pass a dynamic value.

So in my component app.component.html:

If I use interpolation:

{{counto | currency:'EUR':true:'1.2-2'}}

I get an error related with the double braces syntax:

[countTo]="'{{value}}'"

Otherwise, without them it works:

 [countTo]="10"

Here for [countTo] attribute passing the value from component.

For app.component.ts

export class AppComponent {

  value=10;

}


问:
Get property Type and convert String to corresponding Type
I am using CSOM to update some Task of a Project Server Project.

Which property has to be updated is not defined the code finds out dynamically what to update based on the property name as String.

For better understanding I wore a simplified version of my code

```<code>//fieldName = "ActualWorkTimeSpan"; value = "16:00:00";
private void Start(string fieldName, string value)
{
    DraftTask draftTask = GetDraftTask();

    Update(draftTask, fieldName, value);

    PublishAndCheckin(draftTask);
}

private static void Update(DraftTask draftTask, string fieldName, string value)
{
    // skip updating if field is Equal
    if (GetPropValue(draftTask, fieldName).ToString() == value)
        return;

    // update of the task
    SetPropValue(draftTask, fieldName, value);

}

private static object GetPropValue(object src, string propName)
{
    return src.GetType().GetProperty(propName).GetValue(src, null);
}

private static void SetPropValue(DraftTask src, string propName, object value)
{
    src.GetType().GetProperty(propName).SetValue(src, value);
}
</code>```

I can use GetPropValue() without problem but for SetPropValue() I would need the value to be in the right type.

In this case it would be "System.TimeSpan" for the property "ActualWorkTimeSpan". So I would need to convert the string "15:00:00" to TimeSpan.

It would be easy to do if it were TimeSpan every time, but I could be that the Field "Cost" is set to be updated.

```<code>Update(draftTask, "Cost", "500");
</code>```

So my question is if it is Possible to find out what type the field has and than convert my value to the same type.

答:
You can do this, by using Convert.ChangeType method.

```<code>private static void SetPropValue(DraftTask src, string propName, object value)
{
    var property = src.GetType().GetProperty(propName);
    var valueToSet = Convert.ChangeType(value, property.PropertyType);
    property.SetValue(src, valueToSet);
}
</code>```

ref, is useless in this case. It is used when you assign the parameter in the called method and have it also be assigned at the calling site (the scope of the calling method).

Body:
I am using CSOM to update some Task of a Project Server Project.

Which property has to be updated is not defined the code finds out dynamically what to update based on the property name as String.

For better understanding I wore a simplified version of my code

//fieldName = "ActualWorkTimeSpan"; value = "16:00:00";
private void Start(string fieldName, string value)
{
    DraftTask draftTask = GetDraftTask();

    Update(draftTask, fieldName, value);

    PublishAndCheckin(draftTask);
}

private static void Update(DraftTask draftTask, string fieldName, string value)
{
    // skip updating if field is Equal
    if (GetPropValue(draftTask, fieldName).ToString() == value)
        return;

    // update of the task
    SetPropValue(draftTask, fieldName, value);

}

private static object GetPropValue(object src, string propName)
{
    return src.GetType().GetProperty(propName).GetValue(src, null);
}

private static void SetPropValue(DraftTask src, string propName, object value)
{
    src.GetType().GetProperty(propName).SetValue(src, value);
}

I can use GetPropValue() without problem but for SetPropValue() I would need the value to be in the right type.

In this case it would be "System.TimeSpan" for the property "ActualWorkTimeSpan". So I would need to convert the string "15:00:00" to TimeSpan.

It would be easy to do if it were TimeSpan every time, but I could be that the Field "Cost" is set to be updated.

Update(draftTask, "Cost", "500");

So my question is if it is Possible to find out what type the field has and than convert my value to the same type.

Body:
You can do this, by using Convert.ChangeType method.

private static void SetPropValue(DraftTask src, string propName, object value)
{
    var property = src.GetType().GetProperty(propName);
    var valueToSet = Convert.ChangeType(value, property.PropertyType);
    property.SetValue(src, valueToSet);
}

ref, is useless in this case. It is used when you assign the parameter in the called method and have it also be assigned at the calling site (the scope of the calling method).


问:
Microservices internal communication
I'm learning APIs with microservies architect. Here is small description about the setup

I've two microservice applications and API gateway

All the applications including API gateway is nodeJs - express app.

Auth logic - JWT, handled on API gateway

Pass each incoming API gateway request to each of the microservice applications using http-proxy.

Also passes the user info as proxy header.

Client request flow:

Client requesting API1 from microservice1 with JWT token which will be authenticated at API gateway and then information will be served from microservice1. which is fine.

But I've one private API2 which should not be allowed from client side. Only internal applications can use it, but it should be callable upon another request from the client side.

eg.

```<code>client request -> /API/Gateway1 (has JWT)
/API/Gateway1 -> API1 (has valid user)
API1 -> /API/Gateway2 (has valid user)
/API/Gateway2 -> API2 (has valid user)
</code>```

Question:

How can I protect API2 from the client side, what if client fakes the valid user header.

答:
What you want to do is prevent API2 from accepting outside traffic, there are a number of ways you can do this for example:-

White-list a set of IP addresses that correspond to the possible IP addresses of API1

Put all your APIs in a VPN and only expose API1 to public traffic

create some internal auth strategy such as have API1 sign requests to API2 with some secret key.

Title: Microservices internal communication

Body:
I'm learning APIs with microservies architect. Here is small description about the setup

I've two microservice applications and API gateway

All the applications including API gateway is nodeJs - express app.

Auth logic - JWT, handled on API gateway

Pass each incoming API gateway request to each of the microservice applications using http-proxy.

Also passes the user info as proxy header.

Client request flow:

Client requesting API1 from microservice1 with JWT token which will be authenticated at API gateway and then information will be served from microservice1. which is fine.

But I've one private API2 which should not be allowed from client side. Only internal applications can use it, but it should be callable upon another request from the client side.

eg.

client request -> /API/Gateway1 (has JWT)
/API/Gateway1 -> API1 (has valid user)
API1 -> /API/Gateway2 (has valid user)
/API/Gateway2 -> API2 (has valid user)

Question:

How can I protect API2 from the client side, what if client fakes the valid user header.