问:
mongoose aggregate : how to count matching documents and insert counting using Promises
When I perform the following aggregate

```<code>return this.aggregate([
  {
    $lookup: {
      from: 'groups',
      localField: '_group',
      foreignField: '_id',
      as: 'group'
    }
  },
  { $match: query },
  {
    $project: {
      group: {
        $let:{
          vars:{
            firstGroup:{
              $arrayElemAt:["$group",0]
            }
          },
          in:{
            name:"$$firstGroup.name",
            description:"$$firstGroup.description"
          }
        }
      },
      name: 1,
      description: 1,
      _id: 0
    }
  },
  { $sort: sortBy },
  { $limit: resultsPerPage },
  { $skip: skipDocuments }
])
</code>```

with  query = {}
no limit no skip
I get 8 matching roles grouped by group.name

```<code>ROLES: [
{"name":"NewRole","description":"NewRole description","group":{}},{"name":"Visitor","description":"no permissions","group":{}},
{"name":"NewRoleInGroup","description":"NewRoleInGroup description","group":{"name":"GroupA","description":"Description GroupA"}},
{"name":"admin","description":"can RW group, user","group":{"name":"GroupA","description":"Description GroupA"}},
{"name":"employee","description":"can R group, can read user","group":{"name":"GroupA","description":"Description GroupA"}},
{"name":"manager","description":"can R group, can RW user","group":{"name":"GroupA","description":"Description GroupA"}},
{"name":"employee","description":"can R group, can read user","group":{"name":"GroupB","description":"Description GroupB"}},
{"name":"manager","description":"can R group, can RW user","group":{"name":"GroupB","description":"Description GroupB"}},
{"name":"employee","description":"can R group, can read user","group":{"name":"GroupC","description":"Description GroupC"}}
]
</code>```

Now  I would like to insert the total matching documents as the first object in the result to get track of it (when a limit is specified in the aggregate, I should return the total number of docs)

```<code>ROLES: [
{"roleCount": 8},
{"name":"NewRole","description":"NewRole description","group":{}},{"name":"Visitor","description":"no permissions","group":{}},
{"name":"NewRoleInGroup","description":"NewRoleInGroup description","group":{"name":"GroupA","description":"Description GroupA"}},
{"name":"admin","description":"can RW group, user","group":{"name":"GroupA","description":"Description GroupA"}},
{"name":"employee","description":"can R group, can read user","group":{"name":"GroupA","description":"Description GroupA"}}
]
</code>```

Where should I write the count in the pipeline ( I guess after the $match ?)
 and how can I insert the count into the result ?  ( I guess after the  $sort ?)

Maybe there is no way to do it in one aggregate , and the only possibility is to perform first a collection count then the aggregate and insert the counter object before returning the result ( using Promise.all it can be done in parallel.. )

thanks for feedback

答:
One solution is actually to perform it in 2 steps , first counting , then aggregation with limit/skip. These 2 steps can be run in parallel as Promises with Promise.all, then returning both results ( count and data )

```<code>  list(query, pageNumber, resultsPerPage, skipDocuments, sortBy) {

    const counting = this.count()
      .then((count) => {
        return {"roles": count};
      })
      .catch((e) => { throw(e); });
    const aggregation = this.aggregate([
      { $lookup: { from: 'groups', localField: '_group', foreignField: '_id', as: 'group'} },
      { $match: query },
      { $project: { group: { $let:{ vars:{ firstGroup:{ $arrayElemAt:["$group",0] } },  in:{ name:"$$firstGroup.name", description:"$$firstGroup.description" } } }, name: 1, description: 1, _id: 0 } },
      { $sort: sortBy },
      { $skip: skipDocuments },   // SKIP ALWAYS BEFORE LIMIT !
      { $limit: resultsPerPage }
    ]).exec()
      .then((list) => {
        return list;
      })
      .catch((e) => {
        console.log('MongoDB Error: ', e);
        return new APIError('Cannot list roles!', httpStatus.UNPROCESSABLE_ENTITY);
      });

    return Promise.all([counting, aggregation])
      .then((values) => {
        console.log('VALUES: %j', values);
</code>```

return values;
          })
          .catch((e) => { throw(e); });
      },

so we get exactly whats is needed :

```<code>  VALUES: [
  {"roles":9},
  [{"name":"NewRole","description":"NewRole description","group":{}},{
  "name":"Visitor","description":"no permissions","group":{}},
  {"name":"NewRoleInGroup","description":"NewRoleInGroup description","group":{"name":"GroupA","description":"Description GroupA"}},
  {"name":"admin","description":"can RW group, user","group":{"name":"GroupA","description":"Description GroupA"}},
  {"name":"employee","description":"can R group, can read user","group":{"name":"GroupA","description":"Description GroupA"}},
  {"name":"manager","description":"can R group, can RW user","group":{"name":"GroupA","description":"Description GroupA"}},
  {"name":"employee","description":"can R group, can read user","group":{"name":"GroupB","description":"Description GroupB"}},
  {"name":"manager","description":"can R group, can RW user","group":{"name":"GroupB","description":"Description GroupB"}},
  {"name":"employee","description":"can R group, can read user","group":{"name":"GroupC","description":"Description GroupC"}
  }]]
</code>```

Body:
When I perform the following aggregate

return this.aggregate([
  {
    $lookup: {
      from: 'groups',
      localField: '_group',
      foreignField: '_id',
      as: 'group'
    }
  },
  { $match: query },
  {
    $project: {
      group: {
        $let:{
          vars:{
            firstGroup:{
              $arrayElemAt:["$group",0]
            }
          },
          in:{
            name:"$$firstGroup.name",
            description:"$$firstGroup.description"
          }
        }
      },
      name: 1,
      description: 1,
      _id: 0
    }
  },
  { $sort: sortBy },
  { $limit: resultsPerPage },
  { $skip: skipDocuments }
])

with  query = {}
no limit no skip
I get 8 matching roles grouped by group.name

ROLES: [
{"name":"NewRole","description":"NewRole description","group":{}},{"name":"Visitor","description":"no permissions","group":{}},
{"name":"NewRoleInGroup","description":"NewRoleInGroup description","group":{"name":"GroupA","description":"Description GroupA"}},
{"name":"admin","description":"can RW group, user","group":{"name":"GroupA","description":"Description GroupA"}},
{"name":"employee","description":"can R group, can read user","group":{"name":"GroupA","description":"Description GroupA"}},
{"name":"manager","description":"can R group, can RW user","group":{"name":"GroupA","description":"Description GroupA"}},
{"name":"employee","description":"can R group, can read user","group":{"name":"GroupB","description":"Description GroupB"}},
{"name":"manager","description":"can R group, can RW user","group":{"name":"GroupB","description":"Description GroupB"}},
{"name":"employee","description":"can R group, can read user","group":{"name":"GroupC","description":"Description GroupC"}}
]

Now  I would like to insert the total matching documents as the first object in the result to get track of it (when a limit is specified in the aggregate, I should return the total number of docs)

ROLES: [
{"roleCount": 8},
{"name":"NewRole","description":"NewRole description","group":{}},{"name":"Visitor","description":"no permissions","group":{}},
{"name":"NewRoleInGroup","description":"NewRoleInGroup description","group":{"name":"GroupA","description":"Description GroupA"}},
{"name":"admin","description":"can RW group, user","group":{"name":"GroupA","description":"Description GroupA"}},
{"name":"employee","description":"can R group, can read user","group":{"name":"GroupA","description":"Description GroupA"}}
]

Where should I write the count in the pipeline ( I guess after the $match ?)
 and how can I insert the count into the result ?  ( I guess after the  $sort ?)

Maybe there is no way to do it in one aggregate , and the only possibility is to perform first a collection count then the aggregate and insert the counter object before returning the result ( using Promise.all it can be done in parallel.. )

thanks for feedback

Body:
One solution is actually to perform it in 2 steps , first counting , then aggregation with limit/skip. These 2 steps can be run in parallel as Promises with Promise.all, then returning both results ( count and data )

  list(query, pageNumber, resultsPerPage, skipDocuments, sortBy) {

    const counting = this.count()
      .then((count) => {
        return {"roles": count};
      })
      .catch((e) => { throw(e); });
    const aggregation = this.aggregate([
      { $lookup: { from: 'groups', localField: '_group', foreignField: '_id', as: 'group'} },
      { $match: query },
      { $project: { group: { $let:{ vars:{ firstGroup:{ $arrayElemAt:["$group",0] } },  in:{ name:"$$firstGroup.name", description:"$$firstGroup.description" } } }, name: 1, description: 1, _id: 0 } },
      { $sort: sortBy },
      { $skip: skipDocuments },   // SKIP ALWAYS BEFORE LIMIT !
      { $limit: resultsPerPage }
    ]).exec()
      .then((list) => {
        return list;
      })
      .catch((e) => {
        console.log('MongoDB Error: ', e);
        return new APIError('Cannot list roles!', httpStatus.UNPROCESSABLE_ENTITY);
      });

    return Promise.all([counting, aggregation])
      .then((values) => {
        console.log('VALUES: %j', values);

return values;
          })
          .catch((e) => { throw(e); });
      },

so we get exactly whats is needed :

  VALUES: [
  {"roles":9},
  [{"name":"NewRole","description":"NewRole description","group":{}},{
  "name":"Visitor","description":"no permissions","group":{}},
  {"name":"NewRoleInGroup","description":"NewRoleInGroup description","group":{"name":"GroupA","description":"Description GroupA"}},
  {"name":"admin","description":"can RW group, user","group":{"name":"GroupA","description":"Description GroupA"}},
  {"name":"employee","description":"can R group, can read user","group":{"name":"GroupA","description":"Description GroupA"}},
  {"name":"manager","description":"can R group, can RW user","group":{"name":"GroupA","description":"Description GroupA"}},
  {"name":"employee","description":"can R group, can read user","group":{"name":"GroupB","description":"Description GroupB"}},
  {"name":"manager","description":"can R group, can RW user","group":{"name":"GroupB","description":"Description GroupB"}},
  {"name":"employee","description":"can R group, can read user","group":{"name":"GroupC","description":"Description GroupC"}
  }]]


来源: stackexchange

问:
Make child objects have their own type static container
Is it possible that each class object has its own static data store?

I mean, just to perform actions like:

```<code>class Program
{
    static void Main(string[] args)
    {
        var car1 = new Car();
        car1.Save(); ////saves in its own storage
        var own1 = new Owner();
        own1.Save(); //saves in its own storage as well
    }
}
</code>```

In code I tried, I get such error

'System.InvalidCastException`

at this place
var repo = (Repository<IEntity>) CurrentRepository;

Whats wrong and how could I make it?

Whole code is here:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            //var car1 = new Car();
            //car1.Save(); ////saves in its own storage
            //var own1 = new Owner();
            //own1.Save(); //saves in its own storage as well    var car1 = new Car();

        }
    }

    public interface IEntity
    {
        long Id { get; }
    }

    public class Owner : Entity
    {

        public string FirstName { get; set; }

        public string LastName { get; set; }

        public Car Car { get; set; }

        public Owner(string firstName, string lastName, Car car) : base(new Owner())
        {
            FirstName = firstName;
            LastName = lastName;
            Car = car;
        }

        public Owner() : base()
        {
        }

    }

    public class Car : Entity
    {
        public string Name { get; set; }
        public int Year { get; set; }

        public Car() : base()
        {

        }

        public Car(string name, int year)
        {
            Name = name;
            Year = year;
        }
    }

    public abstract class Entity : IEntity
    {
        public long Id { get; }

        public static object CurrentRepository { get; set; }

        public Entity(Entity ent)
        {
            Type entityType = ent.GetType();
            var instance = Activator.CreateInstance(typeof(Repository<>).MakeGenericType(entityType));

            CurrentRepository = instance;

        }

        public Entity()
        {
        }

        public void Save()
        {
            var repo = (Repository<IEntity>)CurrentRepository;
            repo.Save(this);
        }

        public void Delete()
        {
            var repo = (Repository<IEntity>)CurrentRepository;
            repo.Delete(this);
        }
    }

    public interface IRepository<T> where T : IEntity
    {
        void Save(T entity);
        void Delete(T entity);
        T Find(long id);
    }

    public class Repository<T> : IRepository<T> where T : class, IEntity
    {
        protected BaseStorage<T> CustomDataStorage;

        public Repository()
        {
            CustomDataStorage = new BaseStorage<T>();
        }

        public void Save(T entity)
        {
            CustomDataStorage.Add(entity);
        }

        public void Delete(T entity)
        {
            CustomDataStorage.Remove(entity);
        }

        public T Find(long id)
        {
            throw new NotImplementedException();
        }
    }
    public class BaseStorage<T> : IStorage<T>
    {
        List<T> data = new List<T>();

        public void Add(T entity)
        {
            data.Add(entity);
        }

        public void Remove(T entity)
        {
            throw new NotImplementedException();
        }
    }

    public interface IStorage<T>
    {
        void Add(T entity);
        void Remove(T entity);
    }

}
</code>```

答:
One option to consider would be to change Entity as below.

The ConcurrentDictionary is to ensure that you get one repository per type.

```<code>public abstract class Entity : IEntity
{
    public long Id { get; }

    public static ConcurrentDictionary<Type, dynamic> CurrentRepository = new ConcurrentDictionary<Type, dynamic>();

    public Entity(Entity ent)
    {
        GetRepository(ent);
    }

    private static dynamic GetRepository(Entity ent)
    {
        Type entityType = ent.GetType();

        return CurrentRepository.GetOrAdd(entityType, type =>
        {
            var instance = Activator.CreateInstance(typeof(Repository<>).MakeGenericType(entityType));
            return instance;
        });
    }

    public Entity()
    {
    }

    public void Save()
    {
        var repo = GetRepository(this);
        repo.Save((dynamic)this);
    }

    public void Delete()
    {
        var repo = GetRepository(this);
        repo.Delete((dynamic)this);
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Is it possible that each class object has its own static data store?

I mean, just to perform actions like:

class Program
{
    static void Main(string[] args)
    {
        var car1 = new Car();
        car1.Save(); ////saves in its own storage
        var own1 = new Owner();
        own1.Save(); //saves in its own storage as well
    }
}

In code I tried, I get such error

'System.InvalidCastException`

at this place
var repo = (Repository<IEntity>) CurrentRepository;

Whats wrong and how could I make it?

Whole code is here:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            //var car1 = new Car();
            //car1.Save(); ////saves in its own storage
            //var own1 = new Owner();
            //own1.Save(); //saves in its own storage as well    var car1 = new Car();

        }
    }

    public interface IEntity
    {
        long Id { get; }
    }

    public class Owner : Entity
    {

        public string FirstName { get; set; }

        public string LastName { get; set; }

        public Car Car { get; set; }

        public Owner(string firstName, string lastName, Car car) : base(new Owner())
        {
            FirstName = firstName;
            LastName = lastName;
            Car = car;
        }

        public Owner() : base()
        {
        }

    }

    public class Car : Entity
    {
        public string Name { get; set; }
        public int Year { get; set; }

        public Car() : base()
        {

        }

        public Car(string name, int year)
        {
            Name = name;
            Year = year;
        }
    }

    public abstract class Entity : IEntity
    {
        public long Id { get; }

        public static object CurrentRepository { get; set; }

        public Entity(Entity ent)
        {
            Type entityType = ent.GetType();
            var instance = Activator.CreateInstance(typeof(Repository<>).MakeGenericType(entityType));

            CurrentRepository = instance;

        }

        public Entity()
        {
        }

        public void Save()
        {
            var repo = (Repository<IEntity>)CurrentRepository;
            repo.Save(this);
        }

        public void Delete()
        {
            var repo = (Repository<IEntity>)CurrentRepository;
            repo.Delete(this);
        }
    }

    public interface IRepository<T> where T : IEntity
    {
        void Save(T entity);
        void Delete(T entity);
        T Find(long id);
    }

    public class Repository<T> : IRepository<T> where T : class, IEntity
    {
        protected BaseStorage<T> CustomDataStorage;

        public Repository()
        {
            CustomDataStorage = new BaseStorage<T>();
        }

        public void Save(T entity)
        {
            CustomDataStorage.Add(entity);
        }

        public void Delete(T entity)
        {
            CustomDataStorage.Remove(entity);
        }

        public T Find(long id)
        {
            throw new NotImplementedException();
        }
    }
    public class BaseStorage<T> : IStorage<T>
    {
        List<T> data = new List<T>();

        public void Add(T entity)
        {
            data.Add(entity);
        }

        public void Remove(T entity)
        {
            throw new NotImplementedException();
        }
    }

    public interface IStorage<T>
    {
        void Add(T entity);
        void Remove(T entity);
    }

}

Body:
One option to consider would be to change Entity as below.

The ConcurrentDictionary is to ensure that you get one repository per type.

public abstract class Entity : IEntity
{
    public long Id { get; }

    public static ConcurrentDictionary<Type, dynamic> CurrentRepository = new ConcurrentDictionary<Type, dynamic>();

    public Entity(Entity ent)
    {
        GetRepository(ent);
    }

    private static dynamic GetRepository(Entity ent)
    {
        Type entityType = ent.GetType();

        return CurrentRepository.GetOrAdd(entityType, type =>
        {
            var instance = Activator.CreateInstance(typeof(Repository<>).MakeGenericType(entityType));
            return instance;
        });
    }

    public Entity()
    {
    }

    public void Save()
    {
        var repo = GetRepository(this);
        repo.Save((dynamic)this);
    }

    public void Delete()
    {
        var repo = GetRepository(this);
        repo.Delete((dynamic)this);
    }
}


问:
how to show random two li in jquery?
Could you please tell me how to show random two li in jQuery ? I tried like this

$('#id_show12').click(function() {
    var random1 = Math.floor(Math.random() * 7);
    var random2 = Math.floor(Math.random() * 7);
    $('.show12 li').not(':eq(' + random1 + '), :eq(' + random2 + ')').hide();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="show12">
  <ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
    <li>6</li>
    <li>7</li>
  </ul>
</div>

<button id="id_show12">show only one two li</button></code>```

https://jsbin.com/dafurasaye/edit?html,js,output

答:
js code :</p>

```<code>$('#id_show12').click(function() {
 var random1= Math.floor(Math.random() * 7);
 var random2= Math.floor(Math.random() * 7);
 if(random1 == random2){
    if(random1 == 6){
        random1= 5;
  }
  if(random1 = 0){
     random1= 1;
  }
  else{
    random1=random1+1;
  }
}

$( "li" ).each(function( index ) {
        if(random1 != index & random2 != index){
            $( this ).hide();
      }
      else{
            $( this ).show();
      }
 });
})
</code>```

Title: how to show random two li in jquery?

Body:
Could you please tell me how to show random two li in jQuery ? I tried like this

$('#id_show12').click(function() {
    var random1 = Math.floor(Math.random() * 7);
    var random2 = Math.floor(Math.random() * 7);
    $('.show12 li').not(':eq(' + random1 + '), :eq(' + random2 + ')').hide();
});

1

2

3

4

5

6

7

<button id="id_show12">show only one two li</button>

https://jsbin.com/dafurasaye/edit?html,js,output

Body:
js code :

$('#id_show12').click(function() {
 var random1= Math.floor(Math.random() * 7);
 var random2= Math.floor(Math.random() * 7);
 if(random1 == random2){
    if(random1 == 6){
        random1= 5;
  }
  if(random1 = 0){
     random1= 1;
  }
  else{
    random1=random1+1;
  }
}

$( "li" ).each(function( index ) {
        if(random1 != index & random2 != index){
            $( this ).hide();
      }
      else{
            $( this ).show();
      }
 });
})


问:
TensorFlow RandomForest vs Deep learning
I am using TensorFlow for training model which has 1 output for the 4 inputs. The problem is of regression.

I found that when I use RandomForest to train the model, it quickly converges and also runs well on the test data. But when I use a simple Neural network for the same problem, the loss(Random square error) does not converge. It gets stuck on a particular value.

I tried increasing/decreasing number of hidden layers, increasing/decreasing learning rate. I also tried multiple optimizers and tried to train the model on both normalized and non-normalized data.

I am new to this field but the literature that I have read so far vehemently asserts that the neural network should marginally and categorically work better than the random forest.

What could be the reason behind non-convergence of the model in this case?

答:
If your model is not converging it means that the optimizer is stuck in a local minima in your loss function.

I don't know what optimizer you are using but try increasing the momentum or even the learning rate slightly.

Another strategy employed often is the learning rate decay, which reduces your learning rate by a factor every several epochs. This can also help you not get stuck in a local minima early in the training phase, while achieving maximum accuracy towards the end of training.

Otherwise you could try selecting an adaptive optimizer (adam, adagrad, adadelta, etc) that take care of the hyperparameter selection for you.

This is a very good post comparing different optimization techniques.

Deep Neural Networks need a significant number of data to perform adequately. Be sure you have lots of training data or your model will overfit.


问:
PHP include in JavaScript is not working
I've JavaScript and I want to run a include script in the JavaScript . I tried the following statement:

```<code>outputEl.innerHTML = '<?php include "./change/ud1.php";?>';
</code>```

When I run the script I get no response.

Does someone know why I didn't get any response and how I can fix it?

I tried to replace the PHP include with an html iframe. That worked but that is not the best solution for me.

答:
php is a server-side language.

JavaScript is client side language.

so php can only execute on your server and JavaScript executes on user's browser.

there is no way in which php code going to run in JavaScript (browser). so you need to use ajax like this.

```<code>var xhttp = new XMLHttpRequest();

xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        // server sent data successfully in this.responseText variable
        document.getElementById("output1").innerHTML = this.responseText;
    }
};

//Request data from a server
xhttp.open("GET", "path/to/php/include-script.php", true);
xhttp.send();
</code>```

Learn more about ajax here.

Body:
I've JavaScript and I want to run a include script in the JavaScript . I tried the following statement:

outputEl.innerHTML = '<?php include "./change/ud1.php";?>';

When I run the script I get no response.

Does someone know why I didn't get any response and how I can fix it?

I tried to replace the PHP include with an html iframe. That worked but that is not the best solution for me.

Body:
php is a server-side language.

JavaScript is client side language.

so php can only execute on your server and JavaScript executes on user's browser.

there is no way in which php code going to run in JavaScript (browser). so you need to use ajax like this.

var xhttp = new XMLHttpRequest();

xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        // server sent data successfully in this.responseText variable
        document.getElementById("output1").innerHTML = this.responseText;
    }
};

//Request data from a server
xhttp.open("GET", "path/to/php/include-script.php", true);
xhttp.send();

Learn more about ajax here.


问:
RED Robot Editor - Is there anyway to execute multiple testsuites parallelly?
I have 7 testsuites that are specific to languages something like German, Finish, Italy etc., I would like to execute all at one time. Kindly provide me solution on this. Referred to many materials, but having confusions that how we should work with RED Editor.</p>

答:
AFAIK the only possibility to add parallel execution to robot tests is to

parallelize code inside python classes or

make each test suite a
separate test call (i.e. with ctest execution) and call several of
them separately (ctest -j)

RIDE does not provide this, nor does robotframework natively.


问:
Create the configuration file at maven install and without or before feature install for Karaf
In my project, in the bundle module, at resource directory, I have my sample startup.cfg file. This file contains properties I want to use at the startup. In the bundle pom.xml I have the following.

```<code><build>
  <plugins>
    <plugin>
      <groupId>org.codehaus.mojo</groupId>
      <artifactId>build-helper-maven-plugin</artifactId>
      <executions>
        <execution>
          <id>attach-artifacts</id>
          <phase>package</phase>
          <goals>
            <goal>attach-artifact</goal>
          </goals>
          <configuration>
            <artifacts>
              <artifact>
                <file>${project.build.directory}/classes/startup.cfg</file>
                <type>cfg</type>
                <classifier>config</classifier>
              </artifact>
            </artifacts>
          </configuration>
        </execution>
      </executions>
    </plugin>
  </plugins>
</build>
</code>```

And in my feature xml, I have,

```<code><feature name="my-sample-feature" description="Sample service" version='${project.version}'>
    <bundle>mvn:org.sample.app/service.implementation/{{VERSION}}</bundle>
    <configfile finalname="/etc/org.sample.app.startup.cfg">mvn:mvn:org.sample.app/service.implementation/{{VERSION}}/cfg/config</configfile>
</feature>
</code>```

In feature xml, I have added,

```<code><dependency>
  <groupId>${project.groupId}</groupId>
  <artifactId>service.implementation</artifactId>
  <version>${project.version}</version>
  <classifier>config</classifier>
  <type>cfg</type>
</dependency>
</code>```

This feature is a startup feature too. Now, when I install the feature in a karaf container or in this case when I spin up the karaf, only then the etc/org.sample.app.startup.cfg is created. My target is simple, to have this conf file always at etc/ independent of the feature is installed or not.

答:
The cfg file are deployed into etc folder when installing the feature . If you want it to be present independent of the feature is installed or not, this means that you have to deploy it manually to etc and this is more simple after attaching the cfg to your artifact as you did in your pom.

Remember that if you want to follow best pratices (especially in a production environnement), don't separate cfg deployment from it's origin feature.

Body:
In my project, in the bundle module, at resource directory, I have my sample startup.cfg file. This file contains properties I want to use at the startup. In the bundle pom.xml I have the following.

<build>
  <plugins>
    <plugin>
      <groupId>org.codehaus.mojo</groupId>
      <artifactId>build-helper-maven-plugin</artifactId>
      <executions>
        <execution>
          <id>attach-artifacts</id>
          <phase>package</phase>
          <goals>
            <goal>attach-artifact</goal>
          </goals>
          <configuration>
            <artifacts>
              <artifact>
                <file>${project.build.directory}/classes/startup.cfg</file>
                <type>cfg</type>
                <classifier>config</classifier>
              </artifact>
            </artifacts>
          </configuration>
        </execution>
      </executions>
    </plugin>
  </plugins>
</build>

And in my feature xml, I have,

<feature name="my-sample-feature" description="Sample service" version='${project.version}'>
    <bundle>mvn:org.sample.app/service.implementation/{{VERSION}}</bundle>
    <configfile finalname="/etc/org.sample.app.startup.cfg">mvn:mvn:org.sample.app/service.implementation/{{VERSION}}/cfg/config</configfile>
</feature>

In feature xml, I have added,

<dependency>
  <groupId>${project.groupId}</groupId>
  <artifactId>service.implementation</artifactId>
  <version>${project.version}</version>
  <classifier>config</classifier>
  <type>cfg</type>
</dependency>

This feature is a startup feature too. Now, when I install the feature in a karaf container or in this case when I spin up the karaf, only then the etc/org.sample.app.startup.cfg is created. My target is simple, to have this conf file always at etc/ independent of the feature is installed or not.


问:
Getting Cannot call method "getRange" of null error
```<code>var METADATA_SHEET_NAME = 'MetaData';

function readMetaData() {
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = spreadsheet.getSheetByName(METADATA_SHEET_NAME);
  var range = sheet.getRange(1, 2);
  var fixVersion = range.getValue();
  Logger.log(fixVersion);
  return fixVersion;
}
</code>```

In my current google script, I already have Sheet with Name MetaData. I am storing a sheet name in variable METADATA_SHEET_NAME. if I pass sheet name directly in getSheetByName() method, it works perfectly but when I am passing variable name(in which I have stored sheet name) it is giving

TypeError: Cannot call method "getRange" of null.

答:
Check for typos as it's working for me. It's okay to assign the sheet name to a variable.

Here I have a sheet named 'Sheet1' which I assigned to METADATA_SHEET_NAME variable. Now I'm going to fetch value from row 1 col 2 as per your code.

```<code>[17-07-06 05:17:16:829 PDT] Response1
</code>```

Body:
var METADATA_SHEET_NAME = 'MetaData';

function readMetaData() {
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = spreadsheet.getSheetByName(METADATA_SHEET_NAME);
  var range = sheet.getRange(1, 2);
  var fixVersion = range.getValue();
  Logger.log(fixVersion);
  return fixVersion;
}

In my current google script, I already have Sheet with Name MetaData. I am storing a sheet name in variable METADATA_SHEET_NAME. if I pass sheet name directly in getSheetByName() method, it works perfectly but when I am passing variable name(in which I have stored sheet name) it is giving

TypeError: Cannot call method "getRange" of null.

Body:
Check for typos as it's working for me. It's okay to assign the sheet name to a variable.

Here I have a sheet named 'Sheet1' which I assigned to METADATA_SHEET_NAME variable. Now I'm going to fetch value from row 1 col 2 as per your code.

[17-07-06 05:17:16:829 PDT] Response1


问:
Incrementing dates in Excel VBA
this is my current code:

```<code>For z = 3 To 52
    Cells(z, 1) = Cells((z - 1), 3) + 7
Next z
</code>```

Where cell z-1 is a date

I want to add 7 days to the previous cell however it's throwing an error, it this the right way to approach this issue or is there a simpler method?

Thank you

答:
Try the DateAdd function, use inside the loop:

```<code>Cells(Z, 1) = DateAdd("ww", 1, Cells((Z - 1), 3))
</code>```

Note: the 1st parameter, is the Interval, set it to "ww", which means weeks.

To read more about this function go to MSDN

Title: Incrementing dates in Excel VBA

Body:
this is my current code:

For z = 3 To 52
    Cells(z, 1) = Cells((z - 1), 3) + 7
Next z

Where cell z-1 is a date

I want to add 7 days to the previous cell however it's throwing an error, it this the right way to approach this issue or is there a simpler method?

Thank you

Body:
Try the DateAdd function, use inside the loop:

Cells(Z, 1) = DateAdd("ww", 1, Cells((Z - 1), 3))

Note: the 1st parameter, is the Interval, set it to "ww", which means weeks.

To read more about this function go to MSDN


问:
Android NDK : make: *** No rule to make target. Stop
I am trying to build libusb using the NDK. Here is my Android.mk and Application.mk I have checked this thread Android NDK: No rule to make target but it didn't work for me.

Android.mk

```<code>include $(CLEAR_VARS)
LOCAL_MODULE    := libusb
LOCAL_SRC_FILES := libusb/core.c libusb/descriptor.c libusb/io.c libusb/sync.c libusb/os/linux_usbfs.c

LOCAL_LDLIBS    := -llog
include $(BUILD_SHARED_LIBRARY)
</code>```

Application.mk

```<code>APP_ABI:= all
APP_LDFLAGS:= -llog
APP_STL:= stlport_shared
APP_CPP_FEATURES:= exceptions
APP_PLATFORM:= android-21
APP_CFLAGS:= -g
</code>```

build.gradle

```<code>apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.0"
    defaultConfig {
        applicationId "com.williams.libusbpoc"
        minSdkVersion 21
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    androidTestImplementation ('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    implementation"org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    implementation 'com.android.support:appcompat-v7:26.0.0-beta2'
    testImplementation 'junit:junit:4.12'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
}
</code>```

local.properties

```<code>ndk.dir=C\:\\android-ndk-r15
</code>```

Project structure looks like below:

When I am running ndk-build then I get

```<code>ndk-build
Android NDK: WARNING: APP_PLATFORM android-21 is higher than android:minSdkVersion 1 in D:/williams/android/libusbpoc/app/src/main/AndroidManifest.xml. NDK binaries will *not* be comptible with devices older than android-21. See https://android.googlesource.com/platform/ndk/+/master/docs/user/common_problems.md for more information.
make: *** No rule to make target `C:/android-ndk-r15/build//../sources/cxx-stl/stlport/libusb/core.c', needed by `D:/williams/android/libusbpoc/app/src/main/obj/local/arm64-v8a/objs/usb/libusb/core.o'.  Stop.
</code>```

Does anyone know what I am doing wrong ?

答:
Looks like you forgot to set LOCAL_PATH, i.e. in your Android.mk you should have:

```<code>LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
#  ..etc as before..
</code>```

Body:
I am trying to build libusb using the NDK. Here is my Android.mk and Application.mk I have checked this thread Android NDK: No rule to make target but it didn't work for me.

Android.mk

include $(CLEAR_VARS)
LOCAL_MODULE    := libusb
LOCAL_SRC_FILES := libusb/core.c libusb/descriptor.c libusb/io.c libusb/sync.c libusb/os/linux_usbfs.c

LOCAL_LDLIBS    := -llog
include $(BUILD_SHARED_LIBRARY)

Application.mk

APP_ABI:= all
APP_LDFLAGS:= -llog
APP_STL:= stlport_shared
APP_CPP_FEATURES:= exceptions
APP_PLATFORM:= android-21
APP_CFLAGS:= -g

build.gradle

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.0"
    defaultConfig {
        applicationId "com.williams.libusbpoc"
        minSdkVersion 21
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    androidTestImplementation ('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    implementation"org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    implementation 'com.android.support:appcompat-v7:26.0.0-beta2'
    testImplementation 'junit:junit:4.12'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
}

local.properties

ndk.dir=C\:\\android-ndk-r15

Project structure looks like below:

When I am running ndk-build then I get

ndk-build
Android NDK: WARNING: APP_PLATFORM android-21 is higher than android:minSdkVersion 1 in D:/williams/android/libusbpoc/app/src/main/AndroidManifest.xml. NDK binaries will *not* be comptible with devices older than android-21. See https://android.googlesource.com/platform/ndk/+/master/docs/user/common_problems.md for more information.
make: *** No rule to make target `C:/android-ndk-r15/build//../sources/cxx-stl/stlport/libusb/core.c', needed by `D:/williams/android/libusbpoc/app/src/main/obj/local/arm64-v8a/objs/usb/libusb/core.o'.  Stop.

Does anyone know what I am doing wrong ?

Body:
Looks like you forgot to set LOCAL_PATH, i.e. in your Android.mk you should have:

LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
#  ..etc as before..


问:
How come php in include executed first?
How come php in include is executed before html? Because user input is from html.  Shouldn't included script be at last? </p>

```<code><?php
include('login.php'); // Includes Login Script

if(isset($_SESSION['login_user'])){
header("location: profile.php");
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Login Form in PHP with Session</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="main">
<h1>PHP Login Session Example</h1>
<div id="login">
<h2>Login Form</h2>
<form action="" method="post">
<label>UserName :</label>
<input id="name" name="username" placeholder="username" type="text">
<label>Password :</label>
<input id="password" name="password" placeholder="**********" type="password">
<input name="submit" type="submit" value=" Login ">
<span><?php echo $error; ?></span>
</form>
</div>
</div>
</body>
</html>
</code>```

答:
"Because user input is from html"

I believe you confuse between the HTML your PHP script is going to output as a response , and between the HTML <form> that triggered the request.

the HTML in your question is not going to be PARSED by the PHP, instead it is going to be outputted as a response to client request that triggered this PHP script.

That confusion may be happened because your PHP script is outputting the HTML form, and also it process the request comes from that HTML form.

PHP is about the work of building the final HTML to output.

For example:

On the client side whether it is an HTML <form> running by a browser , or C# bot, or JAVA application , or whatever program is going to send the http request to your server(PHP script) , suppose you send this request with these parameters

```<code>Request URL: "http://www.example.com/index.php"
Request method: "POST"
Request parameters: "username=myname&password=123"
</code>```

that request is going to trigger the PHP to parse the index.php script on the server

On the Server side your web server is going to execute the index.php after filling out the request parameters so you can use them in your code.

before triggering index.php

```<code>$_POST['username'] = $_REQUEST['username'] = "myname";
$_POST['password'] = $_REQUEST['password'] = "123";
</code>```

now as you have the request parameters let's call index.php

```<code><?php
    include('login.php'); // Includes Login Script

    if(isset($_SESSION['login_user'])){
        //check if user is authentic then redirect him to the profile page.
        header("location: profile.php");
        //you should exit; your code here
        //see: https://stackoverflow.com/questions/2747791
    }
   /*now any string that is not between the php open and close tags <> is parsed as
    HTML that needs to be outputted*/
?>
<!-- for example this HTML is going to be outputted ,and the browser is going to show it
unless you used the location header -->
<!DOCTYPE html>
<html>
    <!-- your log in form here -->
</html>
</code>```

Title: How come php in include executed first?

Body:
How come php in include is executed before html? Because user input is from html.  Shouldn't included script be at last?

<?php
include('login.php'); // Includes Login Script

if(isset($_SESSION['login_user'])){
header("location: profile.php");
}
?>
<!DOCTYPE html>

<title>Login Form in PHP with Session</title>
<link href="style.css" rel="stylesheet" type="text/css">

PHP Login Session Example

Login Form

<form action="" method="post">
UserName :
<input id="name" name="username" placeholder="username" type="text">
Password :
<input id="password" name="password" placeholder="**********" type="password">
<input name="submit" type="submit" value=" Login ">
<?php echo $error; ?>
</form>

Body:
"Because user input is from html"

I believe you confuse between the HTML your PHP script is going to output as a response , and between the HTML <form> that triggered the request.

the HTML in your question is not going to be PARSED by the PHP, instead it is going to be outputted as a response to client request that triggered this PHP script.

That confusion may be happened because your PHP script is outputting the HTML form, and also it process the request comes from that HTML form.

PHP is about the work of building the final HTML to output.

For example:

On the client side whether it is an HTML <form> running by a browser , or C# bot, or JAVA application , or whatever program is going to send the http request to your server(PHP script) , suppose you send this request with these parameters

Request URL: "http://www.example.com/index.php"
Request method: "POST"
Request parameters: "username=myname&password=123"

that request is going to trigger the PHP to parse the index.php script on the server

On the Server side your web server is going to execute the index.php after filling out the request parameters so you can use them in your code.

before triggering index.php

$_POST['username'] = $_REQUEST['username'] = "myname";
$_POST['password'] = $_REQUEST['password'] = "123";

now as you have the request parameters let's call index.php

<?php
    include('login.php'); // Includes Login Script

    if(isset($_SESSION['login_user'])){
        //check if user is authentic then redirect him to the profile page.
        header("location: profile.php");
        //you should exit; your code here
        //see: https://stackoverflow.com/questions/2747791
    }
   /*now any string that is not between the php open and close tags <> is parsed as
    HTML that needs to be outputted*/
?>
<!-- for example this HTML is going to be outputted ,and the browser is going to show it
unless you used the location header -->
<!DOCTYPE html>
<html>
    <!-- your log in form here -->
</html>


问:
Magento 2 : Replace labels in invoice pdf
I am new in magento 2. I am facing problem in replacing labels in pdf invoice. I need to replace "Tax" label by "GST" label which is present at right hand bottom. I have wasted more than 6 hours on this but not getting any solution.

Please help me in this.

答:
Basically you will need to create tax rules and they will be displayed under tax as summary. You can also change the TAX label in your checkout but you can not easily customise the invoice. Also, you will also need to show CGST and SGST individually.

For that try creating tax rules.

Step 1: Fill the Tax Rule Information

On the Admin Panel, Stores > Taxes > Tax Rules.

In the upper-right corner, click on Add New Tax Rule.

Under the Tax Rule Information section, set Name for the new rule.

From the tax rate list, choose one of them to enable for the rule. However, for each the existing tax rate, you can edit it as the following:

Tap the Edit icon on the row.

Edit the tax rate information on the Tax Rate page, then click Save.

Click on Add New Tax Rate.

Complete the Tax Rate form.

Save to complete.

Step 2: Configure the Additional Settings

On the Tax Rule page, open Additional Settings section,

Choose the Customer Tax Class area to which the rule applies.

Tap the Edit icon to modify the form and then Save it.

If need to create a new tax class, click on Add New Tax Class to fill the necessary information and then Save it.

Choose the Product Tax Class to which the rule applies.

Tap the Edit icon to modify the form and then Save it.

If need to create a new tax class, click on Add New Tax Class to fill the necessary.

Set the Priority to determine this tax to be applied first when more than one tax are enabled

To calculate the tax according to the order subtotal, mark the Calculate off Subtotal Only checkbox.

Set the Sort Order to arrange them in the list of the tax rules.

I hope this helps. For more refer Magento User Guide


问:
Fast Method to Intersect two Integer Quadratic Beziers?
Given two Quadratic Beziers in 2D with integer coordinates, what is the best way to find their intersection point(s)? Also interesting is an early rejection if they do not intersect. If it makes it easier, they can both be assumed to be monotone in both x and y.
Only intersections that are representable by subdivision to integers of the input curves are valid. </p>

答: This document explains various methods for finding the intersection of curves.</p>

OwnerDisplayName: starmole

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: strager


问:
Rails: Factory Girl failing to sequence
Just getting started with factory girl, and I've come across a problem with sequencing: Specifically, it doesn't increment. I've tried changing the database type, updating from factory_girl 1.3.2 to 2.0.0.beta1 (And factory_girl_rails from 1.0 to 1.1.0.beta1), tried recreating the database, but same problem - the sequence won't increment and I get a validation error after the first time I insert a unique field.

Any assistance much appreciated. Code & trace stack below:

/spec/models/user.rb

```<code>require 'spec_helper'

describe User do   describe "test user factory is correct" do
    user = Factory(:user)

    it "should have an email ending in example.com" do
      #user.email.should match "test2@example.com"
    end

    it "should have a password of foobar" do
      user.password.should == 'foobar'
    end

    it "should have a password confirmation field of foobar" do
      user.password_confirmation.should == 'foobar'
    end
    end

end
</code>```

/spec/factories/user.rb

```<code>Factory.define :user do |f|
    f.sequence(:email) { |n| puts "Email ##{n}"; "factory_#{n}@example.com" }
    f.password 'foobar'
    f.password_confirmation { |p| p.password }
end
</code>```

Trace:

```<code>/Users/john/.rvm/gems/ruby-1.9.2-p0/gems/activerecord-3.0.3/lib/active_record/validations.rb:49:in `save!': Validation failed: Email has already been taken (ActiveRecord::RecordInvalid)
    from /Users/john/.rvm/gems/ruby-1.9.2-p0/gems/activerecord-3.0.3/lib/active_record/attribute_methods/dirty.rb:30:in `save!'
    from /Users/john/.rvm/gems/ruby-1.9.2-p0/gems/activerecord-3.0.3/lib/active_record/transactions.rb:242:in `block in save!'
    from /Users/john/.rvm/gems/ruby-1.9.2-p0/gems/activerecord-3.0.3/lib/active_record/transactions.rb:289:in `block in with_transaction_returning_status'
    from /Users/john/.rvm/gems/ruby-1.9.2-p0/gems/activerecord-3.0.3/lib/active_record/connection_adapters/abstract/database_statements.rb:139:in `transaction'
    from /Users/john/.rvm/gems/ruby-1.9.2-p0/gems/activerecord-3.0.3/lib/active_record/transactions.rb:204:in `transaction'
    from /Users/john/.rvm/gems/ruby-1.9.2-p0/gems/activerecord-3.0.3/lib/active_record/transactions.rb:287:in `with_transaction_returning_status'
    from /Users/john/.rvm/gems/ruby-1.9.2-p0/gems/activerecord-3.0.3/lib/active_record/transactions.rb:242:in `save!'
    from /Users/john/.rvm/gems/ruby-1.9.2-p0/gems/factory_girl-1.3.2/lib/factory_girl/proxy/create.rb:6:in `result'
    from /Users/john/.rvm/gems/ruby-1.9.2-p0/gems/factory_girl-1.3.2/lib/factory_girl/factory.rb:327:in `run'
    from /Users/john/.rvm/gems/ruby-1.9.2-p0/gems/factory_girl-1.3.2/lib/factory_girl/factory.rb:270:in `create'
    from /Users/john/.rvm/gems/ruby-1.9.2-p0/gems/factory_girl-1.3.2/lib/factory_girl/factory.rb:301:in `default_strategy'
    from /Users/john/.rvm/gems/ruby-1.9.2-p0/gems/factory_girl-1.3.2/lib/factory_girl.rb:20:in `Factory'
    from /Users/john/Websites/Rails/InDevelopment/fastermanager/spec/models/user_spec.rb:5:in `block (2 levels) in <top (required)>'
    from /Users/john/.rvm/gems/ruby-1.9.2-p0/gems/rspec-core-2.3.1/lib/rspec/core/example_group.rb:131:in `module_eval'
    from /Users/john/.rvm/gems/ruby-1.9.2-p0/gems/rspec-core-2.3.1/lib/rspec/core/example_group.rb:131:in `subclass'
    from /Users/john/.rvm/gems/ruby-1.9.2-p0/gems/rspec-core-2.3.1/lib/rspec/core/example_group.rb:118:in `describe'
    from /Users/john/Websites/Rails/InDevelopment/fastermanager/spec/models/user_spec.rb:4:in `block in <top (required)>'
    from /Users/john/.rvm/gems/ruby-1.9.2-p0/gems/rspec-core-2.3.1/lib/rspec/core/example_group.rb:131:in `module_eval'
    from /Users/john/.rvm/gems/ruby-1.9.2-p0/gems/rspec-core-2.3.1/lib/rspec/core/example_group.rb:131:in `subclass'
    from /Users/john/.rvm/gems/ruby-1.9.2-p0/gems/rspec-core-2.3.1/lib/rspec/core/example_group.rb:118:in `describe'
    from /Users/john/.rvm/gems/ruby-1.9.2-p0/gems/rspec-core-2.3.1/lib/rspec/core/extensions/object.rb:6:in `describe'
    from /Users/john/Websites/Rails/InDevelopment/fastermanager/spec/models/user_spec.rb:3:in `<top (required)>'
    from /Users/john/.rvm/gems/ruby-1.9.2-p0/gems/activesupport-3.0.3/lib/active_support/dependencies.rb:235:in `load'
    from /Users/john/.rvm/gems/ruby-1.9.2-p0/gems/activesupport-3.0.3/lib/active_support/dependencies.rb:235:in `block in load'
    from /Users/john/.rvm/gems/ruby-1.9.2-p0/gems/activesupport-3.0.3/lib/active_support/dependencies.rb:225:in `block in load_dependency'
    from /Users/john/.rvm/gems/ruby-1.9.2-p0/gems/activesupport-3.0.3/lib/active_support/dependencies.rb:596:in `new_constants_in'
    from /Users/john/.rvm/gems/ruby-1.9.2-p0/gems/activesupport-3.0.3/lib/active_support/dependencies.rb:225:in `load_dependency'
    from /Users/john/.rvm/gems/ruby-1.9.2-p0/gems/activesupport-3.0.3/lib/active_support/dependencies.rb:235:in `load'
    from /Users/john/.rvm/gems/ruby-1.9.2-p0/gems/rspec-core-2.3.1/lib/rspec/core/configuration.rb:388:in `block in load_spec_files'
    from /Users/john/.rvm/gems/ruby-1.9.2-p0/gems/rspec-core-2.3.1/lib/rspec/core/configuration.rb:388:in `map'
    from /Users/john/.rvm/gems/ruby-1.9.2-p0/gems/rspec-core-2.3.1/lib/rspec/core/configuration.rb:388:in `load_spec_files'
    from /Users/john/.rvm/gems/ruby-1.9.2-p0/gems/rspec-core-2.3.1/lib/rspec/core/command_line.rb:18:in `run'
    from /Users/john/.rvm/gems/ruby-1.9.2-p0/gems/rspec-core-2.3.1/lib/rspec/core/runner.rb:55:in `run_in_process'
    from /Users/john/.rvm/gems/ruby-1.9.2-p0/gems/rspec-core-2.3.1/lib/rspec/core/runner.rb:44:in `run'
    from /Users/john/.rvm/gems/ruby-1.9.2-p0/gems/rspec-core-2.3.1/lib/rspec/core/runner.rb:10:in `block in autorun'
</code>```

答:
Have you defined the sequence separately?  Here's an excerpt from one of my factory files:</p>

```<code>Factory.sequence(:email)       {|n| "person#{n}@example.com" }

Factory.define :user do |f|
  f.name                  "John Doe"
  f.email                 { Factory.next :email }
end
</code>```

Title: Rails: Factory Girl failing to sequence

Body:
Just getting started with factory girl, and I've come across a problem with sequencing: Specifically, it doesn't increment. I've tried changing the database type, updating from factory_girl 1.3.2 to 2.0.0.beta1 (And factory_girl_rails from 1.0 to 1.1.0.beta1), tried recreating the database, but same problem - the sequence won't increment and I get a validation error after the first time I insert a unique field.

Any assistance much appreciated. Code & trace stack below:

/spec/models/user.rb

require 'spec_helper'

describe User do   describe "test user factory is correct" do
    user = Factory(:user)

    it "should have an email ending in example.com" do
      #user.email.should match "test2@example.com"
    end

    it "should have a password of foobar" do
      user.password.should == 'foobar'
    end

    it "should have a password confirmation field of foobar" do
      user.password_confirmation.should == 'foobar'
    end
    end

end

/spec/factories/user.rb

Factory.define :user do |f|
    f.sequence(:email) { |n| puts "Email ##{n}"; "factory_#{n}@example.com" }
    f.password 'foobar'
    f.password_confirmation { |p| p.password }
end

Trace:

/Users/john/.rvm/gems/ruby-1.9.2-p0/gems/activerecord-3.0.3/lib/active_record/validations.rb:49:in `save!': Validation failed: Email has already been taken (ActiveRecord::RecordInvalid)
    from /Users/john/.rvm/gems/ruby-1.9.2-p0/gems/activerecord-3.0.3/lib/active_record/attribute_methods/dirty.rb:30:in `save!'
    from /Users/john/.rvm/gems/ruby-1.9.2-p0/gems/activerecord-3.0.3/lib/active_record/transactions.rb:242:in `block in save!'
    from /Users/john/.rvm/gems/ruby-1.9.2-p0/gems/activerecord-3.0.3/lib/active_record/transactions.rb:289:in `block in with_transaction_returning_status'
    from /Users/john/.rvm/gems/ruby-1.9.2-p0/gems/activerecord-3.0.3/lib/active_record/connection_adapters/abstract/database_statements.rb:139:in `transaction'
    from /Users/john/.rvm/gems/ruby-1.9.2-p0/gems/activerecord-3.0.3/lib/active_record/transactions.rb:204:in `transaction'
    from /Users/john/.rvm/gems/ruby-1.9.2-p0/gems/activerecord-3.0.3/lib/active_record/transactions.rb:287:in `with_transaction_returning_status'
    from /Users/john/.rvm/gems/ruby-1.9.2-p0/gems/activerecord-3.0.3/lib/active_record/transactions.rb:242:in `save!'
    from /Users/john/.rvm/gems/ruby-1.9.2-p0/gems/factory_girl-1.3.2/lib/factory_girl/proxy/create.rb:6:in `result'
    from /Users/john/.rvm/gems/ruby-1.9.2-p0/gems/factory_girl-1.3.2/lib/factory_girl/factory.rb:327:in `run'
    from /Users/john/.rvm/gems/ruby-1.9.2-p0/gems/factory_girl-1.3.2/lib/factory_girl/factory.rb:270:in `create'
    from /Users/john/.rvm/gems/ruby-1.9.2-p0/gems/factory_girl-1.3.2/lib/factory_girl/factory.rb:301:in `default_strategy'
    from /Users/john/.rvm/gems/ruby-1.9.2-p0/gems/factory_girl-1.3.2/lib/factory_girl.rb:20:in `Factory'
    from /Users/john/Websites/Rails/InDevelopment/fastermanager/spec/models/user_spec.rb:5:in `block (2 levels) in <top (required)>'
    from /Users/john/.rvm/gems/ruby-1.9.2-p0/gems/rspec-core-2.3.1/lib/rspec/core/example_group.rb:131:in `module_eval'
    from /Users/john/.rvm/gems/ruby-1.9.2-p0/gems/rspec-core-2.3.1/lib/rspec/core/example_group.rb:131:in `subclass'
    from /Users/john/.rvm/gems/ruby-1.9.2-p0/gems/rspec-core-2.3.1/lib/rspec/core/example_group.rb:118:in `describe'
    from /Users/john/Websites/Rails/InDevelopment/fastermanager/spec/models/user_spec.rb:4:in `block in <top (required)>'
    from /Users/john/.rvm/gems/ruby-1.9.2-p0/gems/rspec-core-2.3.1/lib/rspec/core/example_group.rb:131:in `module_eval'
    from /Users/john/.rvm/gems/ruby-1.9.2-p0/gems/rspec-core-2.3.1/lib/rspec/core/example_group.rb:131:in `subclass'
    from /Users/john/.rvm/gems/ruby-1.9.2-p0/gems/rspec-core-2.3.1/lib/rspec/core/example_group.rb:118:in `describe'
    from /Users/john/.rvm/gems/ruby-1.9.2-p0/gems/rspec-core-2.3.1/lib/rspec/core/extensions/object.rb:6:in `describe'
    from /Users/john/Websites/Rails/InDevelopment/fastermanager/spec/models/user_spec.rb:3:in `<top (required)>'
    from /Users/john/.rvm/gems/ruby-1.9.2-p0/gems/activesupport-3.0.3/lib/active_support/dependencies.rb:235:in `load'
    from /Users/john/.rvm/gems/ruby-1.9.2-p0/gems/activesupport-3.0.3/lib/active_support/dependencies.rb:235:in `block in load'
    from /Users/john/.rvm/gems/ruby-1.9.2-p0/gems/activesupport-3.0.3/lib/active_support/dependencies.rb:225:in `block in load_dependency'
    from /Users/john/.rvm/gems/ruby-1.9.2-p0/gems/activesupport-3.0.3/lib/active_support/dependencies.rb:596:in `new_constants_in'
    from /Users/john/.rvm/gems/ruby-1.9.2-p0/gems/activesupport-3.0.3/lib/active_support/dependencies.rb:225:in `load_dependency'
    from /Users/john/.rvm/gems/ruby-1.9.2-p0/gems/activesupport-3.0.3/lib/active_support/dependencies.rb:235:in `load'
    from /Users/john/.rvm/gems/ruby-1.9.2-p0/gems/rspec-core-2.3.1/lib/rspec/core/configuration.rb:388:in `block in load_spec_files'
    from /Users/john/.rvm/gems/ruby-1.9.2-p0/gems/rspec-core-2.3.1/lib/rspec/core/configuration.rb:388:in `map'
    from /Users/john/.rvm/gems/ruby-1.9.2-p0/gems/rspec-core-2.3.1/lib/rspec/core/configuration.rb:388:in `load_spec_files'
    from /Users/john/.rvm/gems/ruby-1.9.2-p0/gems/rspec-core-2.3.1/lib/rspec/core/command_line.rb:18:in `run'
    from /Users/john/.rvm/gems/ruby-1.9.2-p0/gems/rspec-core-2.3.1/lib/rspec/core/runner.rb:55:in `run_in_process'
    from /Users/john/.rvm/gems/ruby-1.9.2-p0/gems/rspec-core-2.3.1/lib/rspec/core/runner.rb:44:in `run'
    from /Users/john/.rvm/gems/ruby-1.9.2-p0/gems/rspec-core-2.3.1/lib/rspec/core/runner.rb:10:in `block in autorun'

Body:
Have you defined the sequence separately?  Here's an excerpt from one of my factory files:

Factory.sequence(:email)       {|n| "person#{n}@example.com" }

Factory.define :user do |f|
  f.name                  "John Doe"
  f.email                 { Factory.next :email }
end


问:
Unit testing javascript (NOT node)
I am scratching my head at this one, I must have missed something really obvious.

I have a .Net ASP MVC Web app, developed with VS2015, in which I have written some library javascript code. I would like to have some simple tests for this javascript code that I can run in my dev environment, on my own machine. I have no IIS server locally. (The server side code is fine, I use NUnit and VSs Testrunner).

I have read about Mocha (and used it back end), QUnit etc - but anything whose installation and use instructions start npm install and talks about running grunt jobs is not what I am after.

Can someone point me in the right direction / educate me?

答: If you are up for using pluralsight, it is what got me started. There is a free trial and quite a few videos on testing mvc.</p>

Title: Unit testing javascript (NOT node)


问:
Connection String Form to an SQL server
i want to connect to database in an SQL server, so is the form of this connection string correct:</p>

```<code><connectionStrings>
  <add name="OnlineStoreEntities" connectionString="Data Source=SERVERNAME\SQLEXPRESS;Initial Catalog=MVCOnlineShop;Integrated Security=True" providerName="System.Data.SqlClient" />
  <add name="MVCOnlineShop" connectionString="metadata=res://*/Models.ShopModel.csdl|res://*/Models.ShopModel.ssdl|res://*/Models.ShopModel.msl;provider=System.Data.SqlClient;provider connection string="data source=AHMADZAKARIA-PC;initial catalog=MVCOnlineShop;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
</code>```

答:
I think you need to place </p>

```<code>Data Source=SERVERNAME\\SQLEXPRESS;
</code>```

Title: Connection String Form to an SQL server

Body:
i want to connect to database in an SQL server, so is the form of this connection string correct:

<connectionStrings>
  <add name="OnlineStoreEntities" connectionString="Data Source=SERVERNAME\SQLEXPRESS;Initial Catalog=MVCOnlineShop;Integrated Security=True" providerName="System.Data.SqlClient" />
  <add name="MVCOnlineShop" connectionString="metadata=res://*/Models.ShopModel.csdl|res://*/Models.ShopModel.ssdl|res://*/Models.ShopModel.msl;provider=System.Data.SqlClient;provider connection string="data source=AHMADZAKARIA-PC;initial catalog=MVCOnlineShop;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>

Body:
I think you need to place

Data Source=SERVERNAME\\SQLEXPRESS;


问:
How do I let the user set a variable with Alexa?
For example, I would like the user to be able to set their home location as a 6 digit number. Then they can just ask my skill for an update, "when's the next bus coming", rather than having to say, "when's the next bus coming to location 123456".</p>

答:
You can persist information using either a database or by passing information along in the session object. There are lots of examples and information about using DynamoDB, such as this Alexa cookbook example.

The session object allows passing data along from each intent to the next, but only persists for the life of the session. The Amazon documentation contains the information about session, but the specifics will depend on the language you are using (eg. Java or NodeJS)


问:
integration testing ASP.NET 5 Identity
Im trying to get integration testing working for my ASP.NET 5 MVC6 Api using EF7. Im using the default project that comes with Identity already implemented.

Here is the action im trying to test in my controller (gets all the children for the logged in user)

```<code>[Authorize]
[HttpGet("api/children")]
public JsonResult GetAllChildren()
{
    var children = _repository.GetAllChildren(User.GetUserId());
    var childrenViewModel = Mapper.Map<List<ChildViewModel>>(children);
    return Json(childrenViewModel);
}
</code>```

In my test project I create an inmemory database and then do the integration tests against that

Here is the Base I use for the integration tests

```<code>public class IntegrationTestBase
{
    public TestServer TestServer;
    public IntegrationTestBase()
    {
        TestServer = new TestServer(TestServer.CreateBuilder().UseStartup<TestStartup>());
    }
}
</code>```

And here is the TestStartup (where i override the method that adds SQLServer with one that adds the inmemory test database)

```<code>public class TestStartup : Startup
{
    public TestStartup(IHostingEnvironment env) : base(env)
    {
    }

    public override void AddSqlServer(IServiceCollection services)
    {
        services.AddEntityFramework()
            .AddInMemoryDatabase()
            .AddDbContext<ApplicationDbContext>(options => {
                options.UseInMemoryDatabase();
            });
    }

}
</code>```

And the test for the action

```<code>public class ChildTests : IntegrationTestBase
{
    [Fact]
    public async Task GetAllChildren_Test()
    {
        //TODO Set Current Principal??

        var result = await TestServer.CreateClient().GetAsync("/api/children");
        result.IsSuccessStatusCode.Should().BeTrue();

        var body = await result.Content.ReadAsStringAsync();
        body.Should().NotBeNull();
        //TODO more asserts
    }
}
</code>```

Can anybody point me in the right direction on how to potentially set the CurrentPrincipal or some other way to get my integration tests working?

答:
The question is how you are authenticating in your test? On your project startup you may add a virtual function like below

```<code>public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    // ...
    UseAuthentication(app);

    // ...

    app.UseMvcWithDefaultRoute();
}

protected virtual void UseAuthentication(IApplicationBuilder app)
{
    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        AuthenticationScheme = "Cookies",
        AutomaticAuthenticate = true,
        AutomaticChallenge = true
    });
}
</code>```

And then derived a startup class in your test project and override the authentication method to do nothing or to add claim you can use a middle-ware as below

TestStartUp

```<code>internal TestStartUp : Startup
{
    protected override void UseAuthentication(IApplicationBuilder app)
    {
        app.UseMiddleware<TestAuthMiddlewareToByPass>();
    }
}
</code>```

Middle ware class

```<code>public class TestAuthMiddlewareToByPass
{
    public const string TestingCookieAuthentication = "TestCookieAuthentication";

    private readonly RequestDelegate _next;

    public TestAuthMiddlewareToByPass(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        // fake user
        ClaimsIdentity claimsIdentity = new ClaimsIdentity(Claims(), TestingCookieAuthentication);

        ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(claimsIdentity);

        context.User = claimsPrincipal;

        await _next(context);
    }

    protected virtual List<Claim> Claims()
    {
        return new List<Claim>
        {
            new Claim(ClaimTypes.Name, "admin"),
            new Claim(ClaimTypes.Role, "admin")
        };
    }
}
</code>```

Title: integration testing ASP.NET 5 Identity

Body:
Im trying to get integration testing working for my ASP.NET 5 MVC6 Api using EF7. Im using the default project that comes with Identity already implemented.

Here is the action im trying to test in my controller (gets all the children for the logged in user)

[Authorize]
[HttpGet("api/children")]
public JsonResult GetAllChildren()
{
    var children = _repository.GetAllChildren(User.GetUserId());
    var childrenViewModel = Mapper.Map<List<ChildViewModel>>(children);
    return Json(childrenViewModel);
}

In my test project I create an inmemory database and then do the integration tests against that

Here is the Base I use for the integration tests

public class IntegrationTestBase
{
    public TestServer TestServer;
    public IntegrationTestBase()
    {
        TestServer = new TestServer(TestServer.CreateBuilder().UseStartup<TestStartup>());
    }
}

And here is the TestStartup (where i override the method that adds SQLServer with one that adds the inmemory test database)

public class TestStartup : Startup
{
    public TestStartup(IHostingEnvironment env) : base(env)
    {
    }

    public override void AddSqlServer(IServiceCollection services)
    {
        services.AddEntityFramework()
            .AddInMemoryDatabase()
            .AddDbContext<ApplicationDbContext>(options => {
                options.UseInMemoryDatabase();
            });
    }

}

And the test for the action

public class ChildTests : IntegrationTestBase
{
    [Fact]
    public async Task GetAllChildren_Test()
    {
        //TODO Set Current Principal??

        var result = await TestServer.CreateClient().GetAsync("/api/children");
        result.IsSuccessStatusCode.Should().BeTrue();

        var body = await result.Content.ReadAsStringAsync();
        body.Should().NotBeNull();
        //TODO more asserts
    }
}

Can anybody point me in the right direction on how to potentially set the CurrentPrincipal or some other way to get my integration tests working?

Body:
The question is how you are authenticating in your test? On your project startup you may add a virtual function like below

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    // ...
    UseAuthentication(app);

    // ...

    app.UseMvcWithDefaultRoute();
}

protected virtual void UseAuthentication(IApplicationBuilder app)
{
    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        AuthenticationScheme = "Cookies",
        AutomaticAuthenticate = true,
        AutomaticChallenge = true
    });
}

And then derived a startup class in your test project and override the authentication method to do nothing or to add claim you can use a middle-ware as below

TestStartUp

internal TestStartUp : Startup
{
    protected override void UseAuthentication(IApplicationBuilder app)
    {
        app.UseMiddleware<TestAuthMiddlewareToByPass>();
    }
}

Middle ware class

public class TestAuthMiddlewareToByPass
{
    public const string TestingCookieAuthentication = "TestCookieAuthentication";

    private readonly RequestDelegate _next;

    public TestAuthMiddlewareToByPass(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        // fake user
        ClaimsIdentity claimsIdentity = new ClaimsIdentity(Claims(), TestingCookieAuthentication);

        ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(claimsIdentity);

        context.User = claimsPrincipal;

        await _next(context);
    }

    protected virtual List<Claim> Claims()
    {
        return new List<Claim>
        {
            new Claim(ClaimTypes.Name, "admin"),
            new Claim(ClaimTypes.Role, "admin")
        };
    }
}


问:
How to add column in Dataframe base on the value of other Columns spark
I have a Data-frame with column "Age" of type String,I want to get a new column containing the range in string format

Range as follows

[-1, 12, 17, 24, 34, 44, 54, 64, 100, 1000]

Input Values for example

```<code>Age
=====
-1
12
18
28
38
46
======
</code>```

Output Required

```<code>  Age    Age-Range
 =====  =========
 -1     (-1,12)
 12     (-1,12)
 18     (12-17)
 28     (24-34)
 38     (34-44)
 46     (44-54)
======  ==========
</code>```

Any Suggestion or Help is Highly Appreciated

答:
you can use a udf function as

```<code>def range = udf((age: String) => {
  val array = Array(-1, 12, 17, 24, 34, 44, 54, 64, 100, 1000)
  val ageInt = age.toInt
  array.filter(i => i <= ageInt).last.toString+"-"+array.filter(i => i > ageInt).head.toString
})
</code>```

and call your dataframe as

```<code>df.withColumn("Age-Range", range($"Age"))
</code>```

You should have output as

```<code>+---+---------+
|Age|Age-Range|
+---+---------+
|-1 |-1-12    |
|12 |12-17    |
|18 |17-24    |
|28 |24-34    |
|38 |34-44    |
|46 |44-54    |
+---+---------+
</code>```

The final output is not as you require but should give you more than enough ideas for the right solution.

Body:
I have a Data-frame with column "Age" of type String,I want to get a new column containing the range in string format

Range as follows

[-1, 12, 17, 24, 34, 44, 54, 64, 100, 1000]

Input Values for example

Age
=====
-1
12
18
28
38
46
======

Output Required

  Age    Age-Range
 =====  =========
 -1     (-1,12)
 12     (-1,12)
 18     (12-17)
 28     (24-34)
 38     (34-44)
 46     (44-54)
======  ==========

Any Suggestion or Help is Highly Appreciated

Body:
you can use a udf function as

def range = udf((age: String) => {
  val array = Array(-1, 12, 17, 24, 34, 44, 54, 64, 100, 1000)
  val ageInt = age.toInt
  array.filter(i => i <= ageInt).last.toString+"-"+array.filter(i => i > ageInt).head.toString
})

and call your dataframe as

df.withColumn("Age-Range", range($"Age"))

You should have output as

+---+---------+
|Age|Age-Range|
+---+---------+
|-1 |-1-12    |
|12 |12-17    |
|18 |17-24    |
|28 |24-34    |
|38 |34-44    |
|46 |44-54    |
+---+---------+

The final output is not as you require but should give you more than enough ideas for the right solution.


问:
Ignite loading similar data to particular instance
So i'm really new to apache ignite here. What i'm trying to do is load data having similar properties to a single rather than it being loaded to random instances. For example, say that some data of this form:

```<code>ROLL_NO
34569
12349
34439
45329
32359
43549
53259
34229
</code>```

As u can see, the above data is all ending with 9. Say that i have two ignite instances A and B currently running. Is there any way i can load these data ending with 9 to either of the instance A or B and NOT BOTH.

Please let me know if this is possible and if so how to accomplish this. Thanks in advance.

答:
You need to set an AffinityKeyMapper for your cache. Read javadoc for details:

https://github.com/apache/ignite/blob/master/modules/core/src/main/java/org/apache/ignite/cache/affinity/AffinityKeyMapper.java

Body:
So i'm really new to apache ignite here. What i'm trying to do is load data having similar properties to a single rather than it being loaded to random instances. For example, say that some data of this form:

ROLL_NO
34569
12349
34439
45329
32359
43549
53259
34229

As u can see, the above data is all ending with 9. Say that i have two ignite instances A and B currently running. Is there any way i can load these data ending with 9 to either of the instance A or B and NOT BOTH.

Please let me know if this is possible and if so how to accomplish this. Thanks in advance.


问:
is there any way to save my code ? To undo git reset
First am sorry for my english (BAD)

Can someone help me ?
i was code so much modules here with my team
but when i wanna go to push i was pull my friend code before..
i see favicon was merge, then i ignore that then i pull (overwritten)

but when finish the pull i forgot my code so much overwritten here :(
can i get my last work? is there any way to save my code before ?
i was pull overwrite but i haven't save it, hopefully there's a way to get my lastest save code
i use sublime text editor

答:
Assuming you committed your work (even if you never pushed it), and assuming that you still have the specific repository in which you originally did the work, you can probably recover your work using the reflog.  The reflog doesn't last forever, so this needs to be done soon after the work was "lost".

(If you did not commit your work - i.e. if it was only in your working tree and got lost before you did git add and git commit - then git does not have a record of it and you would have to rely on backups or other solutions outside of git.  And reflogs are local to a specific repo.  Neither reflogs nor "dangling commits" are typically shared during push/fetch/clone/etc.; and you need both of those things if you're going to recover anything.)

Anyway, if you say

```<code>git reflog
</code>```

it will show a list of the commits that have recently been "the current commit".  If you can find the last commit you made, you can recover it (e.g. by creating a new branch with that SHA1 as the starting point).

Body:
Assuming you committed your work (even if you never pushed it), and assuming that you still have the specific repository in which you originally did the work, you can probably recover your work using the reflog.  The reflog doesn't last forever, so this needs to be done soon after the work was "lost".

(If you did not commit your work - i.e. if it was only in your working tree and got lost before you did git add and git commit - then git does not have a record of it and you would have to rely on backups or other solutions outside of git.  And reflogs are local to a specific repo.  Neither reflogs nor "dangling commits" are typically shared during push/fetch/clone/etc.; and you need both of those things if you're going to recover anything.)

Anyway, if you say

git reflog

it will show a list of the commits that have recently been "the current commit".  If you can find the last commit you made, you can recover it (e.g. by creating a new branch with that SHA1 as the starting point).


问:
Grunt aborted due to warnings
I have already installed "npm" on my local machine. In my Gruntfile.js directory, i'm installing grunt in this way:

npm install grunt

npm install -g grunt-cli

grunt watch

The tasker is running, but i got these warnings:

Here's my gruntfile.js file

```<code>module.exports = function (grunt) {
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),

        sass: {
            dist: {
                options: {
                    style: 'compact',
                    cacheLocation: 'assets/sass/.cache-location',
                },
                files: [{
                    'assets/css/dx-epb-admin.css': 'assets/css/scss/dx-epb-admin.scss',
                    'assets/css/dx-epb-public.css': 'assets/css/scss/dx-epb-public.scss',
                    'assets/css/dx-epb-grid.css': 'assets/css/scss/dx-epb-grid.scss',
                }],
            },
        },

        autoprefixer:{
            dist: {
                files: {
                    'assets/css/dx-epb-admin.css': 'assets/css/dx-epb-admin.css',
                    'assets/css/dx-epb-admin-new.css': 'assets/css/dx-epb-admin-new.css',
                    'assets/css/dx-epb-public.css': 'assets/css/dx-epb-public.css',
                    'assets/css/dx-epb-grid.css': 'assets/css/dx-epb-grid.css',
                },
            },
        },

        watch: {
            scripts: {
                files: ['assets/js/src/*.js'],
                tasks: ['jshint', 'uglify'],
            },
            css: {
                files: [ 'assets/css/**/*.scss', 'assets/css/*.css' ],
                tasks: ['sass', 'autoprefixer', 'cssmin'],
            },
        },

        cssmin: {
            options: {
                shorthandCompacting: false,
                roundingPrecision: -1
            },
            target: {
                files: {
                    'assets/css/dx-epb-admin.min.css': ['assets/css/dx-epb-admin.css'],
                    'assets/css/dx-epb-admin-new.min.css': ['assets/css/dx-epb-admin-new.css'],
                    'assets/css/dx-epb-public.min.css': ['assets/css/dx-epb-public.css'],
                    'assets/css/dx-epb-grid.min.css': ['assets/css/dx-epb-grid.css'],
                }
            }
        },

        uglify: {
            target: {
                files: {
                    'assets/js/dx-epb-admin.min.js':
                    [
                        'assets/js/src/dx-epb-admin.js',
                    ],
                    'assets/js/dx-epb-admin-new.min.js':
                    [
                        'assets/js/src/dx-epb-admin-new.js',
                    ],
                    'assets/js/dx-epb-admin-save.min.js':
                    [
                        'assets/js/src/dx-epb-admin-save.js',
                    ],
                    'assets/js/dx-epb-control.min.js':
                    [
                        'assets/js/src/dx-epb-control.js',
                    ],
                    'assets/js/dx-epb-media-upload.min.js':
                    [
                        'assets/js/src/dx-epb-media-upload.js',
                    ],
                    'assets/js/dx-epb-public.min.js':
                    [
                        'assets/js/src/dx-epb-public.js',
                    ],
                    'assets/js/dx-epb-tinymce-button.min.js':
                    [
                        'assets/js/src/dx-epb-tinymce-button.js',
                    ]
                }
            }
        },

        jshint: {
            all: ['Gruntfile.js', 'assets/js/scripts.js'],
        },
    });

    grunt.loadNpmTasks('grunt-sass');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-contrib-cssmin');
    grunt.loadNpmTasks('grunt-autoprefixer');
    grunt.loadNpmTasks('grunt-contrib-uglify');

    grunt.registerTask('default', ['watch']);
    grunt.registerTask('css', ['sass', 'autoprefixer']);
    grunt.registerTask('minify', ['cssmin']);
    grunt.registerTask('minifyjs', ['uglify']);
};
</code>```

答:
You need to install all the missing grunt tasks listed. If you have a package.json file that lists the needed dependencies all you need to do is run npm install in the same directory.

Otherwise install each one manually from the command line like:

```<code>    npm install grunt-sass
    npm install grunt-contrib-watch
    npm install grunt-contrib-jshint
    npm install grunt-contrib-cssmin
    npm install grunt-autoprefixer
    npm install grunt-contrib-uglify
</code>```

Title: Grunt aborted due to warnings

Body:
I have already installed "npm" on my local machine. In my Gruntfile.js directory, i'm installing grunt in this way:

npm install grunt

npm install -g grunt-cli

grunt watch

The tasker is running, but i got these warnings:

Here's my gruntfile.js file

module.exports = function (grunt) {
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),

        sass: {
            dist: {
                options: {
                    style: 'compact',
                    cacheLocation: 'assets/sass/.cache-location',
                },
                files: [{
                    'assets/css/dx-epb-admin.css': 'assets/css/scss/dx-epb-admin.scss',
                    'assets/css/dx-epb-public.css': 'assets/css/scss/dx-epb-public.scss',
                    'assets/css/dx-epb-grid.css': 'assets/css/scss/dx-epb-grid.scss',
                }],
            },
        },

        autoprefixer:{
            dist: {
                files: {
                    'assets/css/dx-epb-admin.css': 'assets/css/dx-epb-admin.css',
                    'assets/css/dx-epb-admin-new.css': 'assets/css/dx-epb-admin-new.css',
                    'assets/css/dx-epb-public.css': 'assets/css/dx-epb-public.css',
                    'assets/css/dx-epb-grid.css': 'assets/css/dx-epb-grid.css',
                },
            },
        },

        watch: {
            scripts: {
                files: ['assets/js/src/*.js'],
                tasks: ['jshint', 'uglify'],
            },
            css: {
                files: [ 'assets/css/**/*.scss', 'assets/css/*.css' ],
                tasks: ['sass', 'autoprefixer', 'cssmin'],
            },
        },

        cssmin: {
            options: {
                shorthandCompacting: false,
                roundingPrecision: -1
            },
            target: {
                files: {
                    'assets/css/dx-epb-admin.min.css': ['assets/css/dx-epb-admin.css'],
                    'assets/css/dx-epb-admin-new.min.css': ['assets/css/dx-epb-admin-new.css'],
                    'assets/css/dx-epb-public.min.css': ['assets/css/dx-epb-public.css'],
                    'assets/css/dx-epb-grid.min.css': ['assets/css/dx-epb-grid.css'],
                }
            }
        },

        uglify: {
            target: {
                files: {
                    'assets/js/dx-epb-admin.min.js':
                    [
                        'assets/js/src/dx-epb-admin.js',
                    ],
                    'assets/js/dx-epb-admin-new.min.js':
                    [
                        'assets/js/src/dx-epb-admin-new.js',
                    ],
                    'assets/js/dx-epb-admin-save.min.js':
                    [
                        'assets/js/src/dx-epb-admin-save.js',
                    ],
                    'assets/js/dx-epb-control.min.js':
                    [
                        'assets/js/src/dx-epb-control.js',
                    ],
                    'assets/js/dx-epb-media-upload.min.js':
                    [
                        'assets/js/src/dx-epb-media-upload.js',
                    ],
                    'assets/js/dx-epb-public.min.js':
                    [
                        'assets/js/src/dx-epb-public.js',
                    ],
                    'assets/js/dx-epb-tinymce-button.min.js':
                    [
                        'assets/js/src/dx-epb-tinymce-button.js',
                    ]
                }
            }
        },

        jshint: {
            all: ['Gruntfile.js', 'assets/js/scripts.js'],
        },
    });

    grunt.loadNpmTasks('grunt-sass');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-contrib-cssmin');
    grunt.loadNpmTasks('grunt-autoprefixer');
    grunt.loadNpmTasks('grunt-contrib-uglify');

    grunt.registerTask('default', ['watch']);
    grunt.registerTask('css', ['sass', 'autoprefixer']);
    grunt.registerTask('minify', ['cssmin']);
    grunt.registerTask('minifyjs', ['uglify']);
};

Body:
You need to install all the missing grunt tasks listed. If you have a package.json file that lists the needed dependencies all you need to do is run npm install in the same directory.

Otherwise install each one manually from the command line like:

    npm install grunt-sass
    npm install grunt-contrib-watch
    npm install grunt-contrib-jshint
    npm install grunt-contrib-cssmin
    npm install grunt-autoprefixer
    npm install grunt-contrib-uglify


问:
SELECT one row of a table, And all rows in another table
if i have these two tables:

```<code>[    id    -     title    -     content    ]
[    1    -     title1    -     content1   ]
[    2    -     title2    -     content2   ]
</code>```

and

```<code>[    id    -     pid    -       tags   ]
[    1    -       1    -        TAG1   ]
[    2    -       1    -        TAG2   ]
[    3    -       1    -        TAG3   ]
[    4    -       2    -        TAG2   ]
</code>```

Now what i'm trying to do is Select the title and content from table1 then all tags from table2 where b.pid = a.id

so my query is

```<code>SELECT a.title, a.content, b.tags
FROM table1 a LEFT JOIN table2 b ON a.id = b.pid
WHERE a.id = 1
</code>```

What i want to get is

title1
content1
TAG1 TAG2 TAG3

but what i get is only TAG1 and repeated values of title1 content1 for each tag

Then i tried

```<code>SELECT a.title, a.content,
 (SELECT DISTINCT b.tags)
  FROM table1 a LEFT JOIN table2 b
  WHERE a.id = 1
</code>```

but still don't work as intended.

答:
For ibtain the tags related to id on the same row you could use group_concat

```<code>  select  a.title, a.content, group_concat(b.tags)
  from table1 a LEFT JOIN table2 b ON a.id = b.pid
  WHERE a.id = 1
  group by  a.title, a.content
</code>```

you can use count on the same  query too

```<code>  select  a.title, a.content, group_concat(b.tags), count(*)
  from table1 a LEFT JOIN table2 b ON a.id = b.pid
  WHERE a.id = 1
  group by  a.title, a.content
</code>```

for distinct tas you can use

```<code> select  a.title, a.content, group_concat(distinct b.tags)
  from table1 a LEFT JOIN table2 b ON a.id = b.pid
  WHERE a.id = 1
  group by  a.title, a.content
</code>```

Body:
if i have these two tables:

[    id    -     title    -     content    ]
[    1    -     title1    -     content1   ]
[    2    -     title2    -     content2   ]

and

[    id    -     pid    -       tags   ]
[    1    -       1    -        TAG1   ]
[    2    -       1    -        TAG2   ]
[    3    -       1    -        TAG3   ]
[    4    -       2    -        TAG2   ]

Now what i'm trying to do is Select the title and content from table1 then all tags from table2 where b.pid = a.id

so my query is

SELECT a.title, a.content, b.tags
FROM table1 a LEFT JOIN table2 b ON a.id = b.pid
WHERE a.id = 1

What i want to get is

title1
content1
TAG1 TAG2 TAG3

but what i get is only TAG1 and repeated values of title1 content1 for each tag

Then i tried

SELECT a.title, a.content,
 (SELECT DISTINCT b.tags)
  FROM table1 a LEFT JOIN table2 b
  WHERE a.id = 1

but still don't work as intended.

Body:
For ibtain the tags related to id on the same row you could use group_concat

  select  a.title, a.content, group_concat(b.tags)
  from table1 a LEFT JOIN table2 b ON a.id = b.pid
  WHERE a.id = 1
  group by  a.title, a.content

you can use count on the same  query too

  select  a.title, a.content, group_concat(b.tags), count(*)
  from table1 a LEFT JOIN table2 b ON a.id = b.pid
  WHERE a.id = 1
  group by  a.title, a.content

for distinct tas you can use

 select  a.title, a.content, group_concat(distinct b.tags)
  from table1 a LEFT JOIN table2 b ON a.id = b.pid
  WHERE a.id = 1
  group by  a.title, a.content


问:
wordpress couldn't connect to database
I am trying to set up Wordpress on my mac. I have done all the setup. when i hit my website, it asks for hostname,username, password. After filling up the details. I get the below message.

On some systems the name of your database is prefixed with your username, so it would be like username_. Could that be the problem?

I have checked the user privileges to the DB. Everything seems fine. Not sure why is it not working still. Please note DB connection is established and using mamp.

答: As you are using mac , there will be a default thing with some systems that was your database name start with your user-name if you are developing in local environment then it will be that username_dbname , if you are developing it under live server i.e any host based platform then you will get that as hostuserid_dbname , so make sure that you use host-name and db name with user-name (local) or hostuserid(live) and  user-name of db with user-name (local) or hostuserid(live) in cofig.php file located in your wordpress file or if you installing wordpress for first time then it will ask you graphically so that you an use the details and set it up . </p>

Title: wordpress couldn't connect to database


问:
Express promisify with axios
I'll start off and say I don't know if this is the issue, but it may very well be (hoping).

I'm using axios to post data to an API.

The data posts successfully, but never gets to the .then function. ie:

```<code>  createPage(page) {
    instance.post('/admin/createPage',page).then((response) => {
      console.log(response) <------- Never gets to.
    }).catch((error) => {
      console.log(error)
    })
  }
</code>```

I do not get the console.log(response).

I ended up adding 'es6-promisify', but how would I set that up?

For reference, here are the important files:

server.js:

```<code>import express from 'express'
import session from 'express-session'
import bodyParser from 'body-parser'
import promisify from 'es6-promisify'
import cors from 'cors'
import low from 'lowdb'
import fileAsync from 'lowdb/lib/storages/file-async'

import { initDb } from './db/index.js'
import routes from './routes/index.js'

const app = express();

const db = low('./core/db/.index.json', { storage: fileAsync })

app.use(cors())

app.set('db', db);

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.use((req,res, next) => {
    next();
});

app.use('/', routes);

app.set('port', process.env.PORT || 1337);

if(!db.has('pages').value()) {
    initDb(db);
}

const server = app.listen(app.get('port'), () => {
  console.log(`Express running → PORT ${server.address().port}`);
});
</code>```

app.js:

```<code>import React, { Component } from 'react';
import {
  BrowserRouter as Router,
  Route
} from 'react-router-dom'
import axios from 'axios'

import Header from '../components/Header'

import Dashboard from './Dashboard'
import AddEditPage from './AddEditPage'

const instance = axios.create({baseURL: 'http://localhost:1337'})

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      "pages": []
    }
    this.createPage = this.createPage.bind(this)
    this.getPages = this.getPages.bind(this)
  }

  componentDidMount() {
    this.getPages()
  }

  getPages() {
    instance.get('/admin/listPages')
      .then(
        (response) => {
          this.setState(
            {
              "pages": response.data
            }
          )
        })
      .catch((error) => {console.log(error)})
  }

  createPage(page) {
    instance.post('/admin/createPage',page).then((response) => {
      console.log(response)
    }).catch((error) => {
      console.log(error)
    })
  }

  render() {
    return (
      <Router>
        <div className="Router">
          <div className="Navbar">
            <Header />
          </div>
          <div className="Wrapper">
            <Route exact path="/" render={ () => (
              <Dashboard pages={this.state.pages} />
            )} />
            <Route path="/admin/new-page" render={ () => (
              <AddEditPage createPage={this.createPage} />
            )} />
            <Route path="/admin/edit-page/:id" render={ () => (
              <AddEditPage />
            )} />
          </div>
        </div>
      </Router>

    );
  }
}

export default App;
</code>```

答:
You didn't include your ./routes/index.js so we don't know your actual routes are and what request handlers do they use, so we can only speculate about it, but what you described is a symptom that happens when you don't return a response from your request handler.

For example, if you have something like:

```<code>router.post('/createPage', (req, res) => {
  console.log(req.body);
});
</code>```

then your request will hang forever (util it times out).

If you return a response:

```<code>router.post('/createPage', (req, res) => {
  console.log(req.body);
  res.json({ ok: true });
});
</code>```

then the request should end and return success.

But of course you didn't include enough code to know that for sure.

Title: Express promisify with axios

Body:
I'll start off and say I don't know if this is the issue, but it may very well be (hoping).

I'm using axios to post data to an API.

The data posts successfully, but never gets to the .then function. ie:

  createPage(page) {
    instance.post('/admin/createPage',page).then((response) => {
      console.log(response) <------- Never gets to.
    }).catch((error) => {
      console.log(error)
    })
  }

I do not get the console.log(response).

I ended up adding 'es6-promisify', but how would I set that up?

For reference, here are the important files:

server.js:

import express from 'express'
import session from 'express-session'
import bodyParser from 'body-parser'
import promisify from 'es6-promisify'
import cors from 'cors'
import low from 'lowdb'
import fileAsync from 'lowdb/lib/storages/file-async'

import { initDb } from './db/index.js'
import routes from './routes/index.js'

const app = express();

const db = low('./core/db/.index.json', { storage: fileAsync })

app.use(cors())

app.set('db', db);

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.use((req,res, next) => {
    next();
});

app.use('/', routes);

app.set('port', process.env.PORT || 1337);

if(!db.has('pages').value()) {
    initDb(db);
}

const server = app.listen(app.get('port'), () => {
  console.log(`Express running → PORT ${server.address().port}`);
});

app.js:

import React, { Component } from 'react';
import {
  BrowserRouter as Router,
  Route
} from 'react-router-dom'
import axios from 'axios'

import Header from '../components/Header'

import Dashboard from './Dashboard'
import AddEditPage from './AddEditPage'

const instance = axios.create({baseURL: 'http://localhost:1337'})

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      "pages": []
    }
    this.createPage = this.createPage.bind(this)
    this.getPages = this.getPages.bind(this)
  }

  componentDidMount() {
    this.getPages()
  }

  getPages() {
    instance.get('/admin/listPages')
      .then(
        (response) => {
          this.setState(
            {
              "pages": response.data
            }
          )
        })
      .catch((error) => {console.log(error)})
  }

  createPage(page) {
    instance.post('/admin/createPage',page).then((response) => {
      console.log(response)
    }).catch((error) => {
      console.log(error)
    })
  }

  render() {
    return (
      <Router>

            <Route exact path="/" render={ () => (
              <Dashboard pages={this.state.pages} />
            )} />
            <Route path="/admin/new-page" render={ () => (
              <AddEditPage createPage={this.createPage} />
            )} />
            <Route path="/admin/edit-page/:id" render={ () => (
              <AddEditPage />
            )} />

      </Router>

    );
  }
}

export default App;

Body:
You didn't include your ./routes/index.js so we don't know your actual routes are and what request handlers do they use, so we can only speculate about it, but what you described is a symptom that happens when you don't return a response from your request handler.

For example, if you have something like:

router.post('/createPage', (req, res) => {
  console.log(req.body);
});

then your request will hang forever (util it times out).

If you return a response:

router.post('/createPage', (req, res) => {
  console.log(req.body);
  res.json({ ok: true });
});

then the request should end and return success.

But of course you didn't include enough code to know that for sure.