问:
MongoError: Invalid Operation, No operations in bulk for insertion
Below is my code for bulk insertion.

```<code>var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var UserSchema = new Schema({
    "xyz": String
}, {
    collection: 'user'
});

Api.prototype.Users = mongoose.model('Users', UserSchema);

resultData = [{
    "xyz": "abc"
}, {
    "xyz": "44545"
}, {
    "xyz": "545"
}]

Api.prototype.Users.collection.insert(resultData, function(err, data) {
    if(err) {
        console.log(err);
    } else {
        console.log("User inserted : " + data.result.n);
    }
});
</code>```

But i'm getting this error: MongoError: Invalid Operation, No operations in      bulk

MongoError: Invalid Operation, No operations in bulk
      at Function.MongoError.create (/myapp/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/error.js:31:11)
      at toError (/myapp/node_modules/mongoose/node_modules/mongodb/lib/utils.js:114:22)

答:
I have had this error when trying to bulk insert an empty array using insertMany. You should check for an empty array before attempting a bulk insert.</p>

```<code>if (resultData.length > 0) {
  // do bulk insert...
}
</code>```

Body:
Below is my code for bulk insertion.

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var UserSchema = new Schema({
    "xyz": String
}, {
    collection: 'user'
});

Api.prototype.Users = mongoose.model('Users', UserSchema);

resultData = [{
    "xyz": "abc"
}, {
    "xyz": "44545"
}, {
    "xyz": "545"
}]

Api.prototype.Users.collection.insert(resultData, function(err, data) {
    if(err) {
        console.log(err);
    } else {
        console.log("User inserted : " + data.result.n);
    }
});

But i'm getting this error: MongoError: Invalid Operation, No operations in      bulk

MongoError: Invalid Operation, No operations in bulk
      at Function.MongoError.create (/myapp/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/error.js:31:11)
      at toError (/myapp/node_modules/mongoose/node_modules/mongodb/lib/utils.js:114:22)

Body:
I have had this error when trying to bulk insert an empty array using insertMany. You should check for an empty array before attempting a bulk insert.

if (resultData.length > 0) {
  // do bulk insert...
}


来源: stackexchange

问:
How to specifiy the java/android platform with IntelliJ-IDEA?
I wanted to try out IntelliJ-IDEA but my experiments failed in a very early state. The Problem is that I found no way to set the Java platforms to be used.

Standard Java fails @Override annotation as IntelliJ-IDEA fails to to use the installed Java 6.

Android tells me to set the Android platform - only there is no setting so be seen to set any platform.

So what am I missing here?

答: Please refer to the official documentation. Also be aware of this issue.</p>

ContentLicense: CC BY-SA 2.5


问:
Reports based on multiple tables MSAccess
I designed a report(salary slip) with many controls(text boxes) in MSAccess 2016.
There are 2 tables Employee details and salary details.
Some controls that need data from employee details table and some from salary table.
I have 2 primary keys

Sl.No

Employee id

for both the tables.
and I have connected the employee id through relationship.
How to specify the expression in the text boxes so that i get the record that matches both the table?

答:
Use a query as record source of your report instead of a table. Then you don't need any expressions in the textboxes, just the column names. I usually give the query the same name as the report but with another prefix. E.g. for report rptSalary the query is named qrptSalary.

```<code>SELECT * FROM
    Employee E
    LEFT JOIN SalaryDetails S
        ON E.EmployeeID = S.EmployeeID
</code>```

In the report, you can insert group headers and footers. You would use EmployeeID as grouping column. Then you can place the employee fields in the employee group header, the salary details in the details section and any sums in the group footer.

ContentLicense: CC BY-SA 3.0

Body:
Use a query as record source of your report instead of a table. Then you don't need any expressions in the textboxes, just the column names. I usually give the query the same name as the report but with another prefix. E.g. for report rptSalary the query is named qrptSalary.

SELECT * FROM
    Employee E
    LEFT JOIN SalaryDetails S
        ON E.EmployeeID = S.EmployeeID

In the report, you can insert group headers and footers. You would use EmployeeID as grouping column. Then you can place the employee fields in the employee group header, the salary details in the details section and any sums in the group footer.


问:
Using IS NULL to convert NULL dates
I'm running a query to change some returned data around in SQL Server 2016, and I am getting a conversion error (Conversion failed when converting date and/or time from character string).

```<code>SELECT jobs.name,
       CASE WHEN jact.start_execution_date IS NULL THEN 'No Execution'
            ELSE jact.start_exeuction_date
       END AS start_execution_date
FROM   msdb.dbo.sysjobactivity jact
       INNER JOIN msdb.dbo.sysjobs jobs
         ON jact.job_id = jobs.job_id
</code>```

The start_execution_date column is a DATETIME type. This column either has a datetime format of (YYYY-MM-DD HH:MM:SS.mmm) or NULL in it. I even tried using COALESCE to make the code a little easier to read but that also did not work and gave the same error. When viewing the returned result set up to the point of the error, it is failing at the first row that has a NULL in this column. What am I doing wrong/not considering?

```<code>SELECT COALESCE(jact.start_execution_date, 'No Execution')
</code>```

答:
Presumably, start_execution_date is a date.  So, you need to convert it.  The simplest way is:

```<code>SELECT . . .,
       COALESCE(CONVERT(VARCHAR(255), jact.start_execution_date),
                'No Execution'
               ) as start_execution_date
FROM msdb.dbo.sysjobactivity jact INNER JOIN
     msdb.dbo.sysjobs jobs
     ON jact.job_id = jobs.job_id;
</code>```

You can add a third parameter that specifies the format of the result.  Or, use the FORMAT() function itself.

Title: Using IS NULL to convert NULL dates

Body:
I'm running a query to change some returned data around in SQL Server 2016, and I am getting a conversion error (Conversion failed when converting date and/or time from character string).

SELECT jobs.name,
       CASE WHEN jact.start_execution_date IS NULL THEN 'No Execution'
            ELSE jact.start_exeuction_date
       END AS start_execution_date
FROM   msdb.dbo.sysjobactivity jact
       INNER JOIN msdb.dbo.sysjobs jobs
         ON jact.job_id = jobs.job_id

The start_execution_date column is a DATETIME type. This column either has a datetime format of (YYYY-MM-DD HH:MM:SS.mmm) or NULL in it. I even tried using COALESCE to make the code a little easier to read but that also did not work and gave the same error. When viewing the returned result set up to the point of the error, it is failing at the first row that has a NULL in this column. What am I doing wrong/not considering?

SELECT COALESCE(jact.start_execution_date, 'No Execution')

Body:
Presumably, start_execution_date is a date.  So, you need to convert it.  The simplest way is:

SELECT . . .,
       COALESCE(CONVERT(VARCHAR(255), jact.start_execution_date),
                'No Execution'
               ) as start_execution_date
FROM msdb.dbo.sysjobactivity jact INNER JOIN
     msdb.dbo.sysjobs jobs
     ON jact.job_id = jobs.job_id;

You can add a third parameter that specifies the format of the result.  Or, use the FORMAT() function itself.


问:
How to make Nav resposive
Demo app you is here: App

Nav looks as I want on small screen, only  'Home' link and toggle button on the right.

Toggle button works, but it is showing elements inline, I would like to display elements one belove other

@media screen and (max-width: 600px) {
  /*.topnav li:not(:first-child) {display:none;}*/
  .topnav li:not(:nth-child(2)) {display:none;}
  .topnav a.icon {
    float: right;
    display: block;
  }
  .topnav li {
  display: inline-block;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav id="main">
  <div class="topnav" id="myTopnav">

  <ul>
    <li class="logo">HOME.</li>
    <li>HOME</li>
    {{#if user.admin }}
    <li class="active"><i class="fa fa-cogs" aria-hidden="true"></i> Administration</li>
    {{/if}}
    <li>

        <i class="fa fa-shopping-basket" aria-hidden="true"></i> Shopping Cart
        <span class="badge">{{ session.cart.totalQty }}</span>

    </li>
    <li>
      <i class="fa fa-envelope-o" aria-hidden="true"></i></i> Contact Us
    </li>
    <li class="dropdown">
      <span class="glyphicon glyphicon-user" aria-hidden="true"></span> User <span class="caret"></span>
      <ul class="dropdown-menu">
        {{# if login }}
          <li>User Account</li>
          <li role="separator" class="divider"></li>
          <li>Logout</li>
        {{ else }}
          <li>Sing in</li>
          <li role="separator" class="divider"></li>
          <li>Sing up</li>
        {{/if}}
      </ul>
    </li>
    ☰
  </ul>
</div>
</nav>

<script type="text/javascript" src="javascripts/navbar.js"></script></code>```

答:
Add display:block to nav ul when below 600px:

```<code>@media screen and (max-width: 600px) {
  /*.topnav li:not(:first-child) {display:none;}*/
  .topnav li:not(:nth-child(2)) {display:none;}
  .topnav a.icon {
    float: right;
    display: block;
  }
  .topnav li {
    display: inline-block;
  }
  /*Add the following*/
  nav ul{
    display:block;
  }
}
</code>```

Title: How to make Nav resposive

Body:
Demo app you is here: App

Nav looks as I want on small screen, only  'Home' link and toggle button on the right.

Toggle button works, but it is showing elements inline, I would like to display elements one belove other

@media screen and (max-width: 600px) {
  /*.topnav li:not(:first-child) {display:none;}*/
  .topnav li:not(:nth-child(2)) {display:none;}
  .topnav a.icon {
    float: right;
    display: block;
  }
  .topnav li {
  display: inline-block;
  }
}

HOME.

HOME

    {{#if user.admin }}

 Administration

    {{/if}}

         Shopping Cart
        {{ session.cart.totalQty }}

       Contact Us

       User

        {{# if login }}

User Account

Logout

        {{ else }}

Sing in

Sing up

        {{/if}}

    ☰

Body:
Add display:block to nav ul when below 600px:

@media screen and (max-width: 600px) {
  /*.topnav li:not(:first-child) {display:none;}*/
  .topnav li:not(:nth-child(2)) {display:none;}
  .topnav a.icon {
    float: right;
    display: block;
  }
  .topnav li {
    display: inline-block;
  }
  /*Add the following*/
  nav ul{
    display:block;
  }
}


问:
any way to put pseudo element under backgrond from parent?
i have a fixed header with some menu and there is a second level menu.
the second level menu must slide in but under the background of the parent, is there any way?!
example:

```<code> `https://codepen.io/anon/pen/mwJZbr`
</code>```

the green background must be under the red

答:
Have a look at this. Hope it helps.

header{
  background-color: rgba(255,0,0,0.5);
  height: 50px;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
}
nav ul.second{
  background-color: #3f3;
  width: 300px;
  opacity: 0;
  position: absolute;
  top: -100%;
  transition: all .5s ease;
}
nav ul.second:after{
  content: "";
  display: block;
  width: 100%;
  height: 100px;
}
nav ul li{
  position: relative;
  margin-right: 30px;
  display: inline-block;
}
nav ul li:hover ul{
  top: 34px;
  opacity: 1;
}
nav ul li ul li {
  width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header>
   <nav>
     <ul>
       <li>test</li>
       <li>test2</li>
       <li>test3
         <ul class="second">
           <li>test3.1</li>
           <li>test3.2</li>
         </ul>
       </li>
     </ul>
  </nav>
</header></code>```

Body:
i have a fixed header with some menu and there is a second level menu.
the second level menu must slide in but under the background of the parent, is there any way?!
example:

 `https://codepen.io/anon/pen/mwJZbr`

the green background must be under the red

Body:
Have a look at this. Hope it helps.

header{
  background-color: rgba(255,0,0,0.5);
  height: 50px;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
}
nav ul.second{
  background-color: #3f3;
  width: 300px;
  opacity: 0;
  position: absolute;
  top: -100%;
  transition: all .5s ease;
}
nav ul.second:after{
  content: "";
  display: block;
  width: 100%;
  height: 100px;
}
nav ul li{
  position: relative;
  margin-right: 30px;
  display: inline-block;
}
nav ul li:hover ul{
  top: 34px;
  opacity: 1;
}
nav ul li ul li {
  width: 100%;
}

<header>
   <nav>
     <ul>
       <li>test</li>
       <li>test2</li>
       <li>test3
         <ul class="second">
           <li>test3.1</li>
           <li>test3.2</li>
         </ul>
       </li>
     </ul>
  </nav>
</header>


问:
C# WYSIWYG Web Field by Drag and Drop
I would like to know what type of field is used for a WebEditor (like WebBuilder) to Drag-and-Drop text, input,... in C# ?

I thinking of an HTML field, but not sure.

Thanks in advance.

答: If you mean Web based application, you should take a look at ASP.NET WebForms. If you want to build desktop application, Visual Studio has a project template called Windows Form Application consisting drag drop support. I don't recommend you using Web Form for web-based application, rather use ASP.NET MVC framework for this purpose which does not include drag-drop functionality in development.   </p>

Title: C# WYSIWYG Web Field by Drag and Drop


问:
In Java, why have a code block with no keywords, just curly brackets
I'm re-factoring some inherited code, but was stumped by the design decision and can't figure out the proper terms to google this. My predecessor would use blocks like this one:

```<code>public class ChildClass extends ParentClass {
    {
        inheritedVar = "someVal";
    }

    public ChildClass(){ /* constructor exists */ }
    // rest of code
}
</code>```

What is the point of declaring a block of code with no keyword? It doesn't behave like a static block, I don't believe. Is it an alternative to setting in the constructor? Would this have some effect if a factory was being used (which in this case it's not)? I found a related thread here on this happening in C but the reasoning (scope & variable declaration) didn't seem relevant to Java.

Any thoughts or ideas on the "why" of this would be appreciated. It's easy enough to re-factor this, I'm just curious at this point.

答:
Scope. Any variables declared in the block go out of scope after the block. It's useful to keep variables scoped minimally.

Also, if you define an anonymous inner class, you use this syntax for the constructor.

Body:
I'm re-factoring some inherited code, but was stumped by the design decision and can't figure out the proper terms to google this. My predecessor would use blocks like this one:

public class ChildClass extends ParentClass {
    {
        inheritedVar = "someVal";
    }

    public ChildClass(){ /* constructor exists */ }
    // rest of code
}

What is the point of declaring a block of code with no keyword? It doesn't behave like a static block, I don't believe. Is it an alternative to setting in the constructor? Would this have some effect if a factory was being used (which in this case it's not)? I found a related thread here on this happening in C but the reasoning (scope & variable declaration) didn't seem relevant to Java.

Any thoughts or ideas on the "why" of this would be appreciated. It's easy enough to re-factor this, I'm just curious at this point.


问:
Obtain client's MAC address using Node js
I'm working on a project that will allow my home automation identify who is at home by using their MAC addresses as an identifier.

I've tried to obtain the MAC address of a client on my own network using Nodejs and the NPM module 'arped'

```<code>var arped = require('arped');

console.log(arped.table());
</code>```

It reads the ARP tables though it only outputs a handfull of IPs/MACs. Is there something that I'm missing about ARPs or what?

The output is showing my router, my chromecast, my windows laptop and my iPhone 4. It's not showing another windows laptop and an iPhone SE.

答:
What do you get when running following from command line:

```<code>arp -h
</code>```

Do you get all MACs or same list you get from node.js?
The ones you don't see might be on different subnet and you will not get MAC address for them.

Body:
I'm working on a project that will allow my home automation identify who is at home by using their MAC addresses as an identifier.

I've tried to obtain the MAC address of a client on my own network using Nodejs and the NPM module 'arped'

var arped = require('arped');

console.log(arped.table());

It reads the ARP tables though it only outputs a handfull of IPs/MACs. Is there something that I'm missing about ARPs or what?

The output is showing my router, my chromecast, my windows laptop and my iPhone 4. It's not showing another windows laptop and an iPhone SE.

Body:
What do you get when running following from command line:

arp -h

Do you get all MACs or same list you get from node.js?
The ones you don't see might be on different subnet and you will not get MAC address for them.


问:
SQL proc to calculate check digit for 7 and 12 digit upc
I just had to scour the internet for this code yet again so I figured I would put it here so I can find it a little faster the next time and hopefully you found it a little faster too :)</p>

答:
And here's a MySQL implementation as well.
Note it requires a 13 digit UPC/EAN13 as input, so you should LPAD your input as required.</p>

```<code>drop function if exists barcodify;
delimiter //
 at the last digit.
create function barcodify(upc varchar(15))
    returns varchar(15)
    sql security invoker
begin
    declare i, r, odd, even,result int;

    set odd=0;
    set even =0;
    set i = length(upc);

    while i > 0 do
        set r = substring(upc, i, 1) ;
        if(i % 2 >0) then set odd = odd + r;
        else set even = even + r;
        end if;
        set i = i - 1;
    end while;
    set result = (3*odd)+even;

    if result % 10 =0 then return 0;
    else return (10 - (result %10));
    end if;
end //

delimiter ;
</code>```

Body:
And here's a MySQL implementation as well.
Note it requires a 13 digit UPC/EAN13 as input, so you should LPAD your input as required.

drop function if exists barcodify;
delimiter //
 at the last digit.
create function barcodify(upc varchar(15))
    returns varchar(15)
    sql security invoker
begin
    declare i, r, odd, even,result int;

    set odd=0;
    set even =0;
    set i = length(upc);

    while i > 0 do
        set r = substring(upc, i, 1) ;
        if(i % 2 >0) then set odd = odd + r;
        else set even = even + r;
        end if;
        set i = i - 1;
    end while;
    set result = (3*odd)+even;

    if result % 10 =0 then return 0;
    else return (10 - (result %10));
    end if;
end //

delimiter ;


问:
Atmel Studio atprogram.exe throws TCF Error code 131120
I try to read the device information from an AT32UC3B1128 (using an jtagicemkii) like this

```<code>atprogram.exe -v -i JTAG -d AT32UC3B1128 -cl 100khz info
</code>```

Doing this on my workstation, I get the following output (containing an error message at the bottom):

```<code>StdOut:

Firmware check OK
Tool jtagicemkii has firmware version: 07.27
Target voltage: 3.35 V

Device information:

Name:       AT32UC3B1128
JtagId:     0x81ee703f
Revision:   I
CPU arch.:  AVR32_UC3
Series:

Security bit is not set.

Memory Information:

Address Space    StartAddress            Size

sysreg                    0x0           0x400

dbgreg                    0x0           0x400

base                      0x0     0x100000000
  FLASH            0x80000000         0x20000
  USER_PAGE        0x80800000           0x200
  SRAM                    0x0          0x8000
  USBB_SLAVE       0xd0000000        0x800000
  IO               0xfffe0000         0x20000

fuses              0xfffe1410             0x4

Fuses:
FGPFRLO (0b11111111111111111111111111111111):
   BODEN         0x3L
   BODHYST       OFF
   BODLEVEL      0x3fL
   BOOTPROT      0x7L
   EPFL          OFF
   LOCK15        OFF
   LOCK14        OFF
   LOCK13        OFF
   LOCK12        OFF
   LOCK11        OFF
   LOCK10        OFF
   LOCK9         OFF
   LOCK8         OFF
   LOCK7         OFF
   LOCK6         OFF
   LOCK5         OFF
   LOCK4         OFF
   LOCK3         OFF
   LOCK2         OFF
   LOCK1         OFF
   LOCK0         OFF

StdErr:

[DEBUG] Starting execution of "info"
[DEBUG] Starting process 'C:\Program Files (x86)\Atmel\Studio\7.0\atbackend\atbackend.exe'
[DEBUG] Connecting to TCP:127.0.0.1:49811
[INFO] Connected to jtagicemkii, fw version: 7.27
[INFO] Firmware check OK
[ERROR] Error in TCF lockbit format. Missed key Could not get Module LOCKBIT for AT32UC3B1128. (TCF Error code: 131120)
[DEBUG] Command "info" finished with return code 0
[DEBUG] Exit successfully.
</code>```

As you can see, the following error message is output to standard error:

```<code>[ERROR] Error in TCF lockbit format. Missed key Could not get Module LOCKBIT for AT32UC3B1128. (TCF Error code: 131120)
</code>```

I have no clue how to resolve this error and couldn't find anything useful searching for similar error messages.

I tried it on another PC with the same programmer and hardware and it works fine. The only obvious difference are different versions of Atmel Studio. I have installed the latest version 7.0.1417, while the other PC uses 7.0.1006.

Any ideas?

PS: Atmel Studio itself seems to be working fine. I have no trouble reading fuses and lockbits from the GUI. Also, erasing/programming from command line is working fine as well. Judging from the error, it seems to be something specific to "lockbit format" due to the missing "lockbit module".

答:
I got an official response from Atmel over at AvrFreaks regarding this problem:

We've already fixed this internally. Unfortunately, it won't be available until the next release (was a bit more than just DFP updates, bug AVRSV-7837).

Body:
I try to read the device information from an AT32UC3B1128 (using an jtagicemkii) like this

atprogram.exe -v -i JTAG -d AT32UC3B1128 -cl 100khz info

Doing this on my workstation, I get the following output (containing an error message at the bottom):

StdOut:

Firmware check OK
Tool jtagicemkii has firmware version: 07.27
Target voltage: 3.35 V

Device information:

Name:       AT32UC3B1128
JtagId:     0x81ee703f
Revision:   I
CPU arch.:  AVR32_UC3
Series:

Security bit is not set.

Memory Information:

Address Space    StartAddress            Size

sysreg                    0x0           0x400

dbgreg                    0x0           0x400

base                      0x0     0x100000000
  FLASH            0x80000000         0x20000
  USER_PAGE        0x80800000           0x200
  SRAM                    0x0          0x8000
  USBB_SLAVE       0xd0000000        0x800000
  IO               0xfffe0000         0x20000

fuses              0xfffe1410             0x4

Fuses:
FGPFRLO (0b11111111111111111111111111111111):
   BODEN         0x3L
   BODHYST       OFF
   BODLEVEL      0x3fL
   BOOTPROT      0x7L
   EPFL          OFF
   LOCK15        OFF
   LOCK14        OFF
   LOCK13        OFF
   LOCK12        OFF
   LOCK11        OFF
   LOCK10        OFF
   LOCK9         OFF
   LOCK8         OFF
   LOCK7         OFF
   LOCK6         OFF
   LOCK5         OFF
   LOCK4         OFF
   LOCK3         OFF
   LOCK2         OFF
   LOCK1         OFF
   LOCK0         OFF

StdErr:

[DEBUG] Starting execution of "info"
[DEBUG] Starting process 'C:\Program Files (x86)\Atmel\Studio\7.0\atbackend\atbackend.exe'
[DEBUG] Connecting to TCP:127.0.0.1:49811
[INFO] Connected to jtagicemkii, fw version: 7.27
[INFO] Firmware check OK
[ERROR] Error in TCF lockbit format. Missed key Could not get Module LOCKBIT for AT32UC3B1128. (TCF Error code: 131120)
[DEBUG] Command "info" finished with return code 0
[DEBUG] Exit successfully.

As you can see, the following error message is output to standard error:

[ERROR] Error in TCF lockbit format. Missed key Could not get Module LOCKBIT for AT32UC3B1128. (TCF Error code: 131120)

I have no clue how to resolve this error and couldn't find anything useful searching for similar error messages.

I tried it on another PC with the same programmer and hardware and it works fine. The only obvious difference are different versions of Atmel Studio. I have installed the latest version 7.0.1417, while the other PC uses 7.0.1006.

Any ideas?

PS: Atmel Studio itself seems to be working fine. I have no trouble reading fuses and lockbits from the GUI. Also, erasing/programming from command line is working fine as well. Judging from the error, it seems to be something specific to "lockbit format" due to the missing "lockbit module".


问:
How to apply manually evolutions in tests with Slick and Play! 2.4
I would like to manually run my evolution script at the beginning of each test file. I'm working with Play! 2.4 and Slick 3.

According to the documentation, the way to go seems to be:

```<code>Evolutions.applyEvolutions(database)
</code>```

but I don't manage to get an instance of my database. In the documentation play.api.db.Databases is imported in order to get a database instance but if I try to import it, I get this error: object Databases is not a member of package play.api.db

How can I get an instance of my database in order to run the evolution script?

Edit: as asked in the comments, here is the entire source code giving the error:

```<code>import models._
import org.scalatest.concurrent.ScalaFutures._
import org.scalatest.time.{Seconds, Span}
import org.scalatestplus.play._
import play.api.db.evolutions.Evolutions
import play.api.db.Databases

class TestAddressModel extends PlaySpec with OneAppPerSuite {
   lazy val appBuilder = new GuiceApplicationBuilder()
   lazy val injector = appBuilder.injector()
   lazy val dbConfProvider = injector.instanceOf[DatabaseConfigProvider]

  def beforeAll() = {
    //val database: Database = ???
    //Evolutions.applyEvolutions(database)
  }

  "test" must {
     "test" in { }
  }
}
</code>```

答:
To have access to play.api.db.Databases, you must add jdbc to your dependencies :

```<code>libraryDependencies += jdbc
</code>```

Hope it helps some people passing here.

EDIT: the code would then look like this :

```<code>import play.api.db.Databases

val database = Databases(
  driver = "com.mysql.jdbc.Driver",
  url = "jdbc:mysql://localhost/test",
  name = "mydatabase",
  config = Map(
    "user" -> "test",
    "password" -> "secret"
  )
)
</code>```

You now have an instance of the DB, and can execute queries on it :

```<code>val statement = database.getConnection().createStatement()
val resultSet = statement.executeQuery("some_sql_query")
</code>```

You can see more from the docs

EDIT: typo

Body:
I would like to manually run my evolution script at the beginning of each test file. I'm working with Play! 2.4 and Slick 3.

According to the documentation, the way to go seems to be:

Evolutions.applyEvolutions(database)

but I don't manage to get an instance of my database. In the documentation play.api.db.Databases is imported in order to get a database instance but if I try to import it, I get this error: object Databases is not a member of package play.api.db

How can I get an instance of my database in order to run the evolution script?

Edit: as asked in the comments, here is the entire source code giving the error:

import models._
import org.scalatest.concurrent.ScalaFutures._
import org.scalatest.time.{Seconds, Span}
import org.scalatestplus.play._
import play.api.db.evolutions.Evolutions
import play.api.db.Databases

class TestAddressModel extends PlaySpec with OneAppPerSuite {
   lazy val appBuilder = new GuiceApplicationBuilder()
   lazy val injector = appBuilder.injector()
   lazy val dbConfProvider = injector.instanceOf[DatabaseConfigProvider]

  def beforeAll() = {
    //val database: Database = ???
    //Evolutions.applyEvolutions(database)
  }

  "test" must {
     "test" in { }
  }
}

Body:
To have access to play.api.db.Databases, you must add jdbc to your dependencies :

libraryDependencies += jdbc

Hope it helps some people passing here.

EDIT: the code would then look like this :

import play.api.db.Databases

val database = Databases(
  driver = "com.mysql.jdbc.Driver",
  url = "jdbc:mysql://localhost/test",
  name = "mydatabase",
  config = Map(
    "user" -> "test",
    "password" -> "secret"
  )
)

You now have an instance of the DB, and can execute queries on it :

val statement = database.getConnection().createStatement()
val resultSet = statement.executeQuery("some_sql_query")

You can see more from the docs

EDIT: typo


问:
htaccess redirect from a folder to another one, but not from its subfolders
can anyone tell me what's the best way to redirect a specific folder to another one?

for example:

```<code>folderName1 -> subFolderName1
            -> subFolderName2
            -> subFolderName3
folderName2
</code>```

and when i get "folderName1" (but not the specific "subFolderName1/2/3") i'm redirect automatically into "folderName2".

thanks a lot!

答:
If my comment above is true then:</p>

```<code>RewriteEngine on

RewriteRule ^folderName1/ /folderName2/ [R,NC]
</code>```

Body:
can anyone tell me what's the best way to redirect a specific folder to another one?

for example:

folderName1 -> subFolderName1
            -> subFolderName2
            -> subFolderName3
folderName2

and when i get "folderName1" (but not the specific "subFolderName1/2/3") i'm redirect automatically into "folderName2".

thanks a lot!

Body:
If my comment above is true then:

RewriteEngine on

RewriteRule ^folderName1/ /folderName2/ [R,NC]


问:
Css cut right side of an image
I have a div with a width of ~ 200px and a height of 145px, inside that div I place an Image which has a height of 145px but a width of 210px, how can I cut 10px from the right side of the Image so that the Image fits into the Content of the div?

答:
Use overflow:hidden for the div.The part of image portion ouside the div will be not be visible

```

Title: Css cut right side of an image

Body:
Use overflow:hidden for the div.The part of image portion ouside the div will be not be visible

<div style="width:200px;height:145px;overflow:hidden;border: 1px solid green;">
  <img src="http://via.placeholder.com/210x145" style="width:210px; height:145px;border: 1px solid red;">
</div>


问:
SQL Server (T-SQL): Avoid call scalar function multiple times
I have a stored procedure which does a SELECT to return some rows. Within the SELECT, I need to check a condition in order to return the correct value for some columns. This condition consists on a scalar function. All times scalar function is called with the same parameter for the row being processed, see below:

```<code>SELECT
    Id,
    Name,
    Surname,
    CASE WHEN (dbo.GetNumTravels(Id) >= 50)
        THEN 10
        ELSE 99
    END as Factor1,
    CASE WHEN (dbo.GetNumTravels(Id) >= 50)
        THEN 15
        ELSE -1
    END as Factor2,
    CASE WHEN (dbo.GetNumTravels(Id) >= 50)
        THEN 30
        ELSE 70
    END as Factor3
FROM
    Employees
WHERE
    DepartmentId = 100
</code>```

I am worried about performance, I mean, I do not like to call scalar function dbo.GetNumTravels multiples times, so how to avoid this and only call it once and then used it all the times I need it?

答:
Scalar user defined functions are infamous for poor performance. If you can convert it to an inline table-valued function you can expect to see performance gains.

If you convert your scalar function to an inline table-valued function you can call it once for each row using cross apply() like so:

```<code>select
     Id,
     Name,
     Surname,
     case when x.NumTravels >= 50
        then 10
        else 99
     end as Factor1,
     case when x.NumTravels >= 50)
        then 15
        else -1
     end as Factor2,
     case when x.NumTravels >= 50
        then 30
        else 70
     end as Factor3
from Employees
  cross apply dbo.GetNumTravels_itvf(e.Id) x
where DepartmentId = 100
</code>```

Reference:

When is a sql function not a function? "If it’s not inline, it’s rubbish." - Rob Farley

Inline Scalar Functions - Itzik Ben-Gan

Scalar functions, inlining, and performance: An entertaining title for a boring post - Adam Machanic

tsql User-Defined Functions: Ten Questions You Were Too Shy To Ask - Robert Sheldon

Body:
I have a stored procedure which does a SELECT to return some rows. Within the SELECT, I need to check a condition in order to return the correct value for some columns. This condition consists on a scalar function. All times scalar function is called with the same parameter for the row being processed, see below:

SELECT
    Id,
    Name,
    Surname,
    CASE WHEN (dbo.GetNumTravels(Id) >= 50)
        THEN 10
        ELSE 99
    END as Factor1,
    CASE WHEN (dbo.GetNumTravels(Id) >= 50)
        THEN 15
        ELSE -1
    END as Factor2,
    CASE WHEN (dbo.GetNumTravels(Id) >= 50)
        THEN 30
        ELSE 70
    END as Factor3
FROM
    Employees
WHERE
    DepartmentId = 100

I am worried about performance, I mean, I do not like to call scalar function dbo.GetNumTravels multiples times, so how to avoid this and only call it once and then used it all the times I need it?

Body:
Scalar user defined functions are infamous for poor performance. If you can convert it to an inline table-valued function you can expect to see performance gains.

If you convert your scalar function to an inline table-valued function you can call it once for each row using cross apply() like so:

select
     Id,
     Name,
     Surname,
     case when x.NumTravels >= 50
        then 10
        else 99
     end as Factor1,
     case when x.NumTravels >= 50)
        then 15
        else -1
     end as Factor2,
     case when x.NumTravels >= 50
        then 30
        else 70
     end as Factor3
from Employees
  cross apply dbo.GetNumTravels_itvf(e.Id) x
where DepartmentId = 100

Reference:

When is a sql function not a function? "If it’s not inline, it’s rubbish." - Rob Farley

Inline Scalar Functions - Itzik Ben-Gan

Scalar functions, inlining, and performance: An entertaining title for a boring post - Adam Machanic

tsql User-Defined Functions: Ten Questions You Were Too Shy To Ask - Robert Sheldon


问:
Keep css animation appearing after unhovering state
I have a div. When I hover into this div, 3 circles should pop in using css animation. But they disappear, when I move the mouse away from the div. How can I make them stay without using jquery? Here is my code:

.circle {
  width: 50px;
  height: 50px;
  border-radius: 50px;
  background-color: blue;
  list-style: none;
  opacity: 0;
  transform: scale(0);
}

.circles li {
  margin-top: 10px;
}

.hoverover:hover + .circles .circle {
  animation: popin .25s forwards;
}

@keyframes popin {
  80% {
    transform: scale(1.15);
  }
  100% {
    opacity: 1;
    transform: scale(1);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="hoverover">Hover Over Me</div>

<ul class="circles">
  <li class="circle"></li>
  <li class="circle"></li>
  <li class="circle"></li>
</ul></code>```

答:
You only need to pause animation with

```<code>-webkit-animation-play-state: paused; /* Chrome, Safari, Opera */
    animation-play-state: paused;
</code>```

And run it again on hover

```<code>-webkit-animation-play-state: running; /* Chrome, Safari, Opera */
    animation-play-state: running;
</code>```

Hover Over Me

```

Body:
I have a div. When I hover into this div, 3 circles should pop in using css animation. But they disappear, when I move the mouse away from the div. How can I make them stay without using jquery? Here is my code:

.circle {
  width: 50px;
  height: 50px;
  border-radius: 50px;
  background-color: blue;
  list-style: none;
  opacity: 0;
  transform: scale(0);
}

.circles li {
  margin-top: 10px;
}

.hoverover:hover + .circles .circle {
  animation: popin .25s forwards;
}

@keyframes popin {
  80% {
    transform: scale(1.15);
  }
  100% {
    opacity: 1;
    transform: scale(1);
  }
}

Hover Over Me

Body:
You only need to pause animation with

-webkit-animation-play-state: paused; /* Chrome, Safari, Opera */
    animation-play-state: paused;

And run it again on hover

-webkit-animation-play-state: running; /* Chrome, Safari, Opera */
    animation-play-state: running;

<html>
<div class="hoverover">Hover Over Me</div>

<ul class="circles">
  <li class="circle"></li>
  <li class="circle"></li>
  <li class="circle"></li>
</ul>

<style>
.circle {
  width: 50px;
  height: 50px;
  border-radius: 50px;
  background-color: blue;
  list-style: none;
  opacity: 0;
  transform: scale(0);
}

.circles li {
  margin-top: 10px;
}

.circles .circle{
   animation: popin .25s forwards;
   -webkit-animation-play-state: paused; /* Chrome, Safari, Opera */
    animation-play-state: paused;
}
.hoverover:hover + .circles .circle {
 -webkit-animation-play-state: running; /* Chrome, Safari, Opera */
    animation-play-state: running;
}

@keyframes popin {
  80% {
    transform: scale(1.15);
  }
  100% {
    opacity: 1;
    transform: scale(1);
  }
}
</style>

</html>


答:
For Fit Image:

```<code>img {
   width:100%;
   //dont need height
}
</code>```

For Cut Image

```<code>div {
  overflow:hidden;
}
</code>```

Title: Css cut right side of an image

Body: I have a div with a width of ~ 200px and a height of 145px, inside that div I place an Image which has a height of 145px but a width of 210px, how can I cut 10px from the right side of the Image so that the Image fits into the Content of the div?

Body:
For Fit Image:

img {
   width:100%;
   //dont need height
}

For Cut Image

div {
  overflow:hidden;
}


问:
How do you make tooltip show up for longer in IE
i got the following

```<code><span id="pageLink" style="cursor:pointer;" onClick="...." title="<%=pHelper.getNameToolTip()%>">
</code>```

in firefox the tooltip stays there until the mouse is moved, but in IE it only stays there for about 5seconds and disappears.

is there a way to make it last longer?

答:
Not with built-in browser tooltips, no.

There are tons of tooltip-like UI components using positioned DOM elements that will give you much finer control of presentation and display duration. I've never used one so couldn't vouch for any of them, so I won't link to any. Googling "JavaScript tooltip" will get you plenty. There are also plenty of tooltip plug-ins for existing libraries like jQuery around.

Body:
i got the following

<span id="pageLink" style="cursor:pointer;" onClick="...." title="<%=pHelper.getNameToolTip()%>">

in firefox the tooltip stays there until the mouse is moved, but in IE it only stays there for about 5seconds and disappears.

is there a way to make it last longer?


问:
C: Separate HEX String into Char Aarray with RegEx
I want to convert hexadecimal strings like:

FE2A8D0000CA372D4F461B1D9A1883A32F018823FFFF60D30000484200000D0A0F270300030006000000B0040307000356A3

Into this format:

```<code>const char msg[] = {0xFE, 0x2A, 0x8D, 0x00, 0x00, 0xCA, 0x37, 0x2D, 0x4F,
0x46, 0x1B, 0x1D, 0x9A, 0x18, 0x83, 0xA3, 0x2F, 0x01, 0x88, 0x23, 0xFF,
0xFF, 0x60, 0xD3, 0x00, 0x00, 0x48, 0x42, 0x00, 0x00, 0x0D, 0x0A, 0x0F,
0x27, 0x03, 0x00, 0x03, 0x00, 0x06, 0x00, 0x00, 0x00, 0xB0, 0x04, 0x03,
0x07, 0x00, 0x03, 0x56, 0xA3};
</code>```

At the moment, I use regex in Notepad++, and works well.
This is the regex:

```<code>find: ([a-z0-9]{2})
replace with: \, 0x\1
(then I remove the first ',')
</code>```

I'm coding in C, I have tried using regex but I can't get it working. How should I use regex for this?

A solution without regex is also fine.

答:
The program in the box below contains the function const char * convert(const char * inb,int idx) that creates a buffer containing the data formatted as you require.

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

#define STR_HELPER(x) #x
#define STR(x) STR_HELPER(x)
#define HEADER1_TEXT "const char msg_"

#define HEADER2_LEN     6   //The number of digits in the costants name msg_nnnn we want

#define HEADER3_TEXT "[] = {"
#define HEADERLENGTH   (strlen(HEADER1_TEXT)+HEADER2_LEN+strlen(HEADER3_TEXT))

#define FOOTER "\n};\n"
#define FOOTERLENGTH    (strlen(FOOTER))

#define INDENT "\n    "
#define INDENTLENGTH    (strlen(INDENT))

#define ITEMxROW        8
#define HEXFIELDLEN     6           // "0xnn, "
#define ROWLEN          (INDENTLENGTH + (ITEMxROW * HEXFIELDLEN))

const char * convert(const char * inb,int idx);

const char * convert(const char * inb,int idx)
{
    char * outb = NULL;
    unsigned int l,rl=0,j;

    l=strlen(inb);
    if (l) {
        j=l/2*HEXFIELDLEN - 1;      //The char used to convert all digit with the format: "0xnn, "
        rl=(j+ROWLEN)/ROWLEN;       //Row number
        j=j + rl*(INDENTLENGTH+1);  // +1 The CR
        j=j + HEADERLENGTH + FOOTERLENGTH;

        outb = malloc(j+11); //+ 11 because the dimension is not correctly computed!!! :(
        memset(outb,0,j+1);

        if (outb!=NULL) {
            strcpy(outb, HEADER1_TEXT);

            sprintf(outb+strlen(outb),"%0" STR(HEADER2_LEN) "d",idx);

            strcat(outb,HEADER3_TEXT);

            rl=0;
            for(j=0;j<l;j+=2) {
                if (j)
                    strcat(outb,", ");

                if ( (rl + HEADER2_LEN) > ROWLEN) {
                    rl=0;
                }

                if (!rl) {
                    rl=INDENTLENGTH;
                    strcat(outb,INDENT);
                }

                strcat(outb,"0x");
                strncat(outb,inb+j,2);

                rl+=HEXFIELDLEN;
            }
        }
    }

    return outb;
}

int main(int argc, char *argv[])
{
    int i,retval=0;
    char * buff=NULL;

    if (argc<2) {
        printf("Usage: %s hex-string [hex-string2] [...] [hex-stringn]\n",basename(argv[0]));
        return 1;
    }

    for(i=1; i<argc; i++) {
        buff=convert(argv[i],i);

        if (buff!=NULL) {
            strcat(buff,FOOTER);
            printf("%s\n",buff);
            free(buff);
        } else {
            retval=1;
            break;
        }
    }

    return retval;
}
</code>```

The program-main calls the function convert sending it the prompt parameters. To decode your string you have to compile the code (for example as convert) and then you have to run it from the system prompt using the string[s] to convert as parameter[s].

```<code>sysprompt: convert FE2A8D0000CA372D4F461B1D9A1883A32F018823FFFF60D30000484200000D0A0F270300030006000000B0040307000356A3
</code>```

the output will be:

```<code>const char msg_000001[] = {
    0xFE, 0x2A, 0x8D, 0x00, 0x00, 0xCA, 0x37, 0x2D,
    0x4F, 0x46, 0x1B, 0x1D, 0x9A, 0x18, 0x83, 0xA3,
    0x2F, 0x01, 0x88, 0x23, 0xFF, 0xFF, 0x60, 0xD3,
    0x00, 0x00, 0x48, 0x42, 0x00, 0x00, 0x0D, 0x0A,
    0x0F, 0x27, 0x03, 0x00, 0x03, 0x00, 0x06, 0x00,
    0x00, 0x00, 0xB0, 0x04, 0x03, 0x07, 0x00, 0x03,
    0x56, 0xA3
};
</code>```

You may convert more strings. For example:

```<code>sysprompt: convert FE55ACA220 56ABFC 4587ABFD
</code>```

the output will be:

```<code>const char msg_000001[] = {
    0xFE, 0x55, 0xAC, 0xA2, 0x20
};

const char msg_000002[] = {
    0x56, 0xAB, 0xFC
};

const char msg_000003[] = {
    0x45, 0x87, 0xAB, 0xFD
};
</code>```

P.S.: In the convert functions there's a piece of code that computes the dimension of the buffer to be used (and allocated) for the conversion. This piece of code is not complitely correct, execuse me! I think you can solve this problem!

Body:
I want to convert hexadecimal strings like:

FE2A8D0000CA372D4F461B1D9A1883A32F018823FFFF60D30000484200000D0A0F270300030006000000B0040307000356A3

Into this format:

const char msg[] = {0xFE, 0x2A, 0x8D, 0x00, 0x00, 0xCA, 0x37, 0x2D, 0x4F,
0x46, 0x1B, 0x1D, 0x9A, 0x18, 0x83, 0xA3, 0x2F, 0x01, 0x88, 0x23, 0xFF,
0xFF, 0x60, 0xD3, 0x00, 0x00, 0x48, 0x42, 0x00, 0x00, 0x0D, 0x0A, 0x0F,
0x27, 0x03, 0x00, 0x03, 0x00, 0x06, 0x00, 0x00, 0x00, 0xB0, 0x04, 0x03,
0x07, 0x00, 0x03, 0x56, 0xA3};

At the moment, I use regex in Notepad++, and works well.
This is the regex:

find: ([a-z0-9]{2})
replace with: \, 0x\1
(then I remove the first ',')

I'm coding in C, I have tried using regex but I can't get it working. How should I use regex for this?

A solution without regex is also fine.

Body:
The program in the box below contains the function const char * convert(const char * inb,int idx) that creates a buffer containing the data formatted as you require.

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

#define STR_HELPER(x) #x
#define STR(x) STR_HELPER(x)
#define HEADER1_TEXT "const char msg_"

#define HEADER2_LEN     6   //The number of digits in the costants name msg_nnnn we want

#define HEADER3_TEXT "[] = {"
#define HEADERLENGTH   (strlen(HEADER1_TEXT)+HEADER2_LEN+strlen(HEADER3_TEXT))

#define FOOTER "\n};\n"
#define FOOTERLENGTH    (strlen(FOOTER))

#define INDENT "\n    "
#define INDENTLENGTH    (strlen(INDENT))

#define ITEMxROW        8
#define HEXFIELDLEN     6           // "0xnn, "
#define ROWLEN          (INDENTLENGTH + (ITEMxROW * HEXFIELDLEN))

const char * convert(const char * inb,int idx);

const char * convert(const char * inb,int idx)
{
    char * outb = NULL;
    unsigned int l,rl=0,j;

    l=strlen(inb);
    if (l) {
        j=l/2*HEXFIELDLEN - 1;      //The char used to convert all digit with the format: "0xnn, "
        rl=(j+ROWLEN)/ROWLEN;       //Row number
        j=j + rl*(INDENTLENGTH+1);  // +1 The CR
        j=j + HEADERLENGTH + FOOTERLENGTH;

        outb = malloc(j+11); //+ 11 because the dimension is not correctly computed!!! :(
        memset(outb,0,j+1);

        if (outb!=NULL) {
            strcpy(outb, HEADER1_TEXT);

            sprintf(outb+strlen(outb),"%0" STR(HEADER2_LEN) "d",idx);

            strcat(outb,HEADER3_TEXT);

            rl=0;
            for(j=0;j<l;j+=2) {
                if (j)
                    strcat(outb,", ");

                if ( (rl + HEADER2_LEN) > ROWLEN) {
                    rl=0;
                }

                if (!rl) {
                    rl=INDENTLENGTH;
                    strcat(outb,INDENT);
                }

                strcat(outb,"0x");
                strncat(outb,inb+j,2);

                rl+=HEXFIELDLEN;
            }
        }
    }

    return outb;
}

int main(int argc, char *argv[])
{
    int i,retval=0;
    char * buff=NULL;

    if (argc<2) {
        printf("Usage: %s hex-string [hex-string2] [...] [hex-stringn]\n",basename(argv[0]));
        return 1;
    }

    for(i=1; i<argc; i++) {
        buff=convert(argv[i],i);

        if (buff!=NULL) {
            strcat(buff,FOOTER);
            printf("%s\n",buff);
            free(buff);
        } else {
            retval=1;
            break;
        }
    }

    return retval;
}

The program-main calls the function convert sending it the prompt parameters. To decode your string you have to compile the code (for example as convert) and then you have to run it from the system prompt using the string[s] to convert as parameter[s].

sysprompt: convert FE2A8D0000CA372D4F461B1D9A1883A32F018823FFFF60D30000484200000D0A0F270300030006000000B0040307000356A3

the output will be:

const char msg_000001[] = {
    0xFE, 0x2A, 0x8D, 0x00, 0x00, 0xCA, 0x37, 0x2D,
    0x4F, 0x46, 0x1B, 0x1D, 0x9A, 0x18, 0x83, 0xA3,
    0x2F, 0x01, 0x88, 0x23, 0xFF, 0xFF, 0x60, 0xD3,
    0x00, 0x00, 0x48, 0x42, 0x00, 0x00, 0x0D, 0x0A,
    0x0F, 0x27, 0x03, 0x00, 0x03, 0x00, 0x06, 0x00,
    0x00, 0x00, 0xB0, 0x04, 0x03, 0x07, 0x00, 0x03,
    0x56, 0xA3
};

You may convert more strings. For example:

sysprompt: convert FE55ACA220 56ABFC 4587ABFD

the output will be:

const char msg_000001[] = {
    0xFE, 0x55, 0xAC, 0xA2, 0x20
};

const char msg_000002[] = {
    0x56, 0xAB, 0xFC
};

const char msg_000003[] = {
    0x45, 0x87, 0xAB, 0xFD
};

P.S.: In the convert functions there's a piece of code that computes the dimension of the buffer to be used (and allocated) for the conversion. This piece of code is not complitely correct, execuse me! I think you can solve this problem!


问:
Safari displays decimal with comma
I have an very frustrating issue in a simple web application I am building.

It works fine in chrome and firefox, but when using the application in Safari on an ipad (which is where it will be used in live) the data is not being formatted correctly.

For example, the data retrieved definitely uses a point (.) as a decimal seperator, and appears as such in firefox/chrome.

However, when viewing the data in safari, it appears as a comma (,) and this is messing up my database inserts.

I tried changing my region and language to United Kingdom but with no effect.

This is how I display one of the decimals in question:

```<code>@Html.LabelFor(model => model.MassOff, new { @class = "viewFieldLabel" }) <br />
@Html.DisplayFor(model => model.MassOff)
</code>```

But it is even worse that this, as I also display decimals elsewhere in a WebGrid, which automatically populates itself based on class properties, so I never explicitly tell it to display the decimal. However, it still appears with a comma in the WebGrid so I ahve no idea how I'm going to change that...

Why would safari do this automatically, when I have at no point asked it to convert any formats? Do I now have to manually try and find all these values and change them using JQuery (which seems absolutely ridiculous), or is there some setting I can change on the ipad or property I need to include in my code?

Update

I managed to fix the way the decimals are displayed with a

```<code>[DisplayFormat(DataFormatString = "{0:0.###}")]
</code>```

Above the properties in question. However, when submitting data, it is still being sent through with a comma (,), so it seems this only changes the way it is displayed.

答:
It seems that you have different navigator.language on your Safari and other browsers.

Please see in this topic:
Best way to determine user's locale within browser

If you can put a server-side script somewhere else on the net that
   simply reads the Accept-Language header and spits it back out as a
   JavaScript file with the header value in the string, eg.:

```<code>var acceptLanguage= 'en-gb,en;q=0.7,de;q=0.3;
</code>```

then you could include a  pointing at that external service in the HTML, and use
   JavaScript to parse the language header. I don't know of any existing
   library code to do this, though, since Accept-Language parsing is
   almost always done on the server side.

Title: Safari displays decimal with comma

Body:
I have an very frustrating issue in a simple web application I am building.

It works fine in chrome and firefox, but when using the application in Safari on an ipad (which is where it will be used in live) the data is not being formatted correctly.

For example, the data retrieved definitely uses a point (.) as a decimal seperator, and appears as such in firefox/chrome.

However, when viewing the data in safari, it appears as a comma (,) and this is messing up my database inserts.

I tried changing my region and language to United Kingdom but with no effect.

This is how I display one of the decimals in question:

@Html.LabelFor(model => model.MassOff, new { @class = "viewFieldLabel" })

@Html.DisplayFor(model => model.MassOff)

But it is even worse that this, as I also display decimals elsewhere in a WebGrid, which automatically populates itself based on class properties, so I never explicitly tell it to display the decimal. However, it still appears with a comma in the WebGrid so I ahve no idea how I'm going to change that...

Why would safari do this automatically, when I have at no point asked it to convert any formats? Do I now have to manually try and find all these values and change them using JQuery (which seems absolutely ridiculous), or is there some setting I can change on the ipad or property I need to include in my code?

Update

I managed to fix the way the decimals are displayed with a

[DisplayFormat(DataFormatString = "{0:0.###}")]

Above the properties in question. However, when submitting data, it is still being sent through with a comma (,), so it seems this only changes the way it is displayed.

Body:
It seems that you have different navigator.language on your Safari and other browsers.

Please see in this topic:
Best way to determine user's locale within browser

If you can put a server-side script somewhere else on the net that
   simply reads the Accept-Language header and spits it back out as a
   JavaScript file with the header value in the string, eg.:

var acceptLanguage= 'en-gb,en;q=0.7,de;q=0.3;

then you could include a  pointing at that external service in the HTML, and use
   JavaScript to parse the language header. I don't know of any existing
   library code to do this, though, since Accept-Language parsing is
   almost always done on the server side.


问:
matching a word (case insensitive) to a list and replace it to the word in the list - C# Regex
lets say my string is "this is a string"

my list is {"tHis", "WoRd, "a", "iS"}

and my regex patern is {"tHis" | "WoRd" | "a" | "iS"}

The desired result is "tHis iS a string"

the only idea i have is looping over the entire list and test it one by one against a substring

答:
```<code>    string input = "this is a string";
    List<string> words = new List<string>(new[] { "tHis", "WoRd", "a", "iS" });
    string pattern = "\\b(" + string.Join("|", words) + ")\\b";
    Regex reg = new Regex(pattern, RegexOptions.IgnoreCase);
    string output = reg.Replace(input, x => words.FirstOrDefault(w => w.Equals(x.Value, StringComparison.CurrentCultureIgnoreCase)));
</code>```


问:
Python Flask app on EC2 AWS
I'm trying to run a simple python flask app on  Amazon Linux AMI. I'm able to show  the Amazon Linux AMI test page but when I try create the proper configuration to run my app I'm facing always the same problem.

```<code>[Fri Sep 16 12:56:39.190230 2016] [:error] [pid 17977] [remote 77.246.17.229:59978] mod_wsgi (pid=17977): Target WSGI script '/var/www/flaskapp/app.wsgi' cannot be loaded as Python module.
[Fri Sep 16 12:56:39.190239 2016] [:error] [pid 17977] [remote 77.246.17.229:59978] mod_wsgi (pid=17977): Exception occurred processing WSGI script '/var/www/flaskapp/app.wsgi'.
[Fri Sep 16 12:56:39.190252 2016] [:error] [pid 17977] [remote 77.246.17.229:59978] Traceback (most recent call last):
[Fri Sep 16 12:56:39.190271 2016] [:error] [pid 17977] [remote 77.246.17.229:59978]   File "/var/www/flaskapp/app.wsgi", line 26, in <module>
[Fri Sep 16 12:56:39.190288 2016] [:error] [pid 17977] [remote 77.246.17.229:59978]     from app import app as application
[Fri Sep 16 12:56:39.190294 2016] [:error] [pid 17977] [remote 77.246.17.229:59978]   File "/var/www/flaskapp/app.py", line 1, in <module>
[Fri Sep 16 12:56:39.190303 2016] [:error] [pid 17977] [remote 77.246.17.229:59978]     from flask import Flask
[Fri Sep 16 12:56:39.190316 2016] [:error] [pid 17977] [remote 77.246.17.229:59978] ImportError: No module named flask
</code>```

My app.py:

```<code>from flask import Flask
app=Flask(__name__)

@app.route('/')
def home():
    return "Hello World!"

if __name__ == "__main__":
    app.run()
</code>```

My app.wsgi:

```<code>import sys
import site
import os
# Add virtualenv site packages
site.addsitedir(os.path.join(os.path.dirname(__file__), '/env/lib/python2.7/site-packages'))

activate_this = '/var/www/flaskapp/env/bin/activate_this.py'
execfile(activate_this, dict(__file__=activate_this))

# Path of execution
sys.path.insert(0,'/var/www/flaskapp')

#import the app
from app import app as application
</code>```

and my httpd.conf:

```<code><VirtualHost *>
    ServerName ec2....
    WSGIDaemonProcess app threads=5 home=/var/www/flaskapp/ python-path=/var/www/flaskapp/env/lib/python2.7 threads=1

    DocumentRoot /var/www/flaskapp

    WSGIScriptAlias / /var/www/flaskapp/app.wsgi
    <Directory /var/www/flaskapp>
            WSGIProcessGroup app
            WSGIApplicationGroup %{GLOBAL}
            Order deny,allow
            Allow from all
    </Directory>
</VirtualHost>
</code>```

If I look at what is installed in the virtualenv wit pip freeze I get this:

```<code>click==6.6
Flask==0.11.1
itsdangerous==0.24
Jinja2==2.8
MarkupSafe==0.23
Werkzeug==0.11.11
</code>```

so Flask is installed. Why I'm not able to import it? What I'm doing wrong?

thanks

答:
On EC2/EB, deploy the flask application through the console by uploading a zip file.
Keep the flask app like a normal flask app on your PC. I guess AWS takes care of WSGI automatically.

Just do the following :

```<code>application = app = Flask(__name__)
......
......
application.run()
</code>```

save this main file as "application.py"

Zip and upload through AWS console and it will run.

Title: Python Flask app on EC2 AWS

Body:
I'm trying to run a simple python flask app on  Amazon Linux AMI. I'm able to show  the Amazon Linux AMI test page but when I try create the proper configuration to run my app I'm facing always the same problem.

[Fri Sep 16 12:56:39.190230 2016] [:error] [pid 17977] [remote 77.246.17.229:59978] mod_wsgi (pid=17977): Target WSGI script '/var/www/flaskapp/app.wsgi' cannot be loaded as Python module.
[Fri Sep 16 12:56:39.190239 2016] [:error] [pid 17977] [remote 77.246.17.229:59978] mod_wsgi (pid=17977): Exception occurred processing WSGI script '/var/www/flaskapp/app.wsgi'.
[Fri Sep 16 12:56:39.190252 2016] [:error] [pid 17977] [remote 77.246.17.229:59978] Traceback (most recent call last):
[Fri Sep 16 12:56:39.190271 2016] [:error] [pid 17977] [remote 77.246.17.229:59978]   File "/var/www/flaskapp/app.wsgi", line 26, in <module>
[Fri Sep 16 12:56:39.190288 2016] [:error] [pid 17977] [remote 77.246.17.229:59978]     from app import app as application
[Fri Sep 16 12:56:39.190294 2016] [:error] [pid 17977] [remote 77.246.17.229:59978]   File "/var/www/flaskapp/app.py", line 1, in <module>
[Fri Sep 16 12:56:39.190303 2016] [:error] [pid 17977] [remote 77.246.17.229:59978]     from flask import Flask
[Fri Sep 16 12:56:39.190316 2016] [:error] [pid 17977] [remote 77.246.17.229:59978] ImportError: No module named flask

My app.py:

from flask import Flask
app=Flask(__name__)

@app.route('/')
def home():
    return "Hello World!"

if __name__ == "__main__":
    app.run()

My app.wsgi:

import sys
import site
import os
# Add virtualenv site packages
site.addsitedir(os.path.join(os.path.dirname(__file__), '/env/lib/python2.7/site-packages'))

activate_this = '/var/www/flaskapp/env/bin/activate_this.py'
execfile(activate_this, dict(__file__=activate_this))

# Path of execution
sys.path.insert(0,'/var/www/flaskapp')

#import the app
from app import app as application

and my httpd.conf:

<VirtualHost *>
    ServerName ec2....
    WSGIDaemonProcess app threads=5 home=/var/www/flaskapp/ python-path=/var/www/flaskapp/env/lib/python2.7 threads=1

    DocumentRoot /var/www/flaskapp

    WSGIScriptAlias / /var/www/flaskapp/app.wsgi
    <Directory /var/www/flaskapp>
            WSGIProcessGroup app
            WSGIApplicationGroup %{GLOBAL}
            Order deny,allow
            Allow from all
    </Directory>
</VirtualHost>

If I look at what is installed in the virtualenv wit pip freeze I get this:

click==6.6
Flask==0.11.1
itsdangerous==0.24
Jinja2==2.8
MarkupSafe==0.23
Werkzeug==0.11.11

so Flask is installed. Why I'm not able to import it? What I'm doing wrong?

thanks

Body:
On EC2/EB, deploy the flask application through the console by uploading a zip file.
Keep the flask app like a normal flask app on your PC. I guess AWS takes care of WSGI automatically.

Just do the following :

application = app = Flask(__name__)
......
......
application.run()

save this main file as "application.py"

Zip and upload through AWS console and it will run.


问:
Read an array recursively
I am learning how to apply recursion to arrays.

For example, I usually read arrays itiratively, this way:

```<code>void read_array(int *a, int n){
        int i;
        for(i = 0; i < n; ++i)
                scanf("%d", &a[i]);
        return;
}
</code>```

I would like to read an array recursively. I wrote the following function:

```<code>void read_array(int *a, int n){
        int i = n - 1;
        if (n < 0)
                return;
        else{
                if(scanf("%d", &a[n - 1 - i]) == 1){
                        read_array(a, n - 1);
                        return;
                }
        }
}
</code>```

It compiles, but when running it trows a segmentation fault error. It confuses me since the function contemplates a base case 0 that should stop it.

答:
Example:</p>

```<code>int read_array_aux(int *i, int *n) {
  if (i == n) {
    return 0;
  }
  if (scanf("%d", i) != 1) {
    return -1;
  }
  return read_array_aux(i + 1, n);
}

int read_array_aux2(int *a, size_t i, size_t n) {
  if (i == n) {
    return 0;
  }
  if (scanf("%d", a + i) != 1) {
    return -1;
  }
  return read_array_aux2(a, i + 1, n);
}

int read_array(int *a, size_t n) {
  return read_array_aux(a, a + n);
  // return read_array_aux2(a, 0, n);
}
</code>```

Title: Read an array recursively

Body:
I am learning how to apply recursion to arrays.

For example, I usually read arrays itiratively, this way:

void read_array(int *a, int n){
        int i;
        for(i = 0; i < n; ++i)
                scanf("%d", &a[i]);
        return;
}

I would like to read an array recursively. I wrote the following function:

void read_array(int *a, int n){
        int i = n - 1;
        if (n < 0)
                return;
        else{
                if(scanf("%d", &a[n - 1 - i]) == 1){
                        read_array(a, n - 1);
                        return;
                }
        }
}

It compiles, but when running it trows a segmentation fault error. It confuses me since the function contemplates a base case 0 that should stop it.

Body:
Example:

int read_array_aux(int *i, int *n) {
  if (i == n) {
    return 0;
  }
  if (scanf("%d", i) != 1) {
    return -1;
  }
  return read_array_aux(i + 1, n);
}

int read_array_aux2(int *a, size_t i, size_t n) {
  if (i == n) {
    return 0;
  }
  if (scanf("%d", a + i) != 1) {
    return -1;
  }
  return read_array_aux2(a, i + 1, n);
}

int read_array(int *a, size_t n) {
  return read_array_aux(a, a + n);
  // return read_array_aux2(a, 0, n);
}


答:
Your calculation of the array index is wrong. This line:

```<code>            if(scanf("%d", &a[n - 1 - i]) == 1){
</code>```

assumes the initial value of n, but at the same time, you decrease n with every recursion step. That being said, it shouldn't crash but just repeatedly write the first element of a, because with i = n - 1, n - 1 - i is always zero.

The idiomatic way to write such a recursion would be to recurse on i:

```<code>void read_array(int *a, int n, int i)
{
    if (i < n)
    {
        if(scanf("%d", &a[i]) == 1)
        {
            read_array(a, n, i+1);
        }
    }
}
</code>```

and call it with the initial value for i, e.g. read_array(a, 10, 0) for reading a 10-element array.

In practice, recursion in C is to be avoided.*

* Functional languages can typically optimize recursion, C just uses the call stack with a lot of overhead.

In this example, the theoretical purpose of recursion for writing a pure function is somewhat defeated with a function returning void. If this is just about learning the principle, the functions actually should return something. You could for example create a functional "list builder":

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

// place the side effect in a separate function
int getValue(void)
{
    // could have `scanf()` here:
    return rand();
}

typedef struct List
{
    int a[10];
    size_t length;
} List;

// non-functional helper to get around limitations of C:
// (if it could initialize result directly with the new values, it would
// be functional)
List listAppend(List list, int val)
{
    List result = list;
    result.a[result.length++] = val;
    return result;
}

// recursive function without side effects:
List buildList(List list, int (*value)())
{
    if (list.length >= 10) return list;
    return buildList(listAppend(list, value()), value);
}

int main(void)
{
    List myList = buildList((List){0}, &getValue);

    for (size_t i = 0; i < myList.length; ++i)
    {
        printf("myList.a[%zu] is %d\n", i, myList.a[i]);
    }
}
</code>```

Title: Read an array recursively

Body:
Your calculation of the array index is wrong. This line:

            if(scanf("%d", &a[n - 1 - i]) == 1){

assumes the initial value of n, but at the same time, you decrease n with every recursion step. That being said, it shouldn't crash but just repeatedly write the first element of a, because with i = n - 1, n - 1 - i is always zero.

The idiomatic way to write such a recursion would be to recurse on i:

void read_array(int *a, int n, int i)
{
    if (i < n)
    {
        if(scanf("%d", &a[i]) == 1)
        {
            read_array(a, n, i+1);
        }
    }
}

and call it with the initial value for i, e.g. read_array(a, 10, 0) for reading a 10-element array.

In practice, recursion in C is to be avoided.*

* Functional languages can typically optimize recursion, C just uses the call stack with a lot of overhead.

In this example, the theoretical purpose of recursion for writing a pure function is somewhat defeated with a function returning void. If this is just about learning the principle, the functions actually should return something. You could for example create a functional "list builder":

#include <stdio.h>
#include <stdlib.h>

// place the side effect in a separate function
int getValue(void)
{
    // could have `scanf()` here:
    return rand();
}

typedef struct List
{
    int a[10];
    size_t length;
} List;

// non-functional helper to get around limitations of C:
// (if it could initialize result directly with the new values, it would
// be functional)
List listAppend(List list, int val)
{
    List result = list;
    result.a[result.length++] = val;
    return result;
}

// recursive function without side effects:
List buildList(List list, int (*value)())
{
    if (list.length >= 10) return list;
    return buildList(listAppend(list, value()), value);
}

int main(void)
{
    List myList = buildList((List){0}, &getValue);

    for (size_t i = 0; i < myList.length; ++i)
    {
        printf("myList.a[%zu] is %d\n", i, myList.a[i]);
    }
}


问:
Is Time.zone.now.to_date equivalent to Date.today?
Is Time.zone.now.to_date equivalent to Date.today?

Another way to put it: will Time.zone.now.to_date == Date.today always be true?

If not, what's the best way to get a Date object corresponding to "now" in the application time zone?

答:
```<code># system timezone
Time.now.to_date == Date.today

# application timezone
Time.zone.now.to_date == Time.current.to_date == Time.zone.today == Date.current
</code>```

http://edgeapi.rubyonrails.org/classes/Time.html#method-c-current
http://edgeapi.rubyonrails.org/classes/Date.html#method-c-current

Body:
# system timezone
Time.now.to_date == Date.today

# application timezone
Time.zone.now.to_date == Time.current.to_date == Time.zone.today == Date.current

http://edgeapi.rubyonrails.org/classes/Time.html#method-c-current
http://edgeapi.rubyonrails.org/classes/Date.html#method-c-current


问:
How do you create hybrid Xcode projects for Mac & iPhone?
I'm working on a project which shall contain two targets. One for building a Framework to use in Mac development and another to create a static library to use in iPhone development.

In the common code it's no problem to #ifdef between the platforms, but I just can't get the targets and dependencies right.

The first question is, which base SDK to use?
For example if I use Mac 10.5 i can't include the UIKit framework (it is marked red and doesn't show the header files if i expand it). Even if the target that actually links against it builds for iPhone OS..

The other question is, how about the Foundation.framework, or stuff like Security.framework?  How to deal with them, as I can only include one of the versions (Mac or iPhone SDK)...

Anyone has an advice for me?
I'd like to have a clean project structure and definitely the same codebase for both targets... Are configurations the way to go?

Thanks!

答:
Probably the easiest (in terms of what you have to do) way of doing it is two projects (which you can wrap up as sub-projects of a dummy umbrella project if you like) which use the same sets of sources—one targeting Mac OS X, the other iPhone OS.

Alternatively, can you not create two separate targets within the same project, and alter the “Base SDK” from the “Build” tab of the “Get Info” window for each? I don't have Xcode in front of me to check, but I think it'll let you do this.

(Of course, with either approach, you can add a third target: a static library for the simulator, which will be useful when testing!)

OwnerDisplayName: stigi

LastEditorDisplayName: stigi

OwnerDisplayName: Mo


问:
How to get CruiseControl.NET working with Mercurial: "Source control failure (GetModifications)"
I'm trying to set up CruiseControl.NET 1.5.7256.1 for automatic builds. My project is stored in Mercurial, and I'm using the following ccnet.config:

```<code><cruisecontrol xmlns:cb="urn:ccnet.config.builder">
    <project name="Slider" webURL="http://localhost/ccnet">
        <triggers>
            <intervalTrigger seconds="3600" />
        </triggers>
        <sourcecontrol type="hg" autoGetSource="true">
            <executable>C:\Python26\Scripts\hg.bat</executable>
            <repo>c:\repos\slider</repo>
            <workingDirectory>c:\ccnet\slider</workingDirectory>
        </sourcecontrol>
        <tasks>
            <msbuild>
                <executable>C:\Windows\Microsoft.NET\Framework64\v4.0.30319\msbuild.exe</executable>
                <workingDirectory>c:\ccnet\slider</workingDirectory>
                <projectFile>Slider.sln</projectFile>
                <buildArgs>/noconsolelogger /p:Configuration=Debug /v:diag</buildArgs>
                <targets>Slider</targets>
                <timeout>900</timeout>
                <logger>C:\Program Files (x86)\CruiseControl.NET\server\ThoughtWorks.CruiseControl.MsBuild.dll</logger>
            </msbuild>
        </tasks>
    </project>
</cruisecontrol>
</code>```

But when I force a build, I get this error:

```<code>[Slider:WARN] Source control failure (GetModifications): Source control operation failed: < was unexpected at this time.
. Process command: C:\Python26\Scripts\hg.bat log -r 0:123 --template <modification><node>{node|short}</node><author>{author|user}</author><date>{date|rfc822date}</date><desc>{desc|escape}</desc><rev>{rev}</rev><email>{author|email|obfuscate}</email><files>{files}</files></modification> --noninteractive
[Slider:INFO] Integration complete: Exception - 12/2/2010 1:19:08 PM
</code>```

The error is presumably caused by the unquoted angle brackets in the --template parameter, but how can I make CC.NET put quotes around that parameter?

===============

Here's hg.bat:

```<code>@echo off
rem Windows Driver script for Mercurial

setlocal
set HG=%~f0

rem Use a full path to Python (relative to this script) as the standard Python
rem install does not put python.exe on the PATH...
rem %~dp0 is the directory of this script

%~dp0..\python "%~dp0hg" %*
endlocal
</code>```

答:
I'm successfully using CruiseControl.NET 1.5.7256.1 with Mercurial installed from this msi, using full path of hg.exe as the executable value.

In project\core\sourcecontrol\Mercurial\Mercurial.cs the template is used like this:

```<code>buffer.AddArgument("--template", HistoryTemplate)
</code>```

and will be formatted for the command line like this:

```<code>string.Format("{0}{1}{2}", arg, separator, StringUtil.AutoDoubleQuoteString(value))
</code>```

where the separator is " ", and AutoDoubleQuoteString will quote the template, so this can't be the cause of the error.

UPDATE 1

Actually, AutoDoubleQuoteString should quote the template, but in the current version doesn't do it. Also, even if the build succeeds when using hg.exe, running the actual command line in a command prompt returns the same error.

UPDATE 2

CruiseControl.NET 1.6.7981.1 was just released (see release notes), and since the template is now passed as a file, it works just fine (at least on my PC).

Body:
I'm trying to set up CruiseControl.NET 1.5.7256.1 for automatic builds. My project is stored in Mercurial, and I'm using the following ccnet.config:

<cruisecontrol xmlns:cb="urn:ccnet.config.builder">
    <project name="Slider" webURL="http://localhost/ccnet">
        <triggers>
            <intervalTrigger seconds="3600" />
        </triggers>
        <sourcecontrol type="hg" autoGetSource="true">
            <executable>C:\Python26\Scripts\hg.bat</executable>
            <repo>c:\repos\slider</repo>
            <workingDirectory>c:\ccnet\slider</workingDirectory>
        </sourcecontrol>
        <tasks>
            <msbuild>
                <executable>C:\Windows\Microsoft.NET\Framework64\v4.0.30319\msbuild.exe</executable>
                <workingDirectory>c:\ccnet\slider</workingDirectory>
                <projectFile>Slider.sln</projectFile>
                <buildArgs>/noconsolelogger /p:Configuration=Debug /v:diag</buildArgs>
                <targets>Slider</targets>
                <timeout>900</timeout>
                <logger>C:\Program Files (x86)\CruiseControl.NET\server\ThoughtWorks.CruiseControl.MsBuild.dll</logger>
            </msbuild>
        </tasks>
    </project>
</cruisecontrol>

But when I force a build, I get this error:

[Slider:WARN] Source control failure (GetModifications): Source control operation failed: < was unexpected at this time.
. Process command: C:\Python26\Scripts\hg.bat log -r 0:123 --template <modification><node>{node|short}</node><author>{author|user}</author><date>{date|rfc822date}</date><desc>{desc|escape}</desc><rev>{rev}</rev><email>{author|email|obfuscate}</email><files>{files}</files></modification> --noninteractive
[Slider:INFO] Integration complete: Exception - 12/2/2010 1:19:08 PM

The error is presumably caused by the unquoted angle brackets in the --template parameter, but how can I make CC.NET put quotes around that parameter?

===============

Here's hg.bat:

@echo off
rem Windows Driver script for Mercurial

setlocal
set HG=%~f0

rem Use a full path to Python (relative to this script) as the standard Python
rem install does not put python.exe on the PATH...
rem %~dp0 is the directory of this script

%~dp0..\python "%~dp0hg" %*
endlocal

Body:
I'm successfully using CruiseControl.NET 1.5.7256.1 with Mercurial installed from this msi, using full path of hg.exe as the executable value.

In project\core\sourcecontrol\Mercurial\Mercurial.cs the template is used like this:

buffer.AddArgument("--template", HistoryTemplate)

and will be formatted for the command line like this:

string.Format("{0}{1}{2}", arg, separator, StringUtil.AutoDoubleQuoteString(value))

where the separator is " ", and AutoDoubleQuoteString will quote the template, so this can't be the cause of the error.

UPDATE 1

Actually, AutoDoubleQuoteString should quote the template, but in the current version doesn't do it. Also, even if the build succeeds when using hg.exe, running the actual command line in a command prompt returns the same error.

UPDATE 2

CruiseControl.NET 1.6.7981.1 was just released (see release notes), and since the template is now passed as a file, it works just fine (at least on my PC).


问:
How to check if all subnodes of TreeNode are expanded?
Is there any easy way to check expand the state of TreeNode and its children? </p>

```<code>bool IsAllNodesExpanded(TreeNode nodeToCheck)
{
  // Use nodeToCheck.isExpanded
  // Use something to check all childrens
  // return something
}
</code>```

答:
As your question is specific to a particular WinForm component, but the solution I'm going to write you is more general. Therefore I'll explain my solution to you considering a general tree, but the code I'll provide you solves your own problem.

What you want to do is basically a tree traversal, which is the process of traversing all the children of a tree given it's root. Basically we need to check whether all the descendants (not the children) of a node. The difference between children and descendant is that children share the same parent (for instance A B C are children of X if and only if A B and C are directly connected to X), whereas descendants might be "children of children of children...of children (example: A is a descendant of X if, starting from X, there is a path on the tree that, starting from the node X, goes down to the node A).

In order to visit all the descendants of a tree we need a recursive function. In our case the function returns a boolean that tells us whether all the descendants of a particular starting node are expanded.
There is a sample code that does exactly what you've asked for:

```<code>bool areAllNodesExpanded(TreeNode nodeToCheck){

    if(!nodeToCheck.IsExpanded)
        return false;
    foreach(TreeNode n in nodeToCheck.Nodes){
        if (n.Nodes.Count == 0)
            continue;
        if(!areAllNodesExpanded(n))
            return false;
    }
    return true;
}
</code>```

Hope this helps.

LuxGiammi

EDIT: the code snippet above could not be compiled because of two errors I made:
1. it's IsExpanded and not isExpanded
2. For some reasons I do not want to investigate further, var n is of type object whereas it should be of type TreeNode.
Mistake corrected

Body:
Is there any easy way to check expand the state of TreeNode and its children?

bool IsAllNodesExpanded(TreeNode nodeToCheck)
{
  // Use nodeToCheck.isExpanded
  // Use something to check all childrens
  // return something
}

Body:
As your question is specific to a particular WinForm component, but the solution I'm going to write you is more general. Therefore I'll explain my solution to you considering a general tree, but the code I'll provide you solves your own problem.

What you want to do is basically a tree traversal, which is the process of traversing all the children of a tree given it's root. Basically we need to check whether all the descendants (not the children) of a node. The difference between children and descendant is that children share the same parent (for instance A B C are children of X if and only if A B and C are directly connected to X), whereas descendants might be "children of children of children...of children (example: A is a descendant of X if, starting from X, there is a path on the tree that, starting from the node X, goes down to the node A).

In order to visit all the descendants of a tree we need a recursive function. In our case the function returns a boolean that tells us whether all the descendants of a particular starting node are expanded.
There is a sample code that does exactly what you've asked for:

bool areAllNodesExpanded(TreeNode nodeToCheck){

    if(!nodeToCheck.IsExpanded)
        return false;
    foreach(TreeNode n in nodeToCheck.Nodes){
        if (n.Nodes.Count == 0)
            continue;
        if(!areAllNodesExpanded(n))
            return false;
    }
    return true;
}

Hope this helps.

LuxGiammi

EDIT: the code snippet above could not be compiled because of two errors I made:
1. it's IsExpanded and not isExpanded
2. For some reasons I do not want to investigate further, var n is of type object whereas it should be of type TreeNode.
Mistake corrected


问:
Legit way to store a destructor information to a void*
Is it legit to store the delete information of a void pointer in a function pointer like this?

```<code>typedef void(*deleter)(void*);
template <class T> void deleteVoidPointer(void* target)
{
    delete static_cast<T*>(target);
}

int main()
{
    void* p = new int;
    deleter del = deleteVoidPointer<int>;

    del(p);
    return 0;
}
</code>```

Are there any side effects I am missing here or is this a legit way to keep track of destructor information for a pointer? (Besides the missing check if target is a nullptr in deleteVoidPointer)

答:
Yes, the code you've shown is perfectly valid.

And there's no missing check: calling delete on a null pointer is guaranteed to do nothing.

Body:
Is it legit to store the delete information of a void pointer in a function pointer like this?

typedef void(*deleter)(void*);
template <class T> void deleteVoidPointer(void* target)
{
    delete static_cast<T*>(target);
}

int main()
{
    void* p = new int;
    deleter del = deleteVoidPointer<int>;

    del(p);
    return 0;
}

Are there any side effects I am missing here or is this a legit way to keep track of destructor information for a pointer? (Besides the missing check if target is a nullptr in deleteVoidPointer)


问:
Public member 'Count' on type 'OrderedEnumerable(Of Panel,Integer)' not found
I used a linq example from the link below.
Going through controls in order

This was exactly what I was looking for. It worked for me. Thank you Tim Schmelter

I added a timer control and some codes. My problem starts now. After that, while running it shows an error.
Even if I remove the code areas using the count property, It won't work.

Public member 'Count' on type 'OrderedEnumerable(Of Panel,Integer)' not found.

I have imported ...
Imports System.Linq

Can Anyone help me. I am new to vb.net

```<code>    Private Sub InitialisePanels() '(pnl As Control)
    Dim allPanels = From pnl In Me.Controls.OfType(Of Panel)()
               Order By pnl.TabIndex

    'Dim blnControlPresent As Boolean
    For Each pnl As Panel In allPanels
        If pnl.[GetType]().Name = "Panel" Then
            pnl.BringToFront()
            pnl.Visible = True
            pnl.Dock = DockStyle.Fill
            pnl.Visible = False
            pnl.SendToBack()
        End If
    Next
    If allPanels.Count > 0 Then
        allPanels(mFirstPanel).BringToFront()
        allPanels(mFirstPanel).Visible = True
        mCurrentPanel = mFirstPanel
    End If
End Sub
</code>```

答:
I must admit that i'm not sure what the problem is(apart from the fact that allPanels(mFirstPanel) doesn't compile because an OrderedEnumerable has no indexer), but this should work, presuming you want to bring the first panel to front:

```<code>Private Sub InitialisePanels() '(pnl As Control)
    Dim allPanels = From pnl In Me.Controls.OfType(Of Panel)()
                    Order By pnl.TabIndex
    For Each pnl As Panel In allPanels
        pnl.BringToFront()
        pnl.Visible = True
        pnl.Dock = DockStyle.Fill
        pnl.Visible = False
        pnl.SendToBack()
    Next

    Dim firstPanel As Panel = allPanels.FirstOrDefault()

    If firstPanel IsNot Nothing Then
        firstPanel.BringToFront()
        firstPanel.Visible = True
        mCurrentPanel = firstPanel
    End If
End Sub
</code>```

Body:
I used a linq example from the link below.
Going through controls in order

This was exactly what I was looking for. It worked for me. Thank you Tim Schmelter

I added a timer control and some codes. My problem starts now. After that, while running it shows an error.
Even if I remove the code areas using the count property, It won't work.

Public member 'Count' on type 'OrderedEnumerable(Of Panel,Integer)' not found.

I have imported ...
Imports System.Linq

Can Anyone help me. I am new to vb.net

    Private Sub InitialisePanels() '(pnl As Control)
    Dim allPanels = From pnl In Me.Controls.OfType(Of Panel)()
               Order By pnl.TabIndex

    'Dim blnControlPresent As Boolean
    For Each pnl As Panel In allPanels
        If pnl.[GetType]().Name = "Panel" Then
            pnl.BringToFront()
            pnl.Visible = True
            pnl.Dock = DockStyle.Fill
            pnl.Visible = False
            pnl.SendToBack()
        End If
    Next
    If allPanels.Count > 0 Then
        allPanels(mFirstPanel).BringToFront()
        allPanels(mFirstPanel).Visible = True
        mCurrentPanel = mFirstPanel
    End If
End Sub

Body:
I must admit that i'm not sure what the problem is(apart from the fact that allPanels(mFirstPanel) doesn't compile because an OrderedEnumerable has no indexer), but this should work, presuming you want to bring the first panel to front:

Private Sub InitialisePanels() '(pnl As Control)
    Dim allPanels = From pnl In Me.Controls.OfType(Of Panel)()
                    Order By pnl.TabIndex
    For Each pnl As Panel In allPanels
        pnl.BringToFront()
        pnl.Visible = True
        pnl.Dock = DockStyle.Fill
        pnl.Visible = False
        pnl.SendToBack()
    Next

    Dim firstPanel As Panel = allPanels.FirstOrDefault()

    If firstPanel IsNot Nothing Then
        firstPanel.BringToFront()
        firstPanel.Visible = True
        mCurrentPanel = firstPanel
    End If
End Sub


问:
Maven: Invalid content was found starting with element "reportSets"
This is the javadoc plugin in pom.xml:

```<code><plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-javadoc-plugin</artifactId>
    <version>2.10.4</version>
    <reportSets>
        <reportSet>
            <id>PDF</id>
            <reports>
                <report>javadoc</report>
            </reports>
            <configuration>
                <name>PDF</name>
                <description>MovieList documentation</description>
                <destDir>pdf</destDir>
                <doclet>com.tarsec.javadoc.pdfdoclet.PDFDoclet</doclet>
                <docletPath>lib\pdfdoclet-1.0.3-all.jar</docletPath>
                <useStandardDocletOptions>false</useStandardDocletOptions>
                <additionalparam>
                    -pdf javadoc.pdf
                </additionalparam>
            </configuration>
        </reportSet>
    </reportSets>
</plugin>
</code>```

And it has an error on <reportSets>.

It says Invalid content was found starting with element 'reportSets'.

I'm trying to use this with the PDFDoclet jar but I can't manage to get it working. What am I doing wrong?

答:
Maybe use their example from their website.

```<code><ant:javadoc doclet="com.tarsec.javadoc.pdfdoclet.PDFDoclet"
        docletpath="./jar/pdfdoclet-1.0.0-all.jar"
        packagenames="com.jlaby.*"
        overview="./example/laby/overview_laby.html"
        additionalparam="-pdf ./example/results/laby.pdf -config ./example/laby/config_laby.properties"
        private="no"
        sourcepath="./example/laby" >
</ant:javadoc>
</code>```

See http://pdfdoclet.sourceforge.net/running.html

Body:
This is the javadoc plugin in pom.xml:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-javadoc-plugin</artifactId>
    <version>2.10.4</version>
    <reportSets>
        <reportSet>
            <id>PDF</id>
            <reports>
                <report>javadoc</report>
            </reports>
            <configuration>
                <name>PDF</name>
                <description>MovieList documentation</description>
                <destDir>pdf</destDir>
                <doclet>com.tarsec.javadoc.pdfdoclet.PDFDoclet</doclet>
                <docletPath>lib\pdfdoclet-1.0.3-all.jar</docletPath>
                <useStandardDocletOptions>false</useStandardDocletOptions>
                <additionalparam>
                    -pdf javadoc.pdf
                </additionalparam>
            </configuration>
        </reportSet>
    </reportSets>
</plugin>

And it has an error on <reportSets>.

It says Invalid content was found starting with element 'reportSets'.

I'm trying to use this with the PDFDoclet jar but I can't manage to get it working. What am I doing wrong?

Body:
Maybe use their example from their website.

<ant:javadoc doclet="com.tarsec.javadoc.pdfdoclet.PDFDoclet"
        docletpath="./jar/pdfdoclet-1.0.0-all.jar"
        packagenames="com.jlaby.*"
        overview="./example/laby/overview_laby.html"
        additionalparam="-pdf ./example/results/laby.pdf -config ./example/laby/config_laby.properties"
        private="no"
        sourcepath="./example/laby" >
</ant:javadoc>

See http://pdfdoclet.sourceforge.net/running.html


问:
In Java, why have a code block with no keywords, just curly brackets
I'm re-factoring some inherited code, but was stumped by the design decision and can't figure out the proper terms to google this. My predecessor would use blocks like this one:

```<code>public class ChildClass extends ParentClass {
    {
        inheritedVar = "someVal";
    }

    public ChildClass(){ /* constructor exists */ }
    // rest of code
}
</code>```

What is the point of declaring a block of code with no keyword? It doesn't behave like a static block, I don't believe. Is it an alternative to setting in the constructor? Would this have some effect if a factory was being used (which in this case it's not)? I found a related thread here on this happening in C but the reasoning (scope & variable declaration) didn't seem relevant to Java.

Any thoughts or ideas on the "why" of this would be appreciated. It's easy enough to re-factor this, I'm just curious at this point.

答:
It is an initializer block.  (Related to static initializer block)  See Initializing Instance Members on this page:

http://download.oracle.com/javase/tutorial/java/javaOO/initial.html

It is an alternative to a constructor.  You could use it when providing multiple, overloaded constructors as a way to share code.

Personally, however, I find it much clearer to have the constructor call a named initializer method rather than rely on the anonymous code block.  Although, the compiler does copy the initializer block to all constructors behind the scenes and you could argue that there is a performance increase similar to inline'ing a method declaration.

Body:
I'm re-factoring some inherited code, but was stumped by the design decision and can't figure out the proper terms to google this. My predecessor would use blocks like this one:

public class ChildClass extends ParentClass {
    {
        inheritedVar = "someVal";
    }

    public ChildClass(){ /* constructor exists */ }
    // rest of code
}

What is the point of declaring a block of code with no keyword? It doesn't behave like a static block, I don't believe. Is it an alternative to setting in the constructor? Would this have some effect if a factory was being used (which in this case it's not)? I found a related thread here on this happening in C but the reasoning (scope & variable declaration) didn't seem relevant to Java.

Any thoughts or ideas on the "why" of this would be appreciated. It's easy enough to re-factor this, I'm just curious at this point.


问:
Sqoop import error: Access denied for user 'root'@'localhost' , even if rights are OK
I found a lot of people with the similar error but no tips are working for my problem.

My command line:

```<code>sqoop import --connect jdbc:mysql://localhost/databaseY --username=root -P --table tableX --target-dir /user/ec2-user/databaseY/tableX --as-textfile --fields-terminated-by "\t"
</code>```

The error

```<code>16/08/19 11:25:51 INFO mapreduce.Job: Job job_1471608424445_0028 running in uber mode : false
16/08/19 11:25:51 INFO mapreduce.Job:  map 0% reduce 0%
16/08/19 11:25:58 INFO mapreduce.Job:  map 25% reduce 0%
16/08/19 11:26:04 INFO mapreduce.Job:  map 50% reduce 0%
16/08/19 11:26:06 INFO mapreduce.Job: Task Id :     attempt_1471608424445_0028_m_000000_0, Status : FAILED
Error: java.lang.RuntimeException: java.lang.RuntimeException: java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)
</code>```

How it is possible that the map start and stop after due to this error?

It looks like I have all the right needed as this two command line are working:

```<code>sqoop list-databases --connect jdbc:mysql://localhost --username root -P
</code>```

And

On mysql with root account I can do

```<code>select * from databaseY.tableX
</code>```

---EDIT---

This command line is working:

```<code>sqoop import --connect jdbc:mysql://localhost/databaseY --username root --password PASSWORD --query "select * from databaseY.tableX where number = 1474 AND \$CONDITIONS" --target-dir /tmp/ok --as-textfile --direct --split-by number
</code>```

but this one no:

```<code>sqoop import --connect jdbc:mysql://localhost/databaseY --username root --password PASSWORD --query "select * from databaseY.tableX where 1 = 1 AND \$CONDITIONS" --target-dir /tmp/ok --as-textfile --direct --split-by number
</code>```

Then, I realized that if I use -m 1 my sqoop import is working. Only with -m 1

Does it mean I have a bad cluster configuration? Why my job is working only with one map task?

----- SOLUTION -----

It was simply a problem of the IP address. I changed localhost by the IP address and it is working fine now.

答: The username and password here specifies the user and password for the database you are trying connect. The username and password here is not for mysql login user. So use the username and password for the user specified for the database you are trying to connect. </p>

Body:
I found a lot of people with the similar error but no tips are working for my problem.

My command line:

sqoop import --connect jdbc:mysql://localhost/databaseY --username=root -P --table tableX --target-dir /user/ec2-user/databaseY/tableX --as-textfile --fields-terminated-by "\t"

The error

16/08/19 11:25:51 INFO mapreduce.Job: Job job_1471608424445_0028 running in uber mode : false
16/08/19 11:25:51 INFO mapreduce.Job:  map 0% reduce 0%
16/08/19 11:25:58 INFO mapreduce.Job:  map 25% reduce 0%
16/08/19 11:26:04 INFO mapreduce.Job:  map 50% reduce 0%
16/08/19 11:26:06 INFO mapreduce.Job: Task Id :     attempt_1471608424445_0028_m_000000_0, Status : FAILED
Error: java.lang.RuntimeException: java.lang.RuntimeException: java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)

How it is possible that the map start and stop after due to this error?

It looks like I have all the right needed as this two command line are working:

sqoop list-databases --connect jdbc:mysql://localhost --username root -P

And

On mysql with root account I can do

select * from databaseY.tableX

---EDIT---

This command line is working:

sqoop import --connect jdbc:mysql://localhost/databaseY --username root --password PASSWORD --query "select * from databaseY.tableX where number = 1474 AND \$CONDITIONS" --target-dir /tmp/ok --as-textfile --direct --split-by number

but this one no:

sqoop import --connect jdbc:mysql://localhost/databaseY --username root --password PASSWORD --query "select * from databaseY.tableX where 1 = 1 AND \$CONDITIONS" --target-dir /tmp/ok --as-textfile --direct --split-by number

Then, I realized that if I use -m 1 my sqoop import is working. Only with -m 1

Does it mean I have a bad cluster configuration? Why my job is working only with one map task?

----- SOLUTION -----

It was simply a problem of the IP address. I changed localhost by the IP address and it is working fine now.


问:
Invalid entitlements error when adding push notifications
I'm trying to add push notifications to my chat app following this tutorial: https://www.appcoda.com/firebase-push-notifications/

I've toggled Push Notifications to On in "Capabilities":

My provisioning profile is set up for push notifications:

I downloaded it, and double clicked it to install.

For Code Signing, in Target -> Code Signing:

And Project -> Code Signing:

Entitlements file:

When I ran the project it succeeded, then said "The executable was signed with invalid entitlements". Full error The entitlements specified in your application’s Code Signing Entitlements file are invalid, not permitted, or do not match those specified in your provisioning profile. (0xE8008016).

Thanks for reading.. Any help on this will be hugely appreciated!

EDIT: Additional Information

Using Xcode 8.2.1

In my App ID in the developers portal, Game Center, In-App Purchases, and Push Notifications are enabled. It's my understanding that Game Center and IAP are enabled by default.

I've tried turning GC and IAP On, and then Off again. Restart Xcode, clean, build. No luck

I've tried turning GC and IAP On, then regenerating my provisioning profiles, installing them, cleaning and building. No luck.

My Bundle ID matches everywhere.

答:
As your given information your app has enabled services for Game Centre, In-App Purchase and Notification.

and according to your entitlements settings that your app in Xcode doesn't have Game Centre as enabled.
Check you entitlements setting once and try again, after enabling Game Centre there shouldn't be any problem.