问:
return a list of data via stored proc to dapper
I am trying to return data using Dapper via stored proc

My DTO Class is similar to below (removed some properties for brevity)

```<code>public class CarDTO
{
    public int CarID { get; set; }
    public string Manufacturer { get; set; }
    public List<CarOptionDTO> CarOptions { get; set; }
}
</code>```

So basically in the DB I have a CarOption table that has a CarID column - i.e a Car can have many options.

My DAL Layer call at the minute is as below:

```<code>    private string getCarDataSp = "[dbo].[GetCarData]";

    public IEnumerable<CarDTO> GetCarData(int customerId, int year)
    {
        return Get(db => db.Query<CarDTO>(getCarDataSp , new { CustomerID = customerId, Year = year },
                                commandType: CommandType.StoredProcedure));
    }
</code>```

Implementation of my Get function is in my BaseRepository class as:

```<code>    public T Get<T>(Func<IDbConnection, T> query)
    {
        using (IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["myDB"].ConnectionString))
        {
            return query.Invoke(db);
        }
    }
</code>```

Is it possible using Dapper I can return from my stored proc the CarOptions as well?

My stored proc at the minute is as below:

```<code>ALTER PROCEDURE [dbo].[GetCarData]
    @CustomerID int,
    @Year int
AS
BEGIN
    SET NOCOUNT ON;

    SELECT * from [dbo].Car c
    JOIN [dbo].Customer cust ON c.CarID = cust.CarID
    WHERE cust.CustID = @CustomerID AND cust.Year = @Year

END
</code>```

the query above may return many rows and the CarID and Manufacturer and the other properties I removed for Brevity. Dapper will map those back to the DTO as expected.

However, it is how to return the list of CarOptions in the stored proc  - is it possible with another query or should it be separated out somehow?  If I have CarID 1 and CarID 2 returned, for example, there may be 6 rows in the CarOption table with CarID 1 and 4 rows in the CarOption table with CarID 2 and ideally, I would like them all to be returned to the CarOptions collection via Dapper if possible?

答:
Yes...it is possible. There are a couple of ways of addressing the "one-to-many" scenario with dapper:

METHOD 1 - Return two queries, combine in DAL

```<code>ALTER PROCEDURE [dbo].[GetCarData]
    @CustomerID int,
    @Year int
AS
BEGIN
    SET NOCOUNT ON;

    --return cars
    SELECT c.*
        from [dbo].Car c
    INNER JOIN [dbo].Customer cust ON c.CarID = cust.CarID
    WHERE cust.CustID = @CustomerID AND cust.Year = @Year

    --return options
    SELECT opt.*
        from [dbo].Car c
    INNER JOIN [dbo].Customer cust ON c.CarID = cust.CarID
    INNER JOIN dbo.CarOptions opt ON op.CarID = c.CarID
    WHERE cust.CustID = @CustomerID AND cust.Year = @Year

END
</code>```

DAL

```<code>var multi = db.QueryMultiple(getCarDataSp , new { CustomerID = customerId, Year = year },
                                commandType: CommandType.StoredProcedure));

var cars = multi.Read<CarDTO>();
var options = multi.Read<CarOptionDTO>();

//wire the options to the cars
foreach(var car in cars){
    var carOptions = options.Where(w=>w.Car.CarID == car.CarID);        //I would override Equals in general so you can write w.Car.Equals(car)...do this on a common DataModel class
    car.Options = carOptions.ToList();
}
</code>```

METHOD 2 - Return one query, split in DAL

Proc

```<code>ALTER PROCEDURE [dbo].[GetCarData]
    @CustomerID int,
    @Year int
AS
BEGIN
    SET NOCOUNT ON;

    SELECT c.*,  opt.*
     from [dbo].Car c
    INNER JOIN [dbo].Customer cust ON c.CarID = cust.CarID
    LEFT OUTER JOIN dbo.CarOptions opt ON op.CarID = c.CarID
    WHERE cust.CustID = @CustomerID AND cust.Year = @Year

END
</code>```

DAL

```<code>var tuples = db.Query<CarDTO, CarOptionDTO,Tuple<CarDTO,CarOptionDTO>>(getCarDataSp , new { CustomerID = customerId, Year = year },
(car,opt)=> Tuple.Create(car,opt),                       commandType: CommandType.StoredProcedure);

//group tuples by car
var cars = tuple.GroupBy(gb=>gb.Item1.CarID)                    //again, overriding equals makes it so you can just to GroupBy(gb=>gb.Item1)
            .Select(s=>{
            var car = s.First().Item1;
            var carOptions = s.Select(t=>t.Item2).ToList()

            return car;
            });
</code>```

Enhancements

Using a temp table in the query

This puts all filtering by parameters into a single query.  Subsequent queries are drop-dead simple selects by ID.

```<code>ALTER PROCEDURE [dbo].[GetCarData]
    @CustomerID int,
    @Year int
AS
BEGIN
    SET NOCOUNT ON;

    declare @t table(CarID int);

    --filter cars (only deal with parameters here)
    INSERT INTO @t(CarID)
    SELECT c.CarID
    FROM dbo.Car c
        INNER JOIN [dbo].Customer cust ON c.CarID = cust.CarID
    WHERE cust.CustID = @CustomerID AND cust.Year = @Year

    --return cars
    SELECT c.*
    FROM [dbo].Car c
        INNER JOIN @t t ON t.CarID = c.CarID

    --return options
    SELECT opt.*
    FROM dbo.CarOptions opt
        INNER JOIN @t t ON t.CarID = opt.CarID

END
</code>```

Applying a BaseDTO to help with equality

Once you have the BaseDTO, and wire up your ID you can simply say things such as:cars.Where(w=>w.Equals(car)), dictionary[car] (if it's in there), if(car.Equals(otherCar)), or results.GroupBy(gb=>gb.Car)...

```<code>public class BaseDTO
{
    internal int ID { get; set; }

    /// <summary>
    /// If the obj is the same type with the same id we'll consider it equal.
    /// </summary>
    public override bool Equals(object obj)
    {
        if(obj == null || this.GetType() != obj.GetType())
        {
            return false;
        }

        return this.GetType().GetHashCode() == obj.GetType().GetHashCode() &&
                this.ID == (BaseDTO)obj.ID;
    }

    /// <summary>
    /// If you override equals, you should override gethashcode.
    /// http://stackoverflow.com/questions/263400/what-is-the-best-algorithm-for-an-overridden-system-object-gethashcode#263416
    /// </summary>
    public override int GetHashCode()
    {
        unchecked
        {
            int hash = 17;

            hash = hash * 23 + this.GetType().GetHashCode();
            hash = hash * 23 + this.ID;

            return hash;
        }
    }
}

public class CarDTO : BaseDTO
{
    public int CarID
    {
        get { return this.ID; }
        set { this.ID = value; }
    }
    public string Manufacturer { get; set; }
    public List<CarOptionDTO> CarOptions { get; set; }
}
</code>```

Body:
I am trying to return data using Dapper via stored proc

My DTO Class is similar to below (removed some properties for brevity)

public class CarDTO
{
    public int CarID { get; set; }
    public string Manufacturer { get; set; }
    public List<CarOptionDTO> CarOptions { get; set; }
}

So basically in the DB I have a CarOption table that has a CarID column - i.e a Car can have many options.

My DAL Layer call at the minute is as below:

    private string getCarDataSp = "[dbo].[GetCarData]";

    public IEnumerable<CarDTO> GetCarData(int customerId, int year)
    {
        return Get(db => db.Query<CarDTO>(getCarDataSp , new { CustomerID = customerId, Year = year },
                                commandType: CommandType.StoredProcedure));
    }

Implementation of my Get function is in my BaseRepository class as:

    public T Get<T>(Func<IDbConnection, T> query)
    {
        using (IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["myDB"].ConnectionString))
        {
            return query.Invoke(db);
        }
    }

Is it possible using Dapper I can return from my stored proc the CarOptions as well?

My stored proc at the minute is as below:

ALTER PROCEDURE [dbo].[GetCarData]
    @CustomerID int,
    @Year int
AS
BEGIN
    SET NOCOUNT ON;

    SELECT * from [dbo].Car c
    JOIN [dbo].Customer cust ON c.CarID = cust.CarID
    WHERE cust.CustID = @CustomerID AND cust.Year = @Year

END

the query above may return many rows and the CarID and Manufacturer and the other properties I removed for Brevity. Dapper will map those back to the DTO as expected.

However, it is how to return the list of CarOptions in the stored proc  - is it possible with another query or should it be separated out somehow?  If I have CarID 1 and CarID 2 returned, for example, there may be 6 rows in the CarOption table with CarID 1 and 4 rows in the CarOption table with CarID 2 and ideally, I would like them all to be returned to the CarOptions collection via Dapper if possible?

Body:
Yes...it is possible. There are a couple of ways of addressing the "one-to-many" scenario with dapper:

METHOD 1 - Return two queries, combine in DAL

ALTER PROCEDURE [dbo].[GetCarData]
    @CustomerID int,
    @Year int
AS
BEGIN
    SET NOCOUNT ON;

    --return cars
    SELECT c.*
        from [dbo].Car c
    INNER JOIN [dbo].Customer cust ON c.CarID = cust.CarID
    WHERE cust.CustID = @CustomerID AND cust.Year = @Year

    --return options
    SELECT opt.*
        from [dbo].Car c
    INNER JOIN [dbo].Customer cust ON c.CarID = cust.CarID
    INNER JOIN dbo.CarOptions opt ON op.CarID = c.CarID
    WHERE cust.CustID = @CustomerID AND cust.Year = @Year

END

DAL

var multi = db.QueryMultiple(getCarDataSp , new { CustomerID = customerId, Year = year },
                                commandType: CommandType.StoredProcedure));

var cars = multi.Read<CarDTO>();
var options = multi.Read<CarOptionDTO>();

//wire the options to the cars
foreach(var car in cars){
    var carOptions = options.Where(w=>w.Car.CarID == car.CarID);        //I would override Equals in general so you can write w.Car.Equals(car)...do this on a common DataModel class
    car.Options = carOptions.ToList();
}

METHOD 2 - Return one query, split in DAL

Proc

ALTER PROCEDURE [dbo].[GetCarData]
    @CustomerID int,
    @Year int
AS
BEGIN
    SET NOCOUNT ON;

    SELECT c.*,  opt.*
     from [dbo].Car c
    INNER JOIN [dbo].Customer cust ON c.CarID = cust.CarID
    LEFT OUTER JOIN dbo.CarOptions opt ON op.CarID = c.CarID
    WHERE cust.CustID = @CustomerID AND cust.Year = @Year

END

DAL

var tuples = db.Query<CarDTO, CarOptionDTO,Tuple<CarDTO,CarOptionDTO>>(getCarDataSp , new { CustomerID = customerId, Year = year },
(car,opt)=> Tuple.Create(car,opt),                       commandType: CommandType.StoredProcedure);

//group tuples by car
var cars = tuple.GroupBy(gb=>gb.Item1.CarID)                    //again, overriding equals makes it so you can just to GroupBy(gb=>gb.Item1)
            .Select(s=>{
            var car = s.First().Item1;
            var carOptions = s.Select(t=>t.Item2).ToList()

            return car;
            });

Enhancements

Using a temp table in the query

This puts all filtering by parameters into a single query.  Subsequent queries are drop-dead simple selects by ID.

ALTER PROCEDURE [dbo].[GetCarData]
    @CustomerID int,
    @Year int
AS
BEGIN
    SET NOCOUNT ON;

    declare @t table(CarID int);

    --filter cars (only deal with parameters here)
    INSERT INTO @t(CarID)
    SELECT c.CarID
    FROM dbo.Car c
        INNER JOIN [dbo].Customer cust ON c.CarID = cust.CarID
    WHERE cust.CustID = @CustomerID AND cust.Year = @Year

    --return cars
    SELECT c.*
    FROM [dbo].Car c
        INNER JOIN @t t ON t.CarID = c.CarID

    --return options
    SELECT opt.*
    FROM dbo.CarOptions opt
        INNER JOIN @t t ON t.CarID = opt.CarID

END

Applying a BaseDTO to help with equality

Once you have the BaseDTO, and wire up your ID you can simply say things such as:cars.Where(w=>w.Equals(car)), dictionary[car] (if it's in there), if(car.Equals(otherCar)), or results.GroupBy(gb=>gb.Car)...

public class BaseDTO
{
    internal int ID { get; set; }

    /// <summary>
    /// If the obj is the same type with the same id we'll consider it equal.
    /// </summary>
    public override bool Equals(object obj)
    {
        if(obj == null || this.GetType() != obj.GetType())
        {
            return false;
        }

        return this.GetType().GetHashCode() == obj.GetType().GetHashCode() &&
                this.ID == (BaseDTO)obj.ID;
    }

    /// <summary>
    /// If you override equals, you should override gethashcode.
    /// http://stackoverflow.com/questions/263400/what-is-the-best-algorithm-for-an-overridden-system-object-gethashcode#263416
    /// </summary>
    public override int GetHashCode()
    {
        unchecked
        {
            int hash = 17;

            hash = hash * 23 + this.GetType().GetHashCode();
            hash = hash * 23 + this.ID;

            return hash;
        }
    }
}

public class CarDTO : BaseDTO
{
    public int CarID
    {
        get { return this.ID; }
        set { this.ID = value; }
    }
    public string Manufacturer { get; set; }
    public List<CarOptionDTO> CarOptions { get; set; }
}


来源: stackexchange

问:
MNIST Tensorflow example
```<code>def conv2d(x, W):
  return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')

def max_pool_2x2(x):
  return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
                        strides=[1, 2, 2, 1], padding='SAME')
</code>```

This is the code from the Deep MNIST for experts tutorial on Tensorflow website.

I have two questions:

1) The documentation k-size is an integer list of length greater than 4 that refers to the size of the max-pool window. Shouldn't that be just [2,2] considering that it's a 2X2 window? I mean why is it [1, 2, 2, 1] instead of [2,2] ?

2) If we are taking a stride step on size one. Why do we need a vector of 4 values, wouldn't one value suffice?

```<code>strides = [1]
</code>```

3) If padding = 'SAME' why does the image size decrease by half? ( from 28 X 28 to 14 X 14  in the first convolutional process )

答:
I'm not sure which documentation you're referring to in this question. The maxpool window is indeed 2x2.

The step size can be different depending on the dimensions. The 4 vector is the most general case where suppose you wanted to skip images in the batch, skip different height and width and potentially even skip based on channels.  This is hardly used but has been left in.

If you have a stride of 2 along each direction then you skip every other pixel that you could potentially use for max pooling.  If you set the skip size to be [1,1,1,1] with padding same then you would indeed return a result of the same size.  The padding "SAME" refers to zero padding the image such that you add a border of height kernel hieght and a width of size kernel width to the image.

ContentLicense: CC BY-SA 3.0

Title: MNIST Tensorflow example

Body:
def conv2d(x, W):
  return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')

def max_pool_2x2(x):
  return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
                        strides=[1, 2, 2, 1], padding='SAME')

This is the code from the Deep MNIST for experts tutorial on Tensorflow website.

I have two questions:

1) The documentation k-size is an integer list of length greater than 4 that refers to the size of the max-pool window. Shouldn't that be just [2,2] considering that it's a 2X2 window? I mean why is it [1, 2, 2, 1] instead of [2,2] ?

2) If we are taking a stride step on size one. Why do we need a vector of 4 values, wouldn't one value suffice?

strides = [1]

3) If padding = 'SAME' why does the image size decrease by half? ( from 28 X 28 to 14 X 14  in the first convolutional process )


问:
python string splitting with multiple splitting points
Ok so ill get straight to the point here is my code

```<code>def digestfragmentwithenzyme(seqs, enzymes):

fragment = []
for seq in seqs:
    for enzyme in enzymes:
        results = []
        prog = re.compile(enzyme[0])
        for dingen in prog.finditer(seq):
           results.append(dingen.start() + enzyme[1])
        results.reverse()
        #result = 0
        for result in results:
            fragment.append(seq[result:])
            seq = seq[:result]
        fragment.append(seq[:result])
fragment.reverse()
return fragment
</code>```

Input for this function is a list of multiple strings (seq) e.g. :

```<code>List = ["AATTCCGGTCGGGGCTCGGGGG","AAAGCAAAATCAAAAAAGCAAAAAATC"]
</code>```

And enzymes as input:

```<code>[["TC", 1],["GC",1]]
</code>```

(note: there can be multiple given but most of them are in this matter of letters with ATCG)

The function should return a list that, in this example, contain 2 lists:

```<code>Outputlist = [["AATT","CCGGT","CGGGG","CT","CGGGGG"],["AAAG","CAAAAT","CAAAAAAG","CAAAAAAT","C"]]
</code>```

Right now i am having troubles with splitting it twice and getting the right output.

Little bit more information about the function. It looks through the string (seq) for the recognizion point. in this case TC or GC and splits it on the 2nd index of enzymes. it should do that for both strings in the list with both enzymes.

答:
Here is my solution:

Replace TC with T C, GC with G C (this is done based on index given)  and then split based on space character....

```<code>def digest(seqs, enzymes):
    res = []
    for li in seqs:
        for en in enzymes:
            li = li.replace(en[0],en[0][:en[1]]+" " + en[0][en[1]:])
        r = li.split()
        res.append(r)
    return res
seqs = ["AATTCCGGTCGGGGCTCGGGGG","AAAGCAAAATCAAAAAAGCAAAAAATC"]
enzymes = [["TC", 1],["GC",1]]
#enzymes = [["AAT", 2],["GC",1]]
print seqs
print digest(seqs, enzymes)
</code>```

the results are:

for ([["TC", 1],["GC",1]])

```<code>['AATTCCGGTCGGGGCTCGGGGG', 'AAAGCAAAATCAAAAAAGCAAAAAATC']
[['AATT', 'CCGGT', 'CGGGG', 'CT', 'CGGGGG'], ['AAAG', 'CAAAAT', 'CAAAAAAG', 'CAA
AAAAT', 'C']]
</code>```

for ([["AAT", 2],["GC",1]])

```<code>['AATTCCGGTCGGGGCTCGGGGG', 'AAAGCAAAATCAAAAAAGCAAAAAATC']
[['AA', 'TTCCGGTCGGGG', 'CTCGGGGG'], ['AAAG', 'CAAAA', 'TCAAAAAAG', 'CAAAAAA', '
TC']]
</code>```

Body:
Ok so ill get straight to the point here is my code

def digestfragmentwithenzyme(seqs, enzymes):

fragment = []
for seq in seqs:
    for enzyme in enzymes:
        results = []
        prog = re.compile(enzyme[0])
        for dingen in prog.finditer(seq):
           results.append(dingen.start() + enzyme[1])
        results.reverse()
        #result = 0
        for result in results:
            fragment.append(seq[result:])
            seq = seq[:result]
        fragment.append(seq[:result])
fragment.reverse()
return fragment

Input for this function is a list of multiple strings (seq) e.g. :

List = ["AATTCCGGTCGGGGCTCGGGGG","AAAGCAAAATCAAAAAAGCAAAAAATC"]

And enzymes as input:

[["TC", 1],["GC",1]]

(note: there can be multiple given but most of them are in this matter of letters with ATCG)

The function should return a list that, in this example, contain 2 lists:

Outputlist = [["AATT","CCGGT","CGGGG","CT","CGGGGG"],["AAAG","CAAAAT","CAAAAAAG","CAAAAAAT","C"]]

Right now i am having troubles with splitting it twice and getting the right output.

Little bit more information about the function. It looks through the string (seq) for the recognizion point. in this case TC or GC and splits it on the 2nd index of enzymes. it should do that for both strings in the list with both enzymes.

Body:
Here is my solution:

Replace TC with T C, GC with G C (this is done based on index given)  and then split based on space character....

def digest(seqs, enzymes):
    res = []
    for li in seqs:
        for en in enzymes:
            li = li.replace(en[0],en[0][:en[1]]+" " + en[0][en[1]:])
        r = li.split()
        res.append(r)
    return res
seqs = ["AATTCCGGTCGGGGCTCGGGGG","AAAGCAAAATCAAAAAAGCAAAAAATC"]
enzymes = [["TC", 1],["GC",1]]
#enzymes = [["AAT", 2],["GC",1]]
print seqs
print digest(seqs, enzymes)

the results are:

for ([["TC", 1],["GC",1]])

['AATTCCGGTCGGGGCTCGGGGG', 'AAAGCAAAATCAAAAAAGCAAAAAATC']
[['AATT', 'CCGGT', 'CGGGG', 'CT', 'CGGGGG'], ['AAAG', 'CAAAAT', 'CAAAAAAG', 'CAA
AAAAT', 'C']]

for ([["AAT", 2],["GC",1]])

['AATTCCGGTCGGGGCTCGGGGG', 'AAAGCAAAATCAAAAAAGCAAAAAATC']
[['AA', 'TTCCGGTCGGGG', 'CTCGGGGG'], ['AAAG', 'CAAAA', 'TCAAAAAAG', 'CAAAAAA', '
TC']]


问:
Drools Fusion Conversion to long not supported from java.time.ZonedDateTime
I am trying to use the Drools Fusion temporal operators before, after, and coincides but I keep getting the error:

Conversion to long not supported from java.time.ZonedDateTime

In my objects, the times I am comparing are ZonedDateTime. Does Drools require time variables be a specific type? What does the error mean by conversion to long?

I have tried using .isBefore() and .isAfter() but it seems Drools does not recognize these functions.

答:
From Drools version 7.0.0.Beta8 it is possible to use CEP temporal operators using also java.time.ZonedDateTime, along with broader java.time support.

You can find more details about temporal operators to support for java.time classes here: DROOLS-1490, until the v7 Final release will come out with documentation release notes.


问:
How to instantiate an instance of our dependency graph in Dagger2
I am learning dagger2 dependency injection framework. I loved it how it injects dependency. I read this article https://github.com/codepath/android_guides/wiki/Dependency-Injection-with-Dagger-2 I see there they explained this with the help of two Modules.

AppModule & NetModule are the two Modules. Both has constructors, so they instantiate an instance of our dependency graph like this

```<code> mNetComponent = DaggerNetComponent.builder()
                // list of modules that are part of this component need to be created here too
                .appModule(new AppModule(this)) // This also corresponds to the name of your module: %component_name%Module
                .netModule(new NetModule("https://api.github.com"))
                .build();
</code>```

Suppose I have one more Modules which do not have a constructor then how would I initialize it, as other 2 modules need values in the constructor ?

Thanks

答:
Let's say your third module is TestModule:

you can simply do this:

```<code> mNetComponent = DaggerNetComponent.builder()
                .appModule(new AppModule(this))
                .netModule(new NetModule("https://api.github.com"))
                .testModule(new TestModule())
                .build();
</code>```

Note: here .testModule will give you deprecated warning which means that you don't even have to define modules that have no constructors. They are implicitly added to the graph.

Body:
I am learning dagger2 dependency injection framework. I loved it how it injects dependency. I read this article https://github.com/codepath/android_guides/wiki/Dependency-Injection-with-Dagger-2 I see there they explained this with the help of two Modules.

AppModule & NetModule are the two Modules. Both has constructors, so they instantiate an instance of our dependency graph like this

 mNetComponent = DaggerNetComponent.builder()
                // list of modules that are part of this component need to be created here too
                .appModule(new AppModule(this)) // This also corresponds to the name of your module: %component_name%Module
                .netModule(new NetModule("https://api.github.com"))
                .build();

Suppose I have one more Modules which do not have a constructor then how would I initialize it, as other 2 modules need values in the constructor ?

Thanks

Body:
Let's say your third module is TestModule:

you can simply do this:

 mNetComponent = DaggerNetComponent.builder()
                .appModule(new AppModule(this))
                .netModule(new NetModule("https://api.github.com"))
                .testModule(new TestModule())
                .build();

Note: here .testModule will give you deprecated warning which means that you don't even have to define modules that have no constructors. They are implicitly added to the graph.


问:
cudaGetDeviceCount returned errorUnknown code=30
I installed CUDA 6.0 tookit on a Windows 8.1 machine and tried to run the deviceQuery CUDA sample. However, it returned the following error for Win32 and Win64 versions.

```<code>deviceQuery.exe Starting...

 CUDA Device Query (Runtime API) version (CUDART static linking)

cudaGetDeviceCount returned 30
-> unknown error
Result = FAIL
</code>```

I installed different versions of the drivers and tried to compile the sample code from Visual Studio but the result of the execution was same.

How can I solve this problem? Any suggestion is really welcome.

答:
Don't forget to restart your computer.

I was getting the same error (cudaGetDeviceCount 30) running samples from CUDA 8.0 on Ubuntu 14. Everything was up-to-date: Nvidia driver (375), chipset GeForce GT 730M (capacity 3). Restarting xserver made it work :)

Body:
I installed CUDA 6.0 tookit on a Windows 8.1 machine and tried to run the deviceQuery CUDA sample. However, it returned the following error for Win32 and Win64 versions.

deviceQuery.exe Starting...

 CUDA Device Query (Runtime API) version (CUDART static linking)

cudaGetDeviceCount returned 30
-> unknown error
Result = FAIL

I installed different versions of the drivers and tried to compile the sample code from Visual Studio but the result of the execution was same.

How can I solve this problem? Any suggestion is really welcome.


问:
How are dependency binaries included in my final built and installed .JAR in Maven?
1) I included a Spring Context dependency in my pom.xml project in Eclipse with Maven.

2) I ran the 'Install' phase on the project and it built properly, and the project was installed to my local .m2 repository

3) When I unzipped my .JAR, I only saw my single class that I created custom.

This brings up two questions:

1) Are external, dependency classes only included in your final built jars if a class from it is physically instantiated within your class?

and

2) How come, when I imported the SpringContextAnnotationConfig class into my class, and instantiated an instance of it, and installed my project, I STILL only saw my custom class when I unzipped my .JAR. Is this unusual? Or is the SpringContextAnnotationConfig now just written into the .class binary so that when I deploy my .jar to another JVM, it hass all its dependencies within my custom built .class binary?

Thanks

SOLUTION:

The problem was that I was expecting maven to do the same for a JAR output as it would for a WAR. When using the webapp archetype to generate a WAR file, Maven automatically packaged the required dependency jars into the WEB-INF directory.

I was basically trying to understand how a container on a remote, brand new server would run my classes without having the dependency binaries. I was attempting to run a maven built to produce a JAR file, which did not end up including my dependencies. However, when I ran maven install to build a  WAR file, my dependencies were all there ready for deployment.

答:
No, they are never included (unless you use a special plugin which does that).

See 1.

If you add this artifact as a dependency to some other project, its dependencies (and their dependencies, etc.) will be automatically added (this is controllable, so you can e.g. exclude them or change the version). But they are taken from pom.xml, not from the .jar itself. This also allows not to download same libraries a huge number of times.

For building fat jars, see e.g. How can I create an executable JAR with dependencies using Maven?. Specifically for Spring you may want Spring Boot.


问:
Mutliversion IKVM Collision
I would like to use POSTagger by Stanford and TikaOnDotNet when I am developing a .Net project. POSTagger requires IKVM 8.1 while TikaOnDotNet needs IKVM 7.4. Though I include them in different projects in VS2015, when I build the whole solution, the dll files of two versions collide, and the program throwed a runtime exception.

Is there any solutions?

答: TikaOnDotnet has been updated since version 1.12 to use the latest IKVM nuget. https://kevm.github.io/tikaondotnet/</p>

Title: Mutliversion IKVM Collision


问:
Stata esttab/LaTeX Error: Extra alignment tab has been changed to \cr
Combining and modifying this code (http://www.stata.com/statalist/archive/2012-11/msg00756.html) and this code (http://www.stata.com/statalist/archive/2009-02/msg00023.html), I try to use esttab (part of estout) in Stata to export a file that can be compiled in LaTeX. A real application of this might involve a complicated summary statistics table where one is pulling the statistics from several different sources and thus needs to utilize matrices. I am getting an error, however, in LaTeX when I compile. The error is:

```<code>Extra alignment tab has been changed to \cr.
</code>```

Stata code:

```<code>clear all
eststo clear
mat A = (1,2\5,6)
mat coln A = male:1979 male:2007
mat rown A = mystat
ereturn post
estadd matrix B = A'
eststo MaleLabel
mat A = (3,4\7,8)
mat coln A = female:1979 female:2007
mat rown A = mystat
ereturn post
estadd matrix B = A'
eststo FemaleLabel
esttab MaleLabel FemaleLabel using "esttab.tex", ///
    cell((B["1979"]B["2007"])) booktabs ///
    mgroups("Male" "Female", pattern(1 1) prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span})) ///
    noobs replace nomtitles nonum
</code>```

LaTeX code:

```<code>\documentclass[12pt]{article}
\usepackage{booktabs}
\begin{document}
\begin{table}[htbp]
\begin{center}
\input{esttab}
\end{center}
\end{table}
\end{document}
</code>```

The file that is produced from esttab is:

```<code>{
\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}
\begin{tabular}{l*{2}{c}}
\toprule
            &\multicolumn{2}{c}{Male} &\multicolumn{2}{c}{Female}\\\cmidrule(lr){2-3}\cmidrule(lr){4-5}
            &        1979&        2007&        1979&        2007\\
\midrule
mystat      &           1&           2&           3&           4\\
mystat      &           5&           6&           7&           8\\
\bottomrule
\end{tabular}
}
</code>```

Now, I can get things to work if I tweak this line:

```<code> \begin{tabular}{l*{2}{c}}
</code>```

to be:

```<code> \begin{tabular}{l*{2}{cc}}
</code>```

(I added an extra c.)

But I only know how to do this manually. What can I change in the Stata code to make this happen automatically?

答:
add this simple option to your estab code

prehead({\begin{tabular}{l*{2}{cc}}\toprule)

and you are all set my man!

Body:
Combining and modifying this code (http://www.stata.com/statalist/archive/2012-11/msg00756.html) and this code (http://www.stata.com/statalist/archive/2009-02/msg00023.html), I try to use esttab (part of estout) in Stata to export a file that can be compiled in LaTeX. A real application of this might involve a complicated summary statistics table where one is pulling the statistics from several different sources and thus needs to utilize matrices. I am getting an error, however, in LaTeX when I compile. The error is:

Extra alignment tab has been changed to \cr.

Stata code:

clear all
eststo clear
mat A = (1,2\5,6)
mat coln A = male:1979 male:2007
mat rown A = mystat
ereturn post
estadd matrix B = A'
eststo MaleLabel
mat A = (3,4\7,8)
mat coln A = female:1979 female:2007
mat rown A = mystat
ereturn post
estadd matrix B = A'
eststo FemaleLabel
esttab MaleLabel FemaleLabel using "esttab.tex", ///
    cell((B["1979"]B["2007"])) booktabs ///
    mgroups("Male" "Female", pattern(1 1) prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span})) ///
    noobs replace nomtitles nonum

LaTeX code:

\documentclass[12pt]{article}
\usepackage{booktabs}
\begin{document}
\begin{table}[htbp]
\begin{center}
\input{esttab}
\end{center}
\end{table}
\end{document}

The file that is produced from esttab is:

{
\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}
\begin{tabular}{l*{2}{c}}
\toprule
            &\multicolumn{2}{c}{Male} &\multicolumn{2}{c}{Female}\\\cmidrule(lr){2-3}\cmidrule(lr){4-5}
            &        1979&        2007&        1979&        2007\\
\midrule
mystat      &           1&           2&           3&           4\\
mystat      &           5&           6&           7&           8\\
\bottomrule
\end{tabular}
}

Now, I can get things to work if I tweak this line:

 \begin{tabular}{l*{2}{c}}

to be:

 \begin{tabular}{l*{2}{cc}}

(I added an extra c.)

But I only know how to do this manually. What can I change in the Stata code to make this happen automatically?


问:
Using 'Lock' in web applications
A few months ago I was interviewing for a job inside the company I am currently in, I dont have a strong web development background, but one of the questions he posed to me was how could you improve this block of code.

I dont remember the code block perfectly but to sum it up it was a web hit counter, and he used lock on the hitcounter.

```<code>lock(HitCounter)
{
   // Bla...
}
</code>```

However after some discussion he said, lock is good but never use it in web applications!

What is the basis behind his statement? Why shouldnt I use lock in web applications?

答:
The application domain might be recycled.

This might result in the old appdomain still finishing serving some requests and the new appdomain also serving new requests.

Static variables are not shared between them, so locking on a static global would not grant exclusivity in this case.

ContentLicense: CC BY-SA 2.5

Title: Using 'Lock' in web applications

Body:
A few months ago I was interviewing for a job inside the company I am currently in, I dont have a strong web development background, but one of the questions he posed to me was how could you improve this block of code.

I dont remember the code block perfectly but to sum it up it was a web hit counter, and he used lock on the hitcounter.

lock(HitCounter)
{
   // Bla...
}

However after some discussion he said, lock is good but never use it in web applications!

What is the basis behind his statement? Why shouldnt I use lock in web applications?


问:
Why do properties have to be class attributes in Python?
Recently I have been learning about managed attributes in Python and a common theme with properties and descriptors is, that they have to be assigned as class attributes. But nowhere can I find an explanation of why and especially why they cannot be assigned as instance attributes. So my question has actually two parts:

why do properties / descriptor instances have to be class attributes?

why can properties / descriptor instances not be instance attributes?

答:
It is because of the way Python tries to resolve attributes:

First it checks if it is defined at the class level

If yes, it checks if it is a property or a data descriptor

If yes, it follows this "path"

If no, it checks if it is a simple class variable (up to its parent classes if any)

If yes, it checks the instance overrides this class attribute value, if yes, it returns the overriden value, if no it returns the class attribute value

If no, it checks if the instance declares this attribute

If yes, it returns the instance attribute value

If no, it throws AttributeError

Voila ;-)

EDIT

I just found this link which explains it better than me.

Another nice illustration.


问:
Storing JFrame output into a String in the Main Program
It seems to me that so far, everything that happens within JFrame stays within JFrame. (Probably should have gotten into JavaFX instead of Swing)

Let's say you have a JFrame Class (gui_frame) that utilizes JButtons with a nested class named HandlerClass that implements ActionListener, as shown below:

```<code>public class gui_frame extends JFrame {
    private JButton button1;
    public gui_frame() {
         super("Title");
         setLayout(new FlowLayout());

         button1 = new JButton("Hello");
         add(button1);

         HandlerClass handler = new HandlerClass();
         button1.addActionListener(handler);
    }

   private class HandlerClass implements ActionListener{
          public void actionPerformed(ActionEvent e){
          //insert code here
          }
   }
}
</code>```

And then you have the main code, which calls upon this gui_frame class.

```<code>public class main {
    public static void main(String[] args){
        //insert some unrelated code here

        gui_frame gf = new gui_frame();
        gf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        gf.setSize(400,75);
        gf.setVisible(true);

        String button_name;
        //insert some code that uses button_name
    }
}
</code>```

Essentially, I'm trying to store the name of the button in the JFrame class gui_frame (in this case "Hello"), AFTER BEING CLICKED, into the String button_name in the main class, during run time.

Is this possible? What do I have to insert into the actionPerformed method in the gui_frame, in order to make this happen?

答:
There's a few ways that you could do this:

implement the ActionListener as a lambda in the main class (btw, that should be capitalized, i.e. "Main"),  and pass the lambda to the gui_frame class (again, that should be "GuiFrame"), and have the GuiFrame class apply the listener to the button

create an interface for the GuiFrame class to use to notify the Main class that the button has been clicked (and the name of the button). Have the Main class implement that interface, and then pass the instance of Main to the GuiFrame class. Then have the GuiFrame's ActionListener call the method in the Main class' interface to notify it.

Store the name of the last clicked button in the GuiFrame class, and have the Main class ask for it when it needs it (if it doesn't need to know when the button is clicked).

Body:
It seems to me that so far, everything that happens within JFrame stays within JFrame. (Probably should have gotten into JavaFX instead of Swing)

Let's say you have a JFrame Class (gui_frame) that utilizes JButtons with a nested class named HandlerClass that implements ActionListener, as shown below:

public class gui_frame extends JFrame {
    private JButton button1;
    public gui_frame() {
         super("Title");
         setLayout(new FlowLayout());

         button1 = new JButton("Hello");
         add(button1);

         HandlerClass handler = new HandlerClass();
         button1.addActionListener(handler);
    }

   private class HandlerClass implements ActionListener{
          public void actionPerformed(ActionEvent e){
          //insert code here
          }
   }
}

And then you have the main code, which calls upon this gui_frame class.

public class main {
    public static void main(String[] args){
        //insert some unrelated code here

        gui_frame gf = new gui_frame();
        gf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        gf.setSize(400,75);
        gf.setVisible(true);

        String button_name;
        //insert some code that uses button_name
    }
}

Essentially, I'm trying to store the name of the button in the JFrame class gui_frame (in this case "Hello"), AFTER BEING CLICKED, into the String button_name in the main class, during run time.

Is this possible? What do I have to insert into the actionPerformed method in the gui_frame, in order to make this happen?


问:
Why is exponential integrator method giving poor results?
```<code>//u' + Au = g(t,u) can be solved by exponential integrators also
//Following snippet is for exp INtegrators
A = -full(Strang(11))
A[end,1]=1;A[1,end]=1;
g(t,u) = 2-u
u0 = zeros(11);u0[6]=1
nsteps = 1000
tmax = 10.0
h = tmax/nsteps
u = u0
t = 0
for k in 1:nsteps
    u = expm(-h*A)*u + h*((expm(-h*A)-1)\(-h*A))*g(t,u)
    t = k*h
end
//this is for euler's method
for k in 1:nsteps
    u += h*(A*u + h*g(t,u))
    t = k*h
end
</code>```

Why are they giving poor results?

The method is exploding very badly, it should converge to [1.99]*11 , or something like that?

Is there any mistake while implementing Exp Integrator?

答:
The exponential Euler-Rosenbrock step should be for u'=Lu+g(t,u)

```<code>u = expm(h*L)*u + ((expm(h*L)-1)/L)*g(t,u)
</code>```

Note that the inverted matrix is L (in Matlab A/B == A*inv(B) and A\B == inv(A)*B), and there is no naked h in the formula. In your case, L = -A.

An alternative method to split off the exponential part has is as follows. Set u(t) = exp(-t*A)*v(t) which translates into the differential equation

```<code>exp(-t*A)*v'(t) = g(t,exp(-t*A)*v((t))
</code>```

Now apply the forward Euler step for v

```<code>v(t+h) = v(t) + h * exp(t*A)*g(t,exp(-t*A)*v((t))
</code>```

which translated back into terms in u gives

```<code>u(t+h) = exp(-(t+h)*A)*v(t+h)
       = exp(-h*A) * ( u(t) + h * g(t,u(t)) )
</code>```

This should equally result in a first order method.

Body:
//u' + Au = g(t,u) can be solved by exponential integrators also
//Following snippet is for exp INtegrators
A = -full(Strang(11))
A[end,1]=1;A[1,end]=1;
g(t,u) = 2-u
u0 = zeros(11);u0[6]=1
nsteps = 1000
tmax = 10.0
h = tmax/nsteps
u = u0
t = 0
for k in 1:nsteps
    u = expm(-h*A)*u + h*((expm(-h*A)-1)\(-h*A))*g(t,u)
    t = k*h
end
//this is for euler's method
for k in 1:nsteps
    u += h*(A*u + h*g(t,u))
    t = k*h
end

Why are they giving poor results?

The method is exploding very badly, it should converge to [1.99]*11 , or something like that?

Is there any mistake while implementing Exp Integrator?

Body:
The exponential Euler-Rosenbrock step should be for u'=Lu+g(t,u)

u = expm(h*L)*u + ((expm(h*L)-1)/L)*g(t,u)

Note that the inverted matrix is L (in Matlab A/B == A*inv(B) and A\B == inv(A)*B), and there is no naked h in the formula. In your case, L = -A.

An alternative method to split off the exponential part has is as follows. Set u(t) = exp(-t*A)*v(t) which translates into the differential equation

exp(-t*A)*v'(t) = g(t,exp(-t*A)*v((t))

Now apply the forward Euler step for v

v(t+h) = v(t) + h * exp(t*A)*g(t,exp(-t*A)*v((t))

which translated back into terms in u gives

u(t+h) = exp(-(t+h)*A)*v(t+h)
       = exp(-h*A) * ( u(t) + h * g(t,u(t)) )

This should equally result in a first order method.

ContentLicense: CC BY-SA 4.0


问:
Query returning records with duplicate data because of the wrong data in one of the columns
I have a record of an employee but my query is returning 2 records of this employee because the address column is different between the 2. How can solve this problem? Is it something that can be done? EMP_ID, CUS_LAST_NAME, CUS_FIRST_NAME, and GUARDIAN_ADDRESS are from 3 separate tables.

Example:

```<code>ID          EMP_ID      CUS_LAST_NAME   CUS_FIRST_NAME  GUARDIAN_ADDRESS
00000000    11111111    Jackson         Michael         1111 Street Apt 1

ID          EMP_ID      CUS_LAST_NAME   CUS_FIRST_NAME  GUARDIAN_ADDRESS
00000000    11111111    Jackson         Michael         1111 Street
</code>```

答:
```<code>--start with unique list of clients
    SELECT DISTINCT a.ID, a.EMP_ID, e.EMP_LAST_NAME, e.EMP_FIRST_NAME,     e.ADDRESS
FROM TABLE1 a
--attach on employee data on id
    OUTER APPLY (SELECT TOP 1 b.EMP_LAST_NAME, b.EMP_FIRST_NAME, b.ADDRESS
    FROM TABLE2 b
    WHERE a.id = b.id
--use order by clause to change order and choose what top employee record u     want to choose
    ORDER BY b.address
    ) e
</code>```

Body:
I have a record of an employee but my query is returning 2 records of this employee because the address column is different between the 2. How can solve this problem? Is it something that can be done? EMP_ID, CUS_LAST_NAME, CUS_FIRST_NAME, and GUARDIAN_ADDRESS are from 3 separate tables.

Example:

ID          EMP_ID      CUS_LAST_NAME   CUS_FIRST_NAME  GUARDIAN_ADDRESS
00000000    11111111    Jackson         Michael         1111 Street Apt 1

ID          EMP_ID      CUS_LAST_NAME   CUS_FIRST_NAME  GUARDIAN_ADDRESS
00000000    11111111    Jackson         Michael         1111 Street


问:
no module name pip : after changing permission of python folder
here is what i did before i messed up everything :

i tried to install a package using pip3 , after a long time the download finished and suddenly the error about permission came up because i forgot to use sudo at first and because I didn't want to download the packages again and didn't know where is the pip cache folder is , I did a very stupid thing i changed the permission of the entire python folder in the /usr/bin/ to install package without sudo , after this i tried this :

```<code>pip3 install tensorflow
File "/usr/bin/pip3", line 7, in <module>
    from pip import main
ImportError: No module named 'pip'
</code>```

i got these damn error ,
can anybody help me fix this ?

Edit :
here is my sequence of the command i used :

1 - pip3 install tensorflow
    -- the error came up

2 - sudo find /usr/lib/python3.5/ -type d -exec chmod 766 {} \;

3 -  sudo find /usr/lib/python3.5/ -type f -exec chmod 766 {} \;

答:
First, and foremost, I consider your approach quite unwise. You have now changed the permissions of all files and directories for the owner, the group, and others.

In principle you just needed to ensure that pip3 (by extension, your user-account) would be able write files and directories in a directory owned by root (presumably /usr/lib/python3.5/site-packages). You could have accomplished this by:

```<code>sudo chmod o+w /usr/lib/python3.5/site-packages
</code>```

Alternatively you could have changed the ownership of this folder. IMPORTANT: when doing this kind of thing, be sure to know what you are doing, and don't forget to change everything back as soon as possible. Things can be broken, and security issues can be created.

Now as to a solution to your problem. You have now given the directories the following permissions -rwxrw-rw- (6 = 4 (read) + 2 (write)). However for users, and programs executed on its behalf, to do anything to/from a directory they need the right to execute. For this you should have used 5 instead of 6 (5 = 4 (read) + 1 (execute)). To correct:

```<code>sudo find /usr/lib/python3.5/ -type d -exec chmod 755 {} \;
</code>```

Then, I think that for Python to correctly load compiled libraries (shared-objects or .so files) they should also have these permissions. Judging from my own Python directory I would probably do:

```<code>sudo find /usr/lib/python3.5/ -type f -exec chmod 644 {} \;
sudo find /usr/lib/python3.5/ -type f -iname '*.so' -exec chmod 755 {} \;
</code>```

to set everything back to it's original state.

P.S. I am no expert in pip, so I have no idea what the protocol is to avoid pip from re-downloading upon retrying a failed installation.

Body:
here is what i did before i messed up everything :

i tried to install a package using pip3 , after a long time the download finished and suddenly the error about permission came up because i forgot to use sudo at first and because I didn't want to download the packages again and didn't know where is the pip cache folder is , I did a very stupid thing i changed the permission of the entire python folder in the /usr/bin/ to install package without sudo , after this i tried this :

pip3 install tensorflow
File "/usr/bin/pip3", line 7, in <module>
    from pip import main
ImportError: No module named 'pip'

i got these damn error ,
can anybody help me fix this ?

Edit :
here is my sequence of the command i used :

1 - pip3 install tensorflow
    -- the error came up

2 - sudo find /usr/lib/python3.5/ -type d -exec chmod 766 {} \;

3 -  sudo find /usr/lib/python3.5/ -type f -exec chmod 766 {} \;

Body:
First, and foremost, I consider your approach quite unwise. You have now changed the permissions of all files and directories for the owner, the group, and others.

In principle you just needed to ensure that pip3 (by extension, your user-account) would be able write files and directories in a directory owned by root (presumably /usr/lib/python3.5/site-packages). You could have accomplished this by:

sudo chmod o+w /usr/lib/python3.5/site-packages

Alternatively you could have changed the ownership of this folder. IMPORTANT: when doing this kind of thing, be sure to know what you are doing, and don't forget to change everything back as soon as possible. Things can be broken, and security issues can be created.

Now as to a solution to your problem. You have now given the directories the following permissions -rwxrw-rw- (6 = 4 (read) + 2 (write)). However for users, and programs executed on its behalf, to do anything to/from a directory they need the right to execute. For this you should have used 5 instead of 6 (5 = 4 (read) + 1 (execute)). To correct:

sudo find /usr/lib/python3.5/ -type d -exec chmod 755 {} \;

Then, I think that for Python to correctly load compiled libraries (shared-objects or .so files) they should also have these permissions. Judging from my own Python directory I would probably do:

sudo find /usr/lib/python3.5/ -type f -exec chmod 644 {} \;
sudo find /usr/lib/python3.5/ -type f -iname '*.so' -exec chmod 755 {} \;

to set everything back to it's original state.

P.S. I am no expert in pip, so I have no idea what the protocol is to avoid pip from re-downloading upon retrying a failed installation.


问:
Split a text in excel containing text and number in brackets
I want to split a cell into multiple columns with each own.
Please see below for example.

```<code>Currrent Cell:
Mobile Users (300)
Want to Split into two more cells:
Device Category        Number of Users
Mobile Users           300
</code>```

I have used LEFT formula to separate Mobile Users one but cannot split 300 number successfully out of brackets.

答:
Use this function to get numbers only.</p>

```<code>Function GetNums(target As Range)
    Dim MyStr As String, i As Integer
    MyStr = ""
    If Len(target.Value) = 0 Then GoTo GoExit
    If target.Value = "None" Then GoTo GoNone
    For i = 1 To Len(target.Value)
        If IsNumeric(Mid(target, i, 1)) Then MyStr = MyStr & Mid(target, i, 1)
    Next i
    GoTo GoExit
GoNone:
    GetNums = "None"
    Exit Function
GoExit:
    GetNums = MyStr

End Function
</code>```

Body:
I want to split a cell into multiple columns with each own.
Please see below for example.

Currrent Cell:
Mobile Users (300)
Want to Split into two more cells:
Device Category        Number of Users
Mobile Users           300

I have used LEFT formula to separate Mobile Users one but cannot split 300 number successfully out of brackets.

Body:
Use this function to get numbers only.

Function GetNums(target As Range)
    Dim MyStr As String, i As Integer
    MyStr = ""
    If Len(target.Value) = 0 Then GoTo GoExit
    If target.Value = "None" Then GoTo GoNone
    For i = 1 To Len(target.Value)
        If IsNumeric(Mid(target, i, 1)) Then MyStr = MyStr & Mid(target, i, 1)
    Next i
    GoTo GoExit
GoNone:
    GetNums = "None"
    Exit Function
GoExit:
    GetNums = MyStr

End Function


问:
How to make a progress-bar in copy or query?
How can I make a progress-bar in copy or SQL query or file transfer (rapi)?

Or some thing's that I can't measure?

Thanks for any help.

答: Set the progress bar to marquee instead of progress.  This will let your users know that something is still happening without providing exact percentages.</p>

OwnerDisplayName: Gold

LastEditorDisplayName: Federico Ramponi

OwnerDisplayName: Tom Anderson


问:
can't create simple image from php exec , can create with the same command as standalone
I have this code running in CentOS 5.5 ,PHP 5.1.6 ,Apache/2.2.3 ,ImageMagick 6.2.8

```<code>$convert = "/usr/bin/convert";
$command = "$convert -size 100x100 xc:blue mytest.jpg";
$test_image = exec($command);
echo "<img src=\"mytest.jpg\">";
</code>```

when i run the php tester i dont get the image created , only the echo string printed on page as html.

but when i run the same command as onliner the image does created just fine.

```<code>/usr/bin/convert -size 100x100 xc:blue mytest.jpg
</code>```

what is wrong here i can't tell.

答: Your PHP assumes that the web server has permissions to execute programs and to write to the current directory. You should use popen() to send the image to stdout and either use the data: scheme to embed the image data into the HTML, or put the PHP script as the src for the img tag and output the appropriate header and then the image data.

Body:
I have this code running in CentOS 5.5 ,PHP 5.1.6 ,Apache/2.2.3 ,ImageMagick 6.2.8

$convert = "/usr/bin/convert";
$command = "$convert -size 100x100 xc:blue mytest.jpg";
$test_image = exec($command);
echo "";

when i run the php tester i dont get the image created , only the echo string printed on page as html.

but when i run the same command as onliner the image does created just fine.

/usr/bin/convert -size 100x100 xc:blue mytest.jpg

what is wrong here i can't tell.


问:
Database control or control datas after I pull them out
I would like to ask which approach is better/faster. Should I pull out the data's from database and then proccess them with a programming language, or should I just pull out the data I want by doing the controls inside SQL Query??(which means the design of database will be more complicated). I think doing the controls in programming language is slower + i would need to withdraw A lot data, in huge databases it would be nonsense. In my case I want to design a database that has in store strings of file paths for images...</p>

答:
It's all about balance.

Selecting huge amounts of data and transferring them back to your client code will take time, and load your network and your database.

If the processing you want to do on the data can be done inside the database, then this will of course be a lot faster.

If, however, said processing involves complex application code that takes a long time to run, it can be an option.

For example, let's say you grab 10000 rows from your database, and it takes a second. If your program does something interesting with them, and it takes 10 minutes, then the time to bring in the data is well amortized. If, on the other hand, all you do is set x=x+1, then really.... no.


问:
Authorization when two ASP.NET MVC project instances work in parallel
I have one ASP.NET MVC project. I have several web sites as instances of that project working on the same server, e.g. on 8000 and 8001 ports. When I authorize on 8000, if I've been authorized on 8001, I am automatically logged out on 8001 site, and vice versa. What's the problem? Is it about cookies? What are the possible ways to solve it?</p>

答:
The problem seems like those sites share primary domain name. As the result, they can also share authentication cookie.

For example, http://site1.example.com and http://site2.example.com

You can do one of the followings not to share cookies between sub-domains.

Option 1

Specify different machine key for each site in their web.config

```<code><system.web>
  <machineKey decryptionKey="..." validationKey="..." />
</system.web>
</code>```

Option 2

Specify full domain name in web.config's form tag

```<code><authentication mode="Forms">
   <forms loginUrl="~/Account/Login" timeout="2880" domain="site1.example.com" />
 </authentication>
</code>```

Body:
The problem seems like those sites share primary domain name. As the result, they can also share authentication cookie.

For example, http://site1.example.com and http://site2.example.com

You can do one of the followings not to share cookies between sub-domains.

Option 1

Specify different machine key for each site in their web.config

<system.web>
  <machineKey decryptionKey="..." validationKey="..." />
</system.web>

Option 2

Specify full domain name in web.config's form tag

<authentication mode="Forms">
   <forms loginUrl="~/Account/Login" timeout="2880" domain="site1.example.com" />
 </authentication>


问:
Implements live highcharts in ionic 2
I want to implement a live chart : http://www.highcharts.com/demo/dynamic-update/sand-signika in ionic 2, so angular2

I had tried many times, but always I got wrong.

I saw this code in js :

```<code>$(document).ready(function () {
    Highcharts.setOptions({
        global: {
            useUTC: false
        }
    });

    Highcharts.chart('container', {
        chart: {
            type: 'spline',
            animation: Highcharts.svg, // don't animate in old IE
            marginRight: 10,
            events: {
                load: function () {

                    // set up the updating of the chart each second
                    var series = this.series[0];
                    setInterval(function () {
                        var x = (new Date()).getTime(), // current time
                            y = Math.random();
                        series.addPoint([x, y], true, true);
                    }, 1000);
                }
            }
        },
        title: {
            text: 'Live random data'
        },
        xAxis: {
            type: 'datetime',
            tickPixelInterval: 150
        },
        yAxis: {
            title: {
                text: 'Value'
            },
            plotLines: [{
                value: 0,
                width: 1,
                color: '#808080'
            }]
        },
        tooltip: {
            formatter: function () {
                return '<b>' + this.series.name + '</b><br/>' +
                    Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + '<br/>' +
                    Highcharts.numberFormat(this.y, 2);
            }
        },
        legend: {
            enabled: false
        },
        exporting: {
            enabled: false
        },
        series: [{
            name: 'Random data',
            data: (function () {
                // generate an array of random data
                var data = [],
                    time = (new Date()).getTime(),
                    i;

                for (i = -19; i <= 0; i += 1) {
                    data.push({
                        x: time + i * 1000,
                        y: Math.random()
                    });
                }
                return data;
            }())
        }]
    });
});
</code>```

But it gives me errors on Highcharts. Also on $(document(.ready()) but i just remove it and it works, so the problem is Highcharts.

Im woring in typescript so also the synthax is different.
Also I saw this : here but no idea how to implement.

My purpose is to achive a realtime line chart in ionic 2.

答:
If you want to use Highcharts in Angular2 you can do it via
Angular2 HighCharts that provides the correct bindings.

The instructions worked fine for me:

From CL:
    npm install angular2-highcharts --save

In your App.module.ts:

```<code>import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ChartModule } from 'angular2-highcharts';
import { App } from './App';

@NgModule({
    imports: [
      BrowserModule,
      ChartModule.forRoot(require('highcharts')
    ],
    declarations: [App],
    bootstrap: [App]
})
export class AppModule {}
</code>```

Title: Implements live highcharts in ionic 2

Body:
I want to implement a live chart : http://www.highcharts.com/demo/dynamic-update/sand-signika in ionic 2, so angular2

I had tried many times, but always I got wrong.

I saw this code in js :

$(document).ready(function () {
    Highcharts.setOptions({
        global: {
            useUTC: false
        }
    });

    Highcharts.chart('container', {
        chart: {
            type: 'spline',
            animation: Highcharts.svg, // don't animate in old IE
            marginRight: 10,
            events: {
                load: function () {

                    // set up the updating of the chart each second
                    var series = this.series[0];
                    setInterval(function () {
                        var x = (new Date()).getTime(), // current time
                            y = Math.random();
                        series.addPoint([x, y], true, true);
                    }, 1000);
                }
            }
        },
        title: {
            text: 'Live random data'
        },
        xAxis: {
            type: 'datetime',
            tickPixelInterval: 150
        },
        yAxis: {
            title: {
                text: 'Value'
            },
            plotLines: [{
                value: 0,
                width: 1,
                color: '#808080'
            }]
        },
        tooltip: {
            formatter: function () {
                return '' + this.series.name + '
' +
                    Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + '
' +
                    Highcharts.numberFormat(this.y, 2);
            }
        },
        legend: {
            enabled: false
        },
        exporting: {
            enabled: false
        },
        series: [{
            name: 'Random data',
            data: (function () {
                // generate an array of random data
                var data = [],
                    time = (new Date()).getTime(),
                    i;

                for (i = -19; i <= 0; i += 1) {
                    data.push({
                        x: time + i * 1000,
                        y: Math.random()
                    });
                }
                return data;
            }())
        }]
    });
});

But it gives me errors on Highcharts. Also on $(document(.ready()) but i just remove it and it works, so the problem is Highcharts.

Im woring in typescript so also the synthax is different.
Also I saw this : here but no idea how to implement.

My purpose is to achive a realtime line chart in ionic 2.

Body:
If you want to use Highcharts in Angular2 you can do it via
Angular2 HighCharts that provides the correct bindings.

The instructions worked fine for me:

From CL:
    npm install angular2-highcharts --save

In your App.module.ts:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ChartModule } from 'angular2-highcharts';
import { App } from './App';

@NgModule({
    imports: [
      BrowserModule,
      ChartModule.forRoot(require('highcharts')
    ],
    declarations: [App],
    bootstrap: [App]
})
export class AppModule {}


问:
LocalDate in form
I have a question about Spring + Thymeleaf date format.
I have a simple entity with LocalDate date field. I want to get this date from a user in form and save it to MySQL database.
I'm getting such an error:

Failed to convert property value of type java.lang.String to required type java.time.LocalDate for property date; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type java.lang.String to type java.time.LocalDate for value 2019-04-30; nested exception is java.time.format.DateTimeParseException: Text 2019-04-30 could not be parsed at index 2

My entity:

```<code>@Entity
@Table(name="game")
public class Game{

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    @Transient
    private User gameOwner;
    private LocalDate date;
    private LocalTime time;

    //other fields
</code>```

Thymeleaf view / form:

```<code><form action="#" th:action="@{/games/addForm}" th:object="${gameForm}" method="post">
    <p>Date: <input type="date" th:field="*{date}" /></p>
</form>
</code>```

What's the reason for this problem? Maybe there is the other, better way to storage date?

答:
Problem solved..
I don't know why but changing my template to:

```<code><input type="date" th:value="*{date}" th:field="*{date}" />
</code>```

and adding @DateTimeFormat(pattern = "yyyy-MM-dd") to entity field solved the problem.

Title: LocalDate in form

Body:
I have a question about Spring + Thymeleaf date format.
I have a simple entity with LocalDate date field. I want to get this date from a user in form and save it to MySQL database.
I'm getting such an error:

Failed to convert property value of type java.lang.String to required type java.time.LocalDate for property date; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type java.lang.String to type java.time.LocalDate for value 2019-04-30; nested exception is java.time.format.DateTimeParseException: Text 2019-04-30 could not be parsed at index 2

My entity:

@Entity
@Table(name="game")
public class Game{

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    @Transient
    private User gameOwner;
    private LocalDate date;
    private LocalTime time;

    //other fields

Thymeleaf view / form:

<form action="#" th:action="@{/games/addForm}" th:object="${gameForm}" method="post">

Date: <input type="date" th:field="*{date}" />

</form>

What's the reason for this problem? Maybe there is the other, better way to storage date?

Body:
Problem solved..
I don't know why but changing my template to:

<input type="date" th:value="*{date}" th:field="*{date}" />

and adding @DateTimeFormat(pattern = "yyyy-MM-dd") to entity field solved the problem.


问:
Adding a property to a function
You can assign a property to a function, but is that a good idea?
In this example, I'm showing that you can't create a property to a function inside the function, but you can outside it.

Q: Is a.questionable considered an ok JavaScript programming practice?

function a() {
a.bad = 1
}
a.questionable = 2

function d() {
  console.log(a.bad)
  console.log(a.questionable)
}
d()```

This question was inspired by JavaScript: Understanding the Weird Parts

答:
In this example, I'm showing that you can't create a property to a function inside the function, but you can outside it.

This is actually not the case. You can add properties to a function anywhere you have a reference to it. The problem is that you haven't called a() and so the line a.bad = 1 has never had a chance to run.

function a() {
a.bad = 1
}
a.questionable = 2

function d() {
  console.log(a.bad)
  console.log(a.questionable)
}
a()
d()```
</div>
</div>
</p>

<blockquote>
  <p>Q: Is <code>a.questionable</code> considered an ok JavaScript programming practice?</p>
</blockquote>

<p>jQuery uses it quite extensively (think <code>jQuery.fn</code>, <code>jQuery.extend</code>, etc.) — so no, I don't think it is considered a "bad" programming practice per se. In fact, adding properties to a constructor function was the only way to mimic static fields and methods before ES6 introduced them as a part of <code>class</code> syntax.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function Constructor() {

}
Constructor.staticMethod = function () {
  return "I'm a static method!"
}

Constructor.staticProperty = "I'm a static property!"

console.log(
  Constructor.staticMethod(),
  Constructor.staticProperty
)</code>```

Title: Adding a property to a function

Body:
You can assign a property to a function, but is that a good idea?
In this example, I'm showing that you can't create a property to a function inside the function, but you can outside it.

Q: Is a.questionable considered an ok JavaScript programming practice?

function a() {
a.bad = 1
}
a.questionable = 2

function d() {
  console.log(a.bad)
  console.log(a.questionable)
}
d()

This question was inspired by JavaScript: Understanding the Weird Parts

Body:
In this example, I'm showing that you can't create a property to a function inside the function, but you can outside it.

This is actually not the case. You can add properties to a function anywhere you have a reference to it. The problem is that you haven't called a() and so the line a.bad = 1 has never had a chance to run.

function a() {
a.bad = 1
}
a.questionable = 2

function d() {
  console.log(a.bad)
  console.log(a.questionable)
}
a()
d()

Q: Is a.questionable considered an ok JavaScript programming practice?

jQuery uses it quite extensively (think jQuery.fn, jQuery.extend, etc.) — so no, I don't think it is considered a "bad" programming practice per se. In fact, adding properties to a constructor function was the only way to mimic static fields and methods before ES6 introduced them as a part of class syntax.

function Constructor() {

}
Constructor.staticMethod = function () {
  return "I'm a static method!"
}

Constructor.staticProperty = "I'm a static property!"

console.log(
  Constructor.staticMethod(),
  Constructor.staticProperty
)


问:
Array: 4th dimension, isset return not reliable
Does anybody know, how it can be, that this code echoes yahoo? There is clearly no 4th array with the key 'something', but it keeps thinking it's like that. Bug? Feature?

```<code>$array = array('a' => array('b' => array('c' => 'test')));
echo '```';
var_dump($array);
echo '```';
if (isset($array['a']['b']['c']['something'])) {
    echo 'yahoo';
}
</code>```

答:
You'd want to use is_array($array['a']['b']['c']) rather than isset($array['a']['b']['c']['something']) in this case, or maybe a crafty combination of the two to make sure you don't get any errors if it's not set when you're checking to see if it's an array.

Something like:

```<code>if(isset($array['a']['b']['c']['something']) && is_array($array['a']['b']['c'])){ [...] }
</code>```

Body:
Does anybody know, how it can be, that this code echoes yahoo? There is clearly no 4th array with the key 'something', but it keeps thinking it's like that. Bug? Feature?

$array = array('a' => array('b' => array('c' => 'test')));
echo '
';
var_dump($array);
echo '
';
if (isset($array['a']['b']['c']['something'])) {
    echo 'yahoo';
}

Body:
You'd want to use is_array($array['a']['b']['c']) rather than isset($array['a']['b']['c']['something']) in this case, or maybe a crafty combination of the two to make sure you don't get any errors if it's not set when you're checking to see if it's an array.

Something like:

if(isset($array['a']['b']['c']['something']) && is_array($array['a']['b']['c'])){ [...] }


问:
Implicit conversion in wrapper class
I have confusion in Number Wrapper Class in Java.

These two assignments look symmetric - a char is assigned to Integer, and an int is assigned to Character. However, the first assignment

```<code>Integer i = 'a';
</code>```

gives Compilation Error, while the second assignment

```<code>Character ch2 = 97;
</code>```

is allowed. Why?

答:
Although int i = 'a' works fine, converting the same to Integer is not allowed, because it requires a boxing conversion.

Java's boxing conversion is defined only for eight cases:

From type boolean to type Boolean

From type byte to type Byte

From type short to type Short

From type char to type Character

From type int to type Integer

From type long to type Long

From type float to type Float

From type double to type Double

Since 'a' is a char literal, Java does not allow conversion from char to Integer: a character literal is always of type char.

However, when you write

```<code>Character ch2 = 97;
</code>```

Java compiler sees that 97 is in the valid range for char (i.e. 0..65535), so it treats 97 as char, not int, and allows the boxing conversion. Trying the same with an out-of-range constant produces an error:

```<code>Character ch3 = 65536; // error: incompatible types: int cannot be converted to Character
</code>```

Title: Implicit conversion in wrapper class

Body:
I have confusion in Number Wrapper Class in Java.

These two assignments look symmetric - a char is assigned to Integer, and an int is assigned to Character. However, the first assignment

Integer i = 'a';

gives Compilation Error, while the second assignment

Character ch2 = 97;

is allowed. Why?

Body:
Although int i = 'a' works fine, converting the same to Integer is not allowed, because it requires a boxing conversion.

Java's boxing conversion is defined only for eight cases:

From type boolean to type Boolean

From type byte to type Byte

From type short to type Short

From type char to type Character

From type int to type Integer

From type long to type Long

From type float to type Float

From type double to type Double

Since 'a' is a char literal, Java does not allow conversion from char to Integer: a character literal is always of type char.

However, when you write

Character ch2 = 97;

Java compiler sees that 97 is in the valid range for char (i.e. 0..65535), so it treats 97 as char, not int, and allows the boxing conversion. Trying the same with an out-of-range constant produces an error:

Character ch3 = 65536; // error: incompatible types: int cannot be converted to Character


问:
Linking IF/OR statement
I have a drop down list cell, I want to create a value in a different cell such that if X in Cell 1 then A in Cell 2 OR if Y in Cell 1 then B in Cell 2 otherwise perform a different function. I think something along the lines of:

=IF(OR(A1="X", 1...

just not sure where to go from there

答:
What yo are describing is a nested if not OR:

```<code>=IF(A1="X","A",IF(A1 = "Y","B","different function"))
</code>```

Title: Linking IF/OR statement

Body:
What yo are describing is a nested if not OR:

=IF(A1="X","A",IF(A1 = "Y","B","different function"))


问:
WebClient UploadString get header and body when receive 400 bad request
I'm making an API call using WebClient.UploadString(). It throws an exception since it's a bad request. I cannot find more information in the exception object or the webclient object itself. But if I use Fiddler to listen to the request, it's giving me all details of the headers and body information, so I know exactly the reason. Is there a way to retrieve these info from UploadString()? or should I use some other method like HttpRequest to get the detail? Thanks!</p>

答:
You can use HttpWebRequest.GetResponse() Method from System.Net namespace.

You can find an example in the official msdn doc:
https://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.getresponse%28v=vs.110%29.aspx

Also: You can capture exception (from try-catch of the Request of UploadString) and get the exception stack by rethrowing the exception if you get any additional errors.

```<code>catch (Exception ex) { String.Format("Error occurred {0} - {1}",ex.Message,ex.ToString()); throw; }
</code>```

You need to log the exception first before you re-throw it to get the according info. If you don't use logging you don't need to re-throw.

Note: You can also view site requests and headers sent using the chrome://net-internals chrome page at the "events" menu.

Body:
You can use HttpWebRequest.GetResponse() Method from System.Net namespace.

You can find an example in the official msdn doc:
https://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.getresponse%28v=vs.110%29.aspx

Also: You can capture exception (from try-catch of the Request of UploadString) and get the exception stack by rethrowing the exception if you get any additional errors.

catch (Exception ex) { String.Format("Error occurred {0} - {1}",ex.Message,ex.ToString()); throw; }

You need to log the exception first before you re-throw it to get the according info. If you don't use logging you don't need to re-throw.

Note: You can also view site requests and headers sent using the chrome://net-internals chrome page at the "events" menu.


问:
Laravel / VirtualBox / Mac permissions error
I am running debian on my virtualbox on my Macbook Pro.

When building my Laravel application - I have set my permissions locally to be 777 on public, storage and bootstrap.

Every time I logout / in I then get another permissions error:

My mount permissions are:

```<code>sudo mount -t vboxsf -o auto,exec,rw,uid=1000,gid=33 BASE ./BASE
</code>```

Can anyone advise what I need to do to fix this? I've tried sticky bit, but no joy.

Thanks

答:
try with

```<code>./artisan cache:clear
</code>```

after the recursive chmod command was inserted

Body:
I am running debian on my virtualbox on my Macbook Pro.

When building my Laravel application - I have set my permissions locally to be 777 on public, storage and bootstrap.

Every time I logout / in I then get another permissions error:

My mount permissions are:

sudo mount -t vboxsf -o auto,exec,rw,uid=1000,gid=33 BASE ./BASE

Can anyone advise what I need to do to fix this? I've tried sticky bit, but no joy.

Thanks

Body:
try with

./artisan cache:clear

after the recursive chmod command was inserted


问:
MongoDB - Sharding migrateThread long running since 3 hours
MongoDB Version: 3.0.8
Engine: WiredTiger

The Balancer is too slow to migrate ~30MB chucks, Due to that we observed long running queries, that's stating that its been running more than 3 hours. Please suggest me.

Attached the long running output from db.currentOp().
Thank You,
Albert

```<code>------ Long Running Query ----

{
    "desc" : "migrateThread",
    "threadId" : "0x95d26a000",
    "opid" : "u001b_s2_rs:-1345098410",
    "active" : true,
    "secs_running" : 9360,
    "microsecs_running" : NumberLong("9360370895"),
    "op" : "none",
    "ns" : "deviceStateEvent.deviceStateEvent",
    "query" : {

    },
    "msg" : "step 2 of 5",
    "numYields" : 0,
    "locks" : {

    },
    "waitingForLock" : false,
    "lockStats" : {
        "Global" : {
            "acquireCount" : {
                "r" : NumberLong(126582),
                "w" : NumberLong(126580)
            }
        },
        "Database" : {
            "acquireCount" : {
                "r" : NumberLong(1),
                "w" : NumberLong(126579),
                "W" : NumberLong(1)
            }
        },
        "Collection" : {
            "acquireCount" : {
                "r" : NumberLong(1),
                "w" : NumberLong(63290),
                "W" : NumberLong(1)
            }
        },
        "oplog" : {
            "acquireCount" : {
                "w" : NumberLong(63288)
            }
        }
    }
}

{
    "desc" : "conn514744",
    "threadId" : "0x4423e3400",
    "connectionId" : 514744,
    "opid" : "u001b_s0_rs:2109828171",
    "active" : true,
    "secs_running" : 9360,
    "microsecs_running" : NumberLong("9360954810"),
    "op" : "query",
    "ns" : "deviceStateEvent.deviceStateEvent",
    "query" : {
        "$msg" : "query not recording (too large)"
    },
    "client_s" : "10.99.8.121:45784",
    "msg" : "step 3 of 6",
    "numYields" : 1063,
    "locks" : {

    },
    "waitingForLock" : false,
    "lockStats" : {
        "Global" : {
            "acquireCount" : {
                "r" : NumberLong(2130),
                "w" : NumberLong(1),
                "R" : NumberLong(1)
            }
        },
        "Database" : {
            "acquireCount" : {
                "r" : NumberLong(1064),
                "w" : NumberLong(1)
            }
        },
        "Collection" : {
            "acquireCount" : {
                "r" : NumberLong(1064),
                "W" : NumberLong(1)
            }
        }
    }

------- Balancer Error -----------

balancer:
        Currently enabled:  no
        Currently running:  no
        Failed balancer rounds in last 5 attempts:  0
        Migration Results for the last 24 hours:
                116 : Success
                1 : Failed with error 'chunk too big to move', from u001b_s4_rs to u001b_s3_rs
                9 : Failed with error 'moveChunk failed to engage TO-shard in the data transfer: can't accept new chunks because  there are still 7 deletes from previous migration', from u001b_s2_rs to u001b_s4_rs
                402 : Failed with error 'data transfer error', from u001b_s0_rs to u001b_s3_rs
                322 : Failed with error 'moveChunk failed to engage TO-shard in the data transfer: can't accept new chunks because  there are still 6 deletes from previous migration', from u001b_s2_rs to u001b_s4_rs
                8 : Failed with error 'moveChunk failed to engage TO-shard in the data transfer: can't accept new chunks because  there are still 7 deletes from previous migration', from u001b_s0_rs to u001b_s4_rs
                6 : Failed with error 'moveChunk failed to engage TO-shard in the data transfer: can't accept new chunks because  there are still 8 deletes from previous migration', from u001b_s0_rs to u001b_s4_rs
                1 : Failed with error 'moveChunk failed to engage TO-shard in the data transfer: can't accept new chunks because  there are still 8 deletes from previous migration', from u001b_s1_rs to u001b_s4_rs
                1 : Failed with error 'chunk too big to move', from u001b_s4_rs to u001b_s1_rs
                2 : Failed with error 'moveChunk failed to engage TO-shard in the data transfer: can't accept new chunks because  there are still 7 deletes from previous migration', from u001b_s1_rs to u001b_s4_rs
                387 : Failed with error 'moveChunk failed to engage TO-shard in the data transfer: can't accept new chunks because  there are still 6 deletes from previous migration', from u001b_s0_rs to u001b_s4_rs
                35 : Failed with error 'moveChunk failed to engage TO-shard in the data transfer: can't accept new chunks because  there are still 2 deletes from previous migration', from u001b_s0_rs to u001b_s2_rs
                15 : Failed with error 'chunk too big to move', from u001b_s0_rs to u001b_s3_rs
                2 : Failed with error 'chunk too big to move', from u001b_s0_rs to u001b_s2_rs
                192 : Failed with error 'moveChunk failed to engage TO-shard in the data transfer: can't accept new chunks because  there are still 6 deletes from previous migration', from u001b_s1_rs to u001b_s4_rs
                23 : Failed with error 'chunk too big to move', from u001b_s0_rs to u001b_s1_rs
                5 : Failed with error 'moveChunk failed to engage TO-shard in the data transfer: can't accept new chunks because  there are still 8 deletes from previous migration', from u001b_s2_rs to u001b_s4_rs
                77 : Failed with error 'moveChunk failed to engage TO-shard in the data transfer: can't accept new chunks because  there are still 1 deletes from previous migration', from u001b_s0_rs to u001b_s2_rs
</code>```

答:
There are some deletes are remaining so it isn't accepting new chunks.

First you need to enable you balancer :
   Go to mongos and run sh.setBalancerState(true)

This might work for you

Go to shard : u001b_s4_rs

go to mongo console and step down your primary node.

rs.stepDown()

and check status again.

Body:
MongoDB Version: 3.0.8
Engine: WiredTiger

The Balancer is too slow to migrate ~30MB chucks, Due to that we observed long running queries, that's stating that its been running more than 3 hours. Please suggest me.

Attached the long running output from db.currentOp().
Thank You,
Albert

------ Long Running Query ----

{
    "desc" : "migrateThread",
    "threadId" : "0x95d26a000",
    "opid" : "u001b_s2_rs:-1345098410",
    "active" : true,
    "secs_running" : 9360,
    "microsecs_running" : NumberLong("9360370895"),
    "op" : "none",
    "ns" : "deviceStateEvent.deviceStateEvent",
    "query" : {

    },
    "msg" : "step 2 of 5",
    "numYields" : 0,
    "locks" : {

    },
    "waitingForLock" : false,
    "lockStats" : {
        "Global" : {
            "acquireCount" : {
                "r" : NumberLong(126582),
                "w" : NumberLong(126580)
            }
        },
        "Database" : {
            "acquireCount" : {
                "r" : NumberLong(1),
                "w" : NumberLong(126579),
                "W" : NumberLong(1)
            }
        },
        "Collection" : {
            "acquireCount" : {
                "r" : NumberLong(1),
                "w" : NumberLong(63290),
                "W" : NumberLong(1)
            }
        },
        "oplog" : {
            "acquireCount" : {
                "w" : NumberLong(63288)
            }
        }
    }
}

{
    "desc" : "conn514744",
    "threadId" : "0x4423e3400",
    "connectionId" : 514744,
    "opid" : "u001b_s0_rs:2109828171",
    "active" : true,
    "secs_running" : 9360,
    "microsecs_running" : NumberLong("9360954810"),
    "op" : "query",
    "ns" : "deviceStateEvent.deviceStateEvent",
    "query" : {
        "$msg" : "query not recording (too large)"
    },
    "client_s" : "10.99.8.121:45784",
    "msg" : "step 3 of 6",
    "numYields" : 1063,
    "locks" : {

    },
    "waitingForLock" : false,
    "lockStats" : {
        "Global" : {
            "acquireCount" : {
                "r" : NumberLong(2130),
                "w" : NumberLong(1),
                "R" : NumberLong(1)
            }
        },
        "Database" : {
            "acquireCount" : {
                "r" : NumberLong(1064),
                "w" : NumberLong(1)
            }
        },
        "Collection" : {
            "acquireCount" : {
                "r" : NumberLong(1064),
                "W" : NumberLong(1)
            }
        }
    }

------- Balancer Error -----------

balancer:
        Currently enabled:  no
        Currently running:  no
        Failed balancer rounds in last 5 attempts:  0
        Migration Results for the last 24 hours:
                116 : Success
                1 : Failed with error 'chunk too big to move', from u001b_s4_rs to u001b_s3_rs
                9 : Failed with error 'moveChunk failed to engage TO-shard in the data transfer: can't accept new chunks because  there are still 7 deletes from previous migration', from u001b_s2_rs to u001b_s4_rs
                402 : Failed with error 'data transfer error', from u001b_s0_rs to u001b_s3_rs
                322 : Failed with error 'moveChunk failed to engage TO-shard in the data transfer: can't accept new chunks because  there are still 6 deletes from previous migration', from u001b_s2_rs to u001b_s4_rs
                8 : Failed with error 'moveChunk failed to engage TO-shard in the data transfer: can't accept new chunks because  there are still 7 deletes from previous migration', from u001b_s0_rs to u001b_s4_rs
                6 : Failed with error 'moveChunk failed to engage TO-shard in the data transfer: can't accept new chunks because  there are still 8 deletes from previous migration', from u001b_s0_rs to u001b_s4_rs
                1 : Failed with error 'moveChunk failed to engage TO-shard in the data transfer: can't accept new chunks because  there are still 8 deletes from previous migration', from u001b_s1_rs to u001b_s4_rs
                1 : Failed with error 'chunk too big to move', from u001b_s4_rs to u001b_s1_rs
                2 : Failed with error 'moveChunk failed to engage TO-shard in the data transfer: can't accept new chunks because  there are still 7 deletes from previous migration', from u001b_s1_rs to u001b_s4_rs
                387 : Failed with error 'moveChunk failed to engage TO-shard in the data transfer: can't accept new chunks because  there are still 6 deletes from previous migration', from u001b_s0_rs to u001b_s4_rs
                35 : Failed with error 'moveChunk failed to engage TO-shard in the data transfer: can't accept new chunks because  there are still 2 deletes from previous migration', from u001b_s0_rs to u001b_s2_rs
                15 : Failed with error 'chunk too big to move', from u001b_s0_rs to u001b_s3_rs
                2 : Failed with error 'chunk too big to move', from u001b_s0_rs to u001b_s2_rs
                192 : Failed with error 'moveChunk failed to engage TO-shard in the data transfer: can't accept new chunks because  there are still 6 deletes from previous migration', from u001b_s1_rs to u001b_s4_rs
                23 : Failed with error 'chunk too big to move', from u001b_s0_rs to u001b_s1_rs
                5 : Failed with error 'moveChunk failed to engage TO-shard in the data transfer: can't accept new chunks because  there are still 8 deletes from previous migration', from u001b_s2_rs to u001b_s4_rs
                77 : Failed with error 'moveChunk failed to engage TO-shard in the data transfer: can't accept new chunks because  there are still 1 deletes from previous migration', from u001b_s0_rs to u001b_s2_rs


问:
JQUERY pass value from link and return it or forward it
I am trying to:

click on the link shown below and have the value passed to an JQUERY $.get (I think it has to be done like that) and this should be made available to a SQL snippet which will include it its WHERE clause.

LINK

```<code>$sOutput .= '"<a href=\"#whatever?' .addslashes($aRow['id_cruise']) .'\" class=\"flip\">'.addslashes($aRow['from_country']).'</a>",';
</code>```

When I click on the link, you see that Flip class. That does open alright a slide pannel within which I have a div that would be populated after a SQL query works with the value sent:

JQUERY SNIPPET

```<code><script type="text/javascript">
$(document).ready(function(){
$('a.flip').live('click',function(){
    $(".panel").slideToggle("slow");

  });
});
</script>
</code>```

As you can see, it uses the LIVE function so that up on clicking indeed activates the slide pannel open. But I need that last bit more, the one that sends the value (of id_cruise). When I hover down the rows, I can see that the value of ID changes, which is great, but however I am not getting to make it passed to the snippet and picked up by the SQL query.

So I can see that in the link, where I write "whatever", indeed it doesnt matter, as long as it has the # sign. Note that the Link is part of the server processing file, whilst the JQUERY is on the user visible page file, they are in two different pages.

UPDATED FROM HERE, INCLUDING NOW THE CODE FROM JEFF:

The link looks so now:

```<code>$sOutput .= '"<a href=\"#id?' .addslashes($aRow['id_cruise']) .'\" class=\"flip\">'.addslashes($aRow['from_country']).'</a>",';
</code>```

Jeff wisely indicated how there should be a third file which would get the parameter from the second JQUERY snippet, return it and this second would pass it to a third one located just below. This third snippet is the one that forwards it to the DIV box located inside the slide panel.

```<code><script type="text/javascript">

$(document).ready(function(){
$('a.flip').live('click',function(){
$(".panel").slideToggle("slow");
      DoSomethingWith(this.id);

     });

});
</script>

 <script type="text/javascript">

function DoSomethingWith(id) {
  $.get("SendIdToDatabase.php", {idCruise: id}, AnotherFunction);
}
function AnotherFunction(str) {
  $("#reviews").html(str);
}
</script>
</code>```

OTHER CONTRIBUTOR SAID THAT IT COULD BE MERGED AND SIMPLIFIED INTO THIS:

```<code>$(function() {
      $('a.flip').live('click',function() {
            $('.panel').slideToggle(slow');
            $('#reviews').load('SendIdToDatabase.php', {idCruise: this.id});
      });
});
</code>```

SO NOW I CREATE THE PHP CODE (SendIdToDatabase.php) THAT WILL HANDLE THE SQL REQUEST

```<code> <?php

$id_crucero = $_REQUEST['id_cruise']; //this is what I (hopefully) should get from the page
              require ('mysqli_connect.php');

                    $sql ="SELECT description
                        FROM cruises
                        WHERE id_cruise
                        = '".$id_crucero."'";

                        $result = @mysql_query ($sql);

                    while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {

                    $reviews = ($row['description']);
                    echo "$reviews";
                    }

                      ?>
</code>```

AND FROM HERE IT SHOULD ECHO IT TO THE SECOND AJAX CODE SNIPPET WHICH FORWARDS IT TO THE PANEL (WHICH I HAVE RENAMED TO "REVIEWS" AND IT IS A DIV, NOT AN HTML)

BUT SOME LINK MUST BE BUGGY AS AT SOME POINT THE VALUE IS NOT PASSED OR RECEIVED.

AS OF 1 DECEMBER THE VALUE IS STILL NOT PASSED ON. I HARDCODED SOME TEXT IN THE PHP SCRIPT AND YES, THAT IS SHOWN IN THE DIV BOX INSIDE THE PANEL BUT IT DOES NOT SHOW THE VALUE

答:
I believe what you are looking for is the "this" object. Within the "this" object, you can get the id property. For example:

```<code><script type="text/javascript">
$(document).ready(function(){
$('a.flip').live('click',function(){
    $(".panel").slideToggle("slow");
    DoSomethingWith(this.id);
  });
});
</script>
</code>```

Once you have the id, you can then pass it to another script with Ajax for processing:
For Example:

```<code><script type="text/javascript">
function DoSomethingWith(id) {
  $.get("SendIdToDatabase.php", {idCruise: id}, AnotherFunction);
}
function AnotherFunction(str) {
  $(".panel").html(str);
}
</script>
</code>```

Check out jQuery Get for documentation on sending "get" Ajax calls.

You would need to write the php script (SendIdToDatabase.php) to do whatever you wanted with the id. Don't forget to remove the #Whatever, from the id before using it.

As for why it needs to be a separate script, you need to understand the "disconnected" nature of http requests. Here are some decent explanations and diagrams.

Body:
I am trying to:

click on the link shown below and have the value passed to an JQUERY $.get (I think it has to be done like that) and this should be made available to a SQL snippet which will include it its WHERE clause.

LINK

$sOutput .= '"'.addslashes($aRow['from_country']).'",';

When I click on the link, you see that Flip class. That does open alright a slide pannel within which I have a div that would be populated after a SQL query works with the value sent:

JQUERY SNIPPET

As you can see, it uses the LIVE function so that up on clicking indeed activates the slide pannel open. But I need that last bit more, the one that sends the value (of id_cruise). When I hover down the rows, I can see that the value of ID changes, which is great, but however I am not getting to make it passed to the snippet and picked up by the SQL query.

So I can see that in the link, where I write "whatever", indeed it doesnt matter, as long as it has the # sign. Note that the Link is part of the server processing file, whilst the JQUERY is on the user visible page file, they are in two different pages.

UPDATED FROM HERE, INCLUDING NOW THE CODE FROM JEFF:

The link looks so now:

$sOutput .= '"'.addslashes($aRow['from_country']).'",';

Jeff wisely indicated how there should be a third file which would get the parameter from the second JQUERY snippet, return it and this second would pass it to a third one located just below. This third snippet is the one that forwards it to the DIV box located inside the slide panel.

OTHER CONTRIBUTOR SAID THAT IT COULD BE MERGED AND SIMPLIFIED INTO THIS:

$(function() {
      $('a.flip').live('click',function() {
            $('.panel').slideToggle(slow');
            $('#reviews').load('SendIdToDatabase.php', {idCruise: this.id});
      });
});

SO NOW I CREATE THE PHP CODE (SendIdToDatabase.php) THAT WILL HANDLE THE SQL REQUEST

 <?php

$id_crucero = $_REQUEST['id_cruise']; //this is what I (hopefully) should get from the page
              require ('mysqli_connect.php');

                    $sql ="SELECT description
                        FROM cruises
                        WHERE id_cruise
                        = '".$id_crucero."'";

                        $result = @mysql_query ($sql);

                    while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {

                    $reviews = ($row['description']);
                    echo "$reviews";
                    }

                      ?>

AND FROM HERE IT SHOULD ECHO IT TO THE SECOND AJAX CODE SNIPPET WHICH FORWARDS IT TO THE PANEL (WHICH I HAVE RENAMED TO "REVIEWS" AND IT IS A DIV, NOT AN HTML)

BUT SOME LINK MUST BE BUGGY AS AT SOME POINT THE VALUE IS NOT PASSED OR RECEIVED.

AS OF 1 DECEMBER THE VALUE IS STILL NOT PASSED ON. I HARDCODED SOME TEXT IN THE PHP SCRIPT AND YES, THAT IS SHOWN IN THE DIV BOX INSIDE THE PANEL BUT IT DOES NOT SHOW THE VALUE

Body:
I believe what you are looking for is the "this" object. Within the "this" object, you can get the id property. For example:

<script type="text/javascript">
$(document).ready(function(){
$('a.flip').live('click',function(){
    $(".panel").slideToggle("slow");
    DoSomethingWith(this.id);
  });
});
</script>

Once you have the id, you can then pass it to another script with Ajax for processing:
For Example:

<script type="text/javascript">
function DoSomethingWith(id) {
  $.get("SendIdToDatabase.php", {idCruise: id}, AnotherFunction);
}
function AnotherFunction(str) {
  $(".panel").html(str);
}
</script>

Check out jQuery Get for documentation on sending "get" Ajax calls.

You would need to write the php script (SendIdToDatabase.php) to do whatever you wanted with the id. Don't forget to remove the #Whatever, from the id before using it.

As for why it needs to be a separate script, you need to understand the "disconnected" nature of http requests. Here are some decent explanations and diagrams.