问:
SQL-Statement provides unexpected result
I've the following table (mTable)

```<code>id  | sent                  | number
---------------------------------------
23  | 2017-03-02 00:00:00   | 0
23  | 2017-03-04 00:00:00   | 0
45  | 2017-03-15 00:00:00   | 1.8
45  | 2017-03-17 00:00:00   | 1.9

id: integer, not unique, no primary key
sent: timestamp
number: float
</code>```

The SQL-Statement:

```<code>SELECT DISTINCT `id`, number as mynum, MAX(`sent`) AS sentOn FROM `mTable` GROUP BY `id`
</code>```

The result is:

```<code>id  | mynum  |  sentOn
------------------------------------
23  | 0      | 2017-03-04 00:00:00
45  | 1.8    | 2017-03-17 00:00:00
</code>```

The expected result would be:

```<code>id  | mynum  |  sentOn
------------------------------------
23  | 0      | 2017-03-04 00:00:00
45  | 1.9    | 2017-03-17 00:00:00
</code>```

In the second row I would expect to be the mynum(1.9) with the latest sent date(2017-03-17 00:00:00).
Instead the SQL-Query provides the mynum(1.8) from the second latest send date(2017-03-15 00:00:00).

Any hints, to solve the problem?
Thank's

答:
Aggregation is the wrong way to get the most recent value.  Here is a more appropriate way:</p>

```<code>select m.*
from mtable m
where m.sent = (select max(m2.sent) from mtable m2 where m.id = m2.id);
</code>```

Body:
I've the following table (mTable)

id  | sent                  | number
---------------------------------------
23  | 2017-03-02 00:00:00   | 0
23  | 2017-03-04 00:00:00   | 0
45  | 2017-03-15 00:00:00   | 1.8
45  | 2017-03-17 00:00:00   | 1.9

id: integer, not unique, no primary key
sent: timestamp
number: float

The SQL-Statement:

SELECT DISTINCT `id`, number as mynum, MAX(`sent`) AS sentOn FROM `mTable` GROUP BY `id`

The result is:

id  | mynum  |  sentOn
------------------------------------
23  | 0      | 2017-03-04 00:00:00
45  | 1.8    | 2017-03-17 00:00:00

The expected result would be:

id  | mynum  |  sentOn
------------------------------------
23  | 0      | 2017-03-04 00:00:00
45  | 1.9    | 2017-03-17 00:00:00

In the second row I would expect to be the mynum(1.9) with the latest sent date(2017-03-17 00:00:00).
Instead the SQL-Query provides the mynum(1.8) from the second latest send date(2017-03-15 00:00:00).

Any hints, to solve the problem?
Thank's

Body:
Aggregation is the wrong way to get the most recent value.  Here is a more appropriate way:

select m.*
from mtable m
where m.sent = (select max(m2.sent) from mtable m2 where m.id = m2.id);


来源: stackexchange

问:
Add each character from each line of a text file, to a list in Python
So I want to read each character (separated by spaces) of each line of a text file and add them to a seperate index of a list for each line.

```<code>file = open("theTextFile.txt", 'r+')
pal = []

words = file.split(' ')
pal.append(words)

print(pal)
split_line(file)
</code>```

The text file has a single character separated by a space for each line.
The editor wouldn't allow for my punctuation from the text file, but below is an example of what it looks like.

r o t o r

r a c e c

答:
Maybe you want like this?</p>

```<code>words = []
with open('theTextFile.txt', 'r') as fp:
    words = sum([l.strip().split(' ') for l in fp], [])
print(words)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
So I want to read each character (separated by spaces) of each line of a text file and add them to a seperate index of a list for each line.

file = open("theTextFile.txt", 'r+')
pal = []

words = file.split(' ')
pal.append(words)

print(pal)
split_line(file)

The text file has a single character separated by a space for each line.
The editor wouldn't allow for my punctuation from the text file, but below is an example of what it looks like.

r o t o r

r a c e c

Body:
Maybe you want like this?

words = []
with open('theTextFile.txt', 'r') as fp:
    words = sum([l.strip().split(' ') for l in fp], [])
print(words)


问:
Button fill div height using Bootstrap
I want my div col-md-9 to have a height the same as the content in my first div col-md-3's contents.

I also want my div col-md-9's button inside to be the same height as the col-md-3's content.

I'd like the text on the button to fill the button also.

How do I accomplish this?

```<code><div class="row" style="height:300px;">
    <div class="col-md-3">
        <div class="thumbnail">
            <a href="@(Url.Content("~/ProjectTimer/LITL.DesktopTimer.application"))">
                <img src="@(Url.Content("~/Images/LIJayCow-135.png"))" alt="Download Timer App" />
            </a>

            <div class="caption">
                <p>Run the Timer App on your computer to keep track of your time.</p>
                <a class="btn btn-primary" href="@(Url.Content("~/ProjectTimer/LITL.DesktopTimer.application"))">
                    <span class="glyphicon glyphicon-download"></span> Download
                </a>
            </div>
        </div>
    </div>
    <div class="col-md-9" style="height:300px; background: #f0e68c">

        <div class="thumbnail" style="width:100%; height:300px">
            <a class="btn btn-block btn-primary" style="display: block; width: 100%; height:100%; font-size:large" href="@(Url.Content("~/ProjectTimer/LITL.DesktopTimer.application"))">
                <span class="glyphicon glyphicon-share"> LIRA</span>
            </a>
        </div>
    </div>
</div>
</code>```

答:
Just use the btn-block class, like this:

```<code><div class="col-md-3"><button class="btn btn-block" >Show Details</button></div>
</code>```

Title: Button fill div height using Bootstrap

Body:
I want my div col-md-9 to have a height the same as the content in my first div col-md-3's contents.

I also want my div col-md-9's button inside to be the same height as the col-md-3's content.

I'd like the text on the button to fill the button also.

How do I accomplish this?

Run the Timer App on your computer to keep track of your time.

                     Download

                 LIRA

Body:
Just use the btn-block class, like this:

<div class="col-md-3"><button class="btn btn-block" >Show Details</button></div>


问:
Serializing FileInfo Objects to XML in C#
I am trying to serialize an IEnumerable<FileInfo> into xml. I have researched and found that because the FileInfo class does not have a parameterless constructor, it cannot be serialized as it is, and i should use a wrapper class.

For simplicity, the code im using to serialize is in the click event of a winforms button as shown. Ill refactor this once its working:

```<code>    private void button1_Click(object sender, System.EventArgs e)
    {
        IEnumerable<FileInfo> allfiles = FileGetter.FileInfoAllFiles();

        FileList filelist = new FileList();

        foreach (var file in allfiles)
        {
            filelist.Add(new FileInfoSerializable(file));
        }

        var stream = new FileStream("Xmllist.xml", FileMode.Create);
        new XmlSerializer(typeof(FileInfoSerializable)).Serialize(stream, filelist);

    }
</code>```

The wrapper class:

```<code>[Serializable]
public class FileInfoSerializable
{

    private readonly FileInfo _fileInfo;

    #region ~~~ Constructors ~~~

    public FileInfoSerializable() { }

    public FileInfoSerializable(FileInfo FileInfo) { _fileInfo = FileInfo; }

    #endregion

    #region ~~~ Properties ~~~

    public string Name { get { return _fileInfo.Name; } set { } }

    public string FullName { get { return _fileInfo.FullName; } set { } }

    public long Length { get { return _fileInfo.Length; } set { } }

    public string Extension { get { return _fileInfo.Extension; } set { } }

    public DateTime LastWriteTime { get { return _fileInfo.LastWriteTime; } set { } }

    public string DirectoryName { get { return _fileInfo.DirectoryName; } set { } }

    #endregion
}
</code>```

I want to add each FileInfo object in the IEnumerable<FileInfo> to a collection, which i will then serialize.This is the class that holds the collection:

```<code>[Serializable]
public class FileList
{
    public List<FileInfoSerializable> filez { get; set; }

    public FileList()
    {
        filez = new List<FileInfoSerializable>();
    }

    public void Add(FileInfoSerializable m)
    {
        filez.Add(m);
    }
}
</code>```

THE PROBLEM

Im getting the following exception at the line: new XmlSerializer(typeof(FileInfoSerializable)).Serialize(stream, filelist);

I have tried casting to a generic list, using filelist.filez in place of filelist but still getting the same error. What do i need to change to make this work?

cheers

答:
I finally found issue.  typeof(FileInfoSerializable) should be typeof(FileList).  The code below works. FileInfoSerializable was creating an array at the root level of the xml.  The root of the xml must be singular.</p>

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;

namespace ConsoleApplication49
{
    class Program
    {

        static void Main(string[] args)
        {
            List<FileInfo> allfiles = Directory.GetFiles(@"c:\temp").Select(x => new FileInfo(x)).ToList();

            FileList filelist = new FileList();

            foreach (var file in allfiles)
            {
                filelist.Add(new FileInfoSerializable(file));
            }

            var stream = new FileStream("c:\\temp\\Xmllist.xml", FileMode.Create);

            XmlSerializer serializer = new XmlSerializer(typeof(FileList));

            serializer.Serialize(stream, filelist);

        }
    }
    [Serializable]
    public class FileInfoSerializable
    {

        private readonly FileInfo _fileInfo;

        #region ~~~ Constructors ~~~

        public FileInfoSerializable() { }

        public FileInfoSerializable(FileInfo FileInfo) { _fileInfo = FileInfo; }

        #endregion

        #region ~~~ Properties ~~~

        public string Name { get { return _fileInfo.Name; } set { } }

        public string FullName { get { return _fileInfo.FullName; } set { } }

        public long Length { get { return _fileInfo.Length; } set { } }

        public string Extension { get { return _fileInfo.Extension; } set { } }

        public DateTime LastWriteTime { get { return _fileInfo.LastWriteTime; } set { } }

        public string DirectoryName { get { return _fileInfo.DirectoryName; } set { } }

        #endregion
    }

    [Serializable]
    public class FileList
    {
        public List<FileInfoSerializable> filez { get; set; }

        public FileList()
        {
            filez = new List<FileInfoSerializable>();
        }

        public void Add(FileInfoSerializable m)
        {
            filez.Add(m);
        }
    }
}
</code>```

Body:
I am trying to serialize an IEnumerable<FileInfo> into xml. I have researched and found that because the FileInfo class does not have a parameterless constructor, it cannot be serialized as it is, and i should use a wrapper class.

For simplicity, the code im using to serialize is in the click event of a winforms button as shown. Ill refactor this once its working:

    private void button1_Click(object sender, System.EventArgs e)
    {
        IEnumerable<FileInfo> allfiles = FileGetter.FileInfoAllFiles();

        FileList filelist = new FileList();

        foreach (var file in allfiles)
        {
            filelist.Add(new FileInfoSerializable(file));
        }

        var stream = new FileStream("Xmllist.xml", FileMode.Create);
        new XmlSerializer(typeof(FileInfoSerializable)).Serialize(stream, filelist);

    }

The wrapper class:

[Serializable]
public class FileInfoSerializable
{

    private readonly FileInfo _fileInfo;

    #region ~~~ Constructors ~~~

    public FileInfoSerializable() { }

    public FileInfoSerializable(FileInfo FileInfo) { _fileInfo = FileInfo; }

    #endregion

    #region ~~~ Properties ~~~

    public string Name { get { return _fileInfo.Name; } set { } }

    public string FullName { get { return _fileInfo.FullName; } set { } }

    public long Length { get { return _fileInfo.Length; } set { } }

    public string Extension { get { return _fileInfo.Extension; } set { } }

    public DateTime LastWriteTime { get { return _fileInfo.LastWriteTime; } set { } }

    public string DirectoryName { get { return _fileInfo.DirectoryName; } set { } }

    #endregion
}

I want to add each FileInfo object in the IEnumerable<FileInfo> to a collection, which i will then serialize.This is the class that holds the collection:

[Serializable]
public class FileList
{
    public List<FileInfoSerializable> filez { get; set; }

    public FileList()
    {
        filez = new List<FileInfoSerializable>();
    }

    public void Add(FileInfoSerializable m)
    {
        filez.Add(m);
    }
}

THE PROBLEM

Im getting the following exception at the line: new XmlSerializer(typeof(FileInfoSerializable)).Serialize(stream, filelist);

I have tried casting to a generic list, using filelist.filez in place of filelist but still getting the same error. What do i need to change to make this work?

cheers

Body:
I finally found issue.  typeof(FileInfoSerializable) should be typeof(FileList).  The code below works. FileInfoSerializable was creating an array at the root level of the xml.  The root of the xml must be singular.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;

namespace ConsoleApplication49
{
    class Program
    {

        static void Main(string[] args)
        {
            List<FileInfo> allfiles = Directory.GetFiles(@"c:\temp").Select(x => new FileInfo(x)).ToList();

            FileList filelist = new FileList();

            foreach (var file in allfiles)
            {
                filelist.Add(new FileInfoSerializable(file));
            }

            var stream = new FileStream("c:\\temp\\Xmllist.xml", FileMode.Create);

            XmlSerializer serializer = new XmlSerializer(typeof(FileList));

            serializer.Serialize(stream, filelist);

        }
    }
    [Serializable]
    public class FileInfoSerializable
    {

        private readonly FileInfo _fileInfo;

        #region ~~~ Constructors ~~~

        public FileInfoSerializable() { }

        public FileInfoSerializable(FileInfo FileInfo) { _fileInfo = FileInfo; }

        #endregion

        #region ~~~ Properties ~~~

        public string Name { get { return _fileInfo.Name; } set { } }

        public string FullName { get { return _fileInfo.FullName; } set { } }

        public long Length { get { return _fileInfo.Length; } set { } }

        public string Extension { get { return _fileInfo.Extension; } set { } }

        public DateTime LastWriteTime { get { return _fileInfo.LastWriteTime; } set { } }

        public string DirectoryName { get { return _fileInfo.DirectoryName; } set { } }

        #endregion
    }

    [Serializable]
    public class FileList
    {
        public List<FileInfoSerializable> filez { get; set; }

        public FileList()
        {
            filez = new List<FileInfoSerializable>();
        }

        public void Add(FileInfoSerializable m)
        {
            filez.Add(m);
        }
    }
}


问:
Deleting running files
When I used the latest version of McAfee Antivirus, I noticed that the shred feature can delete running files and then asks you to restart your computer. Do anyone know how does it delete running files without closing them?</p>

答:
It may depend on the OS and file system types. On Linux and Unix like, deleting a file a just removing an entry from a folder. The file is actually deleted on last close if no folder entry points to it. So you can safely delete a file even if it is opened in another process.

On Windows the MSDN says:

The DeleteFile function fails if an application attempts to delete a file that has other handles open for normal I/O or as a memory-mapped file

Usual tricks include:

try to close all processes having handles on that file. For an executable it generally means terminating all its instances

mark the file for deletion on next reboot. As you say that McAfee asks to reboot the computer it likely uses that option. The MoveFileEx WINAPI function has provision for that. Extracts from MSDN page (emphasize mine)

```<code>BOOL WINAPI MoveFileEx(
  _In_     LPCTSTR lpExistingFileName,
  _In_opt_ LPCTSTR lpNewFileName,
  _In_     DWORD   dwFlags
);
</code>```

...
lpNewFileName [in, optional]

      The new name of the file or directory on the local computer.
...

      If dwFlags specifies MOVEFILE_DELAY_UNTIL_REBOOT and lpNewFileName is NULL, MoveFileEx registers the lpExistingFileName file to be deleted when the system restarts.

Title: Deleting running files

Body:
It may depend on the OS and file system types. On Linux and Unix like, deleting a file a just removing an entry from a folder. The file is actually deleted on last close if no folder entry points to it. So you can safely delete a file even if it is opened in another process.

On Windows the MSDN says:

The DeleteFile function fails if an application attempts to delete a file that has other handles open for normal I/O or as a memory-mapped file

Usual tricks include:

try to close all processes having handles on that file. For an executable it generally means terminating all its instances

mark the file for deletion on next reboot. As you say that McAfee asks to reboot the computer it likely uses that option. The MoveFileEx WINAPI function has provision for that. Extracts from MSDN page (emphasize mine)

BOOL WINAPI MoveFileEx(
  _In_     LPCTSTR lpExistingFileName,
  _In_opt_ LPCTSTR lpNewFileName,
  _In_     DWORD   dwFlags
);

...
lpNewFileName [in, optional]

      The new name of the file or directory on the local computer.
...

      If dwFlags specifies MOVEFILE_DELAY_UNTIL_REBOOT and lpNewFileName is NULL, MoveFileEx registers the lpExistingFileName file to be deleted when the system restarts.


问:
How to use UIPickerView inside UITableViewController
Hi I have a Table view Controller Name as MyTableViewController. In MyTableViewController, i am using different UIPickerView inside different cell of table which is name as headerCell which is set by the following function and in that i am not using any UIPickerView

```<code>override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let  headerCell = tableView.dequeueReusableCell(withIdentifier: "header") as! MyTableViewCell
    headerCell.contentView.backgroundColor = UIColor.white
    return headerCell
}
</code>```

MyTableViewCell is class of UITableViewCell type in which, I have attached all table layouts like Label, TextField, Button,UIPickerView and etc.

My Second cell is middleCell an footerCell which is as

```<code>override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    var cell : SubscriptionTableViewCell?
    if indexPath.row == 1 {
        cell = tableView.dequeueReusableCell(withIdentifier: "footer", for: indexPath) as? SubscriptionTableViewCell
        cell!.cardTypePicker.delegate = self
        cell!.expMonth.delegate = self
        cell!.expYear.delegate = self
        cell!.countryPicker.delegate = self
        cell!.shippingMethodPicker.delegate = self

        cell!.cardTypePicker.dataSource = self
        cell!.expMonth.dataSource = self
        cell!.expYear.dataSource = self
        cell!.countryPicker.dataSource = self
        cell!.shippingMethodPicker.dataSource = self

    }else {
        cell = tableView.dequeueReusableCell(withIdentifier: "middle", for: indexPath) as? SubscriptionTableViewCell
        cell!.variantPicker.delegate = self
        cell!.variantPicker.dataSource = self
    }
    return cell!
}
</code>```

as you can see there are different UIPickerView.
So now i am not able to understand how should i use UIPickerView delegates inside UITableViewController.

Please help for that thanks.

答:
The term you are asking about is Inline Picker. There are so many ways to achieve this functionality. You can add a UIPickerView in your UITableViewCell and by making it's height's constraint you can modify it as you want. If you want to use third party picker you can refer below link:

https://github.com/sebamisc/UItableViewWithPicker

Body:
Hi I have a Table view Controller Name as MyTableViewController. In MyTableViewController, i am using different UIPickerView inside different cell of table which is name as headerCell which is set by the following function and in that i am not using any UIPickerView

override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let  headerCell = tableView.dequeueReusableCell(withIdentifier: "header") as! MyTableViewCell
    headerCell.contentView.backgroundColor = UIColor.white
    return headerCell
}

MyTableViewCell is class of UITableViewCell type in which, I have attached all table layouts like Label, TextField, Button,UIPickerView and etc.

My Second cell is middleCell an footerCell which is as

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    var cell : SubscriptionTableViewCell?
    if indexPath.row == 1 {
        cell = tableView.dequeueReusableCell(withIdentifier: "footer", for: indexPath) as? SubscriptionTableViewCell
        cell!.cardTypePicker.delegate = self
        cell!.expMonth.delegate = self
        cell!.expYear.delegate = self
        cell!.countryPicker.delegate = self
        cell!.shippingMethodPicker.delegate = self

        cell!.cardTypePicker.dataSource = self
        cell!.expMonth.dataSource = self
        cell!.expYear.dataSource = self
        cell!.countryPicker.dataSource = self
        cell!.shippingMethodPicker.dataSource = self

    }else {
        cell = tableView.dequeueReusableCell(withIdentifier: "middle", for: indexPath) as? SubscriptionTableViewCell
        cell!.variantPicker.delegate = self
        cell!.variantPicker.dataSource = self
    }
    return cell!
}

as you can see there are different UIPickerView.
So now i am not able to understand how should i use UIPickerView delegates inside UITableViewController.

Please help for that thanks.


答:
If you want the maximum value for mynum as well, then you need to apply MAX on mynum, e.g.:

```<code>SELECT `id`, MAX(number) as mynum, MAX(`sent`) AS sentOn
FROM `mTable`
GROUP BY `id`
</code>```

Title: SQL-Statement provides unexpected result

Body:
If you want the maximum value for mynum as well, then you need to apply MAX on mynum, e.g.:

SELECT `id`, MAX(number) as mynum, MAX(`sent`) AS sentOn
FROM `mTable`
GROUP BY `id`


问:
Distinct() returns duplicates with a user-defined type
I'm trying to write a Linq query which returns an array of objects, with unique values in their constructors.  For integer types, Distinct returns only one copy of each value, but when I try creating my list of objects, things fall apart.  I suspect it's a problem with the equality operator for my class, but when I set a breakpoint, it's never hit.

Filtering out the duplicate int in a sub-expression solves the problem, and also saves me from constructing objects that will be immediately discarded, but I'm curious why this version doesn't work.

UPDATE: 11:04 PM  Several folks have pointed out that MyType doesn't override GetHashCode().  I'm afraid I oversimplified the example.  The original MyType does indeed implement it.  I've added it below, modified only to put the hash code in a temp variable before returning it.

Running through the debugger, I see that all five invocations of GetHashCode return a different value. And since MyType only inherits from Object, this is presumably the same behavior Object would exhibit.

Would I be correct then to conclude that the hash should instead be based on the contents of Value?  This was my first attempt at overriding operators, and at the time, it didn't appear that GetHashCode needed to be particularly fancy.  (This is the first time one of my equality checks didn't seem to work properly.)

```<code>class Program
{
    static void Main(string[] args)
    {
        int[] list = { 1, 3, 4, 4, 5 };
        int[] list2 =
            (from value in list
             select value).Distinct().ToArray();    // One copy of each value.
        MyType[] distinct =
            (from value in list
             select new MyType(value)).Distinct().ToArray(); // Two objects created with 4.

        Array.ForEach(distinct, value => Console.WriteLine(value));
    }
}

class MyType
{
    public int Value { get; private set; }

    public MyType(int arg)
    {
        Value = arg;
    }

    public override int GetHashCode()
    {
        int retval = base.GetHashCode();
        return retval;
    }

    public override bool Equals(object obj)
    {
        if (obj == null)
            return false;

        MyType rhs = obj as MyType;
        if ((Object)rhs == null)
            return false;

        return this == rhs;
    }

    public static bool operator ==(MyType lhs, MyType rhs)
    {
        bool result;

        if ((Object)lhs != null && (Object)rhs != null)
            result = lhs.Value == rhs.Value;
        else
            result = (Object)lhs == (Object)rhs;

        return result;
    }

    public static bool operator !=(MyType lhs, MyType rhs)
    {
        return !(lhs == rhs);
    }
}
</code>```

答:
The other answers have pretty much covered the fact that you need to implement Equals and GetHashCode correctly, but as a side note you may be interested to know that anonymous types have these values implemented automatically:

```<code>var distinct =
        (from value in list
         select new {Value = value}).Distinct().ToArray();
</code>```

So without ever having to define this class, you automatically get the Equals and GetHashCode behavior you're looking for.  Cool, eh?

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to write a Linq query which returns an array of objects, with unique values in their constructors.  For integer types, Distinct returns only one copy of each value, but when I try creating my list of objects, things fall apart.  I suspect it's a problem with the equality operator for my class, but when I set a breakpoint, it's never hit.

Filtering out the duplicate int in a sub-expression solves the problem, and also saves me from constructing objects that will be immediately discarded, but I'm curious why this version doesn't work.

UPDATE: 11:04 PM  Several folks have pointed out that MyType doesn't override GetHashCode().  I'm afraid I oversimplified the example.  The original MyType does indeed implement it.  I've added it below, modified only to put the hash code in a temp variable before returning it.

Running through the debugger, I see that all five invocations of GetHashCode return a different value. And since MyType only inherits from Object, this is presumably the same behavior Object would exhibit.

Would I be correct then to conclude that the hash should instead be based on the contents of Value?  This was my first attempt at overriding operators, and at the time, it didn't appear that GetHashCode needed to be particularly fancy.  (This is the first time one of my equality checks didn't seem to work properly.)

class Program
{
    static void Main(string[] args)
    {
        int[] list = { 1, 3, 4, 4, 5 };
        int[] list2 =
            (from value in list
             select value).Distinct().ToArray();    // One copy of each value.
        MyType[] distinct =
            (from value in list
             select new MyType(value)).Distinct().ToArray(); // Two objects created with 4.

        Array.ForEach(distinct, value => Console.WriteLine(value));
    }
}

class MyType
{
    public int Value { get; private set; }

    public MyType(int arg)
    {
        Value = arg;
    }

    public override int GetHashCode()
    {
        int retval = base.GetHashCode();
        return retval;
    }

    public override bool Equals(object obj)
    {
        if (obj == null)
            return false;

        MyType rhs = obj as MyType;
        if ((Object)rhs == null)
            return false;

        return this == rhs;
    }

    public static bool operator ==(MyType lhs, MyType rhs)
    {
        bool result;

        if ((Object)lhs != null && (Object)rhs != null)
            result = lhs.Value == rhs.Value;
        else
            result = (Object)lhs == (Object)rhs;

        return result;
    }

    public static bool operator !=(MyType lhs, MyType rhs)
    {
        return !(lhs == rhs);
    }
}

Body:
The other answers have pretty much covered the fact that you need to implement Equals and GetHashCode correctly, but as a side note you may be interested to know that anonymous types have these values implemented automatically:

var distinct =
        (from value in list
         select new {Value = value}).Distinct().ToArray();

So without ever having to define this class, you automatically get the Equals and GetHashCode behavior you're looking for.  Cool, eh?


问:
Using a blade file for a template?
I have a blade file that I wish to use as a vue component. So in the .vue file I would normally have it coded as:

```<code><template>
....
</tempalte>
....rest of vue file
</code>```

But how can I use a blade file for a template?

答:
You can make use of slot in the vue file to insert the html passed from blade view.

Blade file:

```<code><vue-component>All your html to be passed goes here</vue-component>
</code>```

Vue file:

```<code><template>
    <slot></slot>
</template>
</code>```

You can read more about it in the official documentation for single slot here.

Title: Using a blade file for a template?

Body:
I have a blade file that I wish to use as a vue component. So in the .vue file I would normally have it coded as:

<template>
....
</tempalte>
....rest of vue file

But how can I use a blade file for a template?

Body:
You can make use of slot in the vue file to insert the html passed from blade view.

Blade file:

<vue-component>All your html to be passed goes here</vue-component>

Vue file:

<template>
    <slot></slot>
</template>

You can read more about it in the official documentation for single slot here.

ContentLicense: CC BY-SA 4.0


问:
How to reload the component of same URL in Angular 2?
I am trying to reload the same url in Angular 2 by using router.navigate but it is not working.
url : http://localhost:3000/landing
Scenario : I am on http://localhost:3000/landing and now I am changing a particular parameter in the page which should reload the page.

Code :

```<code>let link = ['Landing'];
this.router.navigate(link);
</code>```

答:
I managed to implement reloading a component by using PlatformLocation:onPopState and NgZone:run in the constructor. It was a work around, but atleast it worked the way it was required.

```<code>constructor(
    private route: ActivatedRoute,
    public router: Router,
    private platformLocation: PlatformLocation,
    private ngZone: NgZone) {

    platformLocation.onPopState(() => {
        if(platformLocation.pathname.startsWith("/currentRoute")) {
            this.ngZone.run(() => {
                console.log("Reloading component");
            });
        }
    });
}
</code>```

onPopState was used as the reloading was supposed to be triggered on browser back/forward button. Also the check for pathname had to be used as the onPopState method was getting invoked on back/forward in any routes as the component is injected.

Body:
I am trying to reload the same url in Angular 2 by using router.navigate but it is not working.
url : http://localhost:3000/landing
Scenario : I am on http://localhost:3000/landing and now I am changing a particular parameter in the page which should reload the page.

Code :

let link = ['Landing'];
this.router.navigate(link);

Body:
I managed to implement reloading a component by using PlatformLocation:onPopState and NgZone:run in the constructor. It was a work around, but atleast it worked the way it was required.

constructor(
    private route: ActivatedRoute,
    public router: Router,
    private platformLocation: PlatformLocation,
    private ngZone: NgZone) {

    platformLocation.onPopState(() => {
        if(platformLocation.pathname.startsWith("/currentRoute")) {
            this.ngZone.run(() => {
                console.log("Reloading component");
            });
        }
    });
}

onPopState was used as the reloading was supposed to be triggered on browser back/forward button. Also the check for pathname had to be used as the onPopState method was getting invoked on back/forward in any routes as the component is injected.


问:
Mockito Android Unit testing
I have MVP in my application. Presenter has interface

```<code>public interface ILoginPresenter<V> extends Presenter<V> {
    void logUserIn(String email, String password, String deviceToken, String deviceType);
}
</code>```

Realization has RX Single

```<code> mLoginSubscription = mModel.logUserIn(email, password, deviceToken, deviceType)
            .compose(RxUtil.setupNetworkSingle())
            .subscribe(new Subscriber<User>() {
                @Override
                public void onCompleted() {
                    Timber.i("Log in complete");
                }

                @Override
                public void onError(Throwable e) {
                    Timber.e(e, "Retrofit could not get User.");

                    getView().dismissProgressDialog();
                }

                @Override
                public void onNext(UserResponseRetrofit response) {
                    Timber.i("Retrofit is attempting to get User");
                    mSaveModel.saveUser(user);
                    getView().dismissProgressDialog();
                    getView().goToMenuActivity();
                }
            });
</code>```

Also i have module for Dagger

```<code>@Module
public class ModelModule {
    @Provides
    @ScreenScope
    public ILoginModel provideLoginModel(LoginModel p) {
        return p;
    }
}
</code>```

My unit test look like next:

```<code>@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 21, manifest = "/src/main/AndroidManifest.xml")
public class LoginPresenterTest {

    public static final String SOME_OTHER_TOKEN = "someOtherToken";
    private AppComponent mAppComponent;
    private LoginComponent mLoginComponent;
    private ILoginView mockView;
    private ModelModule mockModel;
    private ILoginPresenter mLoginPresenter;

    @Before
    public void setup() {
        // Creating the mocks
        mockView = Mockito.mock(ILoginView.class);
        mockModel = Mockito.mock(ModelModule.class);

        ILoginModel mock = Mockito.mock(ILoginModel.class);
        User urr = Mockito.mock(User.class);
        Mockito.when(mockModel.provideLoginModel(null)).thenReturn(mock);
        Mockito.when(mock.logUserIn("", "", "", "")).thenReturn(ScalarSynchronousSingle.just(urr));

        mAppComponent = DaggerAppComponent.builder()
                .appModule(new AppModule(RuntimeEnvironment.application))
                .build();

        mLoginComponent = DaggerLoginComponent.builder()
                .appComponent(mAppComponent)
                .modelModule(mockModel)
                .presenterModule(new PresenterModule())
                .build();

        mLoginPresenter = mLoginComponent.provideLoginPresenter();
        mLoginPresenter.setView(mockView);
    }

    @Test
    public void testLogin() {
        mLoginPresenter.logUserIn("", "", "", "");
        try {
            java.lang.Thread.sleep(20000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Mockito.verify(mockView).dismissProgressDialog();
    }
</code>```

So using Dagger I need to build Presenter correctly. For this purposes, I am trying to use Mockito.when. Firstly look like this line doesn't work

```<code>Mockito.when(mockModel.provideLoginModel(null)).thenReturn(mock);
</code>```

The target purpose is to use my own Model realization which return Single.

don't really understand why my mock of ModelModule doesn't work?

答:
UPDATED

The issue may be that you are mocking will null. In that case mockModel will only return mock when provideLoginModel is called with null

```<code>Mockito.when(mockModel.provideLoginModel(null)).thenReturn(mock);
mockModel.provideLoginModel(null) // returns mock
mockModel.provideLoginModel(new Foo()) // returns null
</code>```

Instead you can use a matcher such as any():

```<code>Mockito.when(mockModel.provideLoginModel(any())).thenReturn(mock);
mockModel.provideLoginModel(null) // returns mock
mockModel.provideLoginModel(new Foo()) // also returns null
</code>```

to return mock on any call.

BIG PICTURE
For unit testing I would suggest not using Dagger, instead use @Mock and @InjectMocks you only need the object you are testing to be real the rest can be mocks.

```<code>@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 21, manifest = "/src/main/AndroidManifest.xml")
public class LoginPresenterTest {

    public static final String SOME_OTHER_TOKEN = "someOtherToken";

    @Mock
    ILoginView mockView;

    @Mock
    SomePresenterDependency somePresenterDependency

    @InjectMocks
    ILoginPresenter mLoginPresenter;

    @Before
    public void setup() {
        MockitoAnnotations.injectMocks(this);

        mLoginPresenter.setView(mockView);
    }

    @Test
    public void testLogin() {
        mLoginPresenter.logUserIn("", "", "", "");
        try {
            java.lang.Thread.sleep(20000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Mockito.verify(mockView).dismissProgressDialog();
    }
}
</code>```

If you are doing integration testing and need multiple real objects you could just create an inner/anonymous module for your component that returns the desired object. (instead of trying to mock the module interface).

Title: Mockito Android Unit testing

Body:
I have MVP in my application. Presenter has interface

public interface ILoginPresenter<V> extends Presenter<V> {
    void logUserIn(String email, String password, String deviceToken, String deviceType);
}

Realization has RX Single

 mLoginSubscription = mModel.logUserIn(email, password, deviceToken, deviceType)
            .compose(RxUtil.setupNetworkSingle())
            .subscribe(new Subscriber<User>() {
                @Override
                public void onCompleted() {
                    Timber.i("Log in complete");
                }

                @Override
                public void onError(Throwable e) {
                    Timber.e(e, "Retrofit could not get User.");

                    getView().dismissProgressDialog();
                }

                @Override
                public void onNext(UserResponseRetrofit response) {
                    Timber.i("Retrofit is attempting to get User");
                    mSaveModel.saveUser(user);
                    getView().dismissProgressDialog();
                    getView().goToMenuActivity();
                }
            });

Also i have module for Dagger

@Module
public class ModelModule {
    @Provides
    @ScreenScope
    public ILoginModel provideLoginModel(LoginModel p) {
        return p;
    }
}

My unit test look like next:

@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 21, manifest = "/src/main/AndroidManifest.xml")
public class LoginPresenterTest {

    public static final String SOME_OTHER_TOKEN = "someOtherToken";
    private AppComponent mAppComponent;
    private LoginComponent mLoginComponent;
    private ILoginView mockView;
    private ModelModule mockModel;
    private ILoginPresenter mLoginPresenter;

    @Before
    public void setup() {
        // Creating the mocks
        mockView = Mockito.mock(ILoginView.class);
        mockModel = Mockito.mock(ModelModule.class);

        ILoginModel mock = Mockito.mock(ILoginModel.class);
        User urr = Mockito.mock(User.class);
        Mockito.when(mockModel.provideLoginModel(null)).thenReturn(mock);
        Mockito.when(mock.logUserIn("", "", "", "")).thenReturn(ScalarSynchronousSingle.just(urr));

        mAppComponent = DaggerAppComponent.builder()
                .appModule(new AppModule(RuntimeEnvironment.application))
                .build();

        mLoginComponent = DaggerLoginComponent.builder()
                .appComponent(mAppComponent)
                .modelModule(mockModel)
                .presenterModule(new PresenterModule())
                .build();

        mLoginPresenter = mLoginComponent.provideLoginPresenter();
        mLoginPresenter.setView(mockView);
    }

    @Test
    public void testLogin() {
        mLoginPresenter.logUserIn("", "", "", "");
        try {
            java.lang.Thread.sleep(20000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Mockito.verify(mockView).dismissProgressDialog();
    }

So using Dagger I need to build Presenter correctly. For this purposes, I am trying to use Mockito.when. Firstly look like this line doesn't work

Mockito.when(mockModel.provideLoginModel(null)).thenReturn(mock);

The target purpose is to use my own Model realization which return Single.

don't really understand why my mock of ModelModule doesn't work?

Body:
UPDATED

The issue may be that you are mocking will null. In that case mockModel will only return mock when provideLoginModel is called with null

Mockito.when(mockModel.provideLoginModel(null)).thenReturn(mock);
mockModel.provideLoginModel(null) // returns mock
mockModel.provideLoginModel(new Foo()) // returns null

Instead you can use a matcher such as any():

Mockito.when(mockModel.provideLoginModel(any())).thenReturn(mock);
mockModel.provideLoginModel(null) // returns mock
mockModel.provideLoginModel(new Foo()) // also returns null

to return mock on any call.

BIG PICTURE
For unit testing I would suggest not using Dagger, instead use @Mock and @InjectMocks you only need the object you are testing to be real the rest can be mocks.

@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 21, manifest = "/src/main/AndroidManifest.xml")
public class LoginPresenterTest {

    public static final String SOME_OTHER_TOKEN = "someOtherToken";

    @Mock
    ILoginView mockView;

    @Mock
    SomePresenterDependency somePresenterDependency

    @InjectMocks
    ILoginPresenter mLoginPresenter;

    @Before
    public void setup() {
        MockitoAnnotations.injectMocks(this);

        mLoginPresenter.setView(mockView);
    }

    @Test
    public void testLogin() {
        mLoginPresenter.logUserIn("", "", "", "");
        try {
            java.lang.Thread.sleep(20000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Mockito.verify(mockView).dismissProgressDialog();
    }
}

If you are doing integration testing and need multiple real objects you could just create an inner/anonymous module for your component that returns the desired object. (instead of trying to mock the module interface).


问:
PHP overwrite method and call the overwritten in same class
I have a class given by an external developer. He could update his class whenever he wants.
One of his method, e.g. "getArray", returns me an Array directly with important information in it.

```<code>class externalDevDudesClass
{
    public function getArray
    {
        return array(
            'example' => 'important information';
        );
    }
}
</code>```

I'd like to add some information to the given array.
I have the possibility to copy and overwrite any method of his class but then I don't have the new information coming on an update.
Ye, I could create a child of his class but I can't update the code where it creates objects of the class "externalDevDudesClass". So my question is: is there a possibility to add additional informations to this array by calling the method "getArray"? Maybe by working with an class_alias or something?

答:
Of course there is a solution. Extends his class and add your information to the return value of parent::getArray()</p>

```<code>class MyClass extends externalDevDudesClass {
    public function getArray() {
        $parentValue = parent::getArray();
        return array_merge($parentValue, ['my' => 1];
    }
}
</code>```

Body:
I have a class given by an external developer. He could update his class whenever he wants.
One of his method, e.g. "getArray", returns me an Array directly with important information in it.

class externalDevDudesClass
{
    public function getArray
    {
        return array(
            'example' => 'important information';
        );
    }
}

I'd like to add some information to the given array.
I have the possibility to copy and overwrite any method of his class but then I don't have the new information coming on an update.
Ye, I could create a child of his class but I can't update the code where it creates objects of the class "externalDevDudesClass". So my question is: is there a possibility to add additional informations to this array by calling the method "getArray"? Maybe by working with an class_alias or something?

Body:
Of course there is a solution. Extends his class and add your information to the return value of parent::getArray()

class MyClass extends externalDevDudesClass {
    public function getArray() {
        $parentValue = parent::getArray();
        return array_merge($parentValue, ['my' => 1];
    }
}


问:
Bootstrap - Auto expanding container, row & row columns' width with content
I have following html:

```<code><div class="container">
 <div class="row">
    <div class="col-md-6">
        <ul>
            <li>Long Content 1<li>
        </ul>
    </div>
    <div class="col-md-6">
        <ul>
            <li>Long Content 2<li>
        </ul>
    </div>
 </div>
</div>
</code>```

I will be adding dynamic content into each ul element. I want col-md-* elements and their parents to expand  themselves horizontally with the content, even if they horizontally overflow the screen window. I don't mind horizontal scrolling on the screen. How can I achieve this?

答:
This will force the element to NEVER wrap text and should help with what you're looking for.

```<code>li{white-space:nowrap}
</code>```

You may need to change the li element to display:block as well

Body:
I have following html:

Long Content 1

Long Content 2

I will be adding dynamic content into each ul element. I want col-md-* elements and their parents to expand  themselves horizontally with the content, even if they horizontally overflow the screen window. I don't mind horizontal scrolling on the screen. How can I achieve this?

Body:
This will force the element to NEVER wrap text and should help with what you're looking for.

li{white-space:nowrap}

You may need to change the li element to display:block as well


问:
brew: no formula called ctls
I'm getting the following error when trying to install Vapor's CTLS package. </p>

```<code>Gertrude:ctls tanner$ brew install ctls
Error: No available formula with the name "ctls"
==> Searching for similarly named formulae...
Error: No similarly named formulae found.
==> Searching taps...
Error: No formulae found in taps.
</code>```

答:
You need to add Vapor's tap first.

```<code>brew tap vapor/homebrew-tap
</code>```

Then run it again

```<code>brew install ctls
</code>```

Title: brew: no formula called ctls

Body:
I'm getting the following error when trying to install Vapor's CTLS package.

Gertrude:ctls tanner$ brew install ctls
Error: No available formula with the name "ctls"
==> Searching for similarly named formulae...
Error: No similarly named formulae found.
==> Searching taps...
Error: No formulae found in taps.

Body:
You need to add Vapor's tap first.

brew tap vapor/homebrew-tap

Then run it again

brew install ctls


问:
Windows Azure automatic deployment. Problem with powershell script
I am using Azure Management Cmdlets version 1.0.

I run the following PowerShell script

New-Deployment -subscriptionId bef7722c-1a13-4c9f-b7f6-fafc0a958b35 -certificate D:\pcg\T.cer -serviceName 1ClickDeploymentTest -slot Production -package D:\pcg

\CloudTodorTest.cspkg -configuration D:\pcg\ServiceConfiguration.cscfg -label lbl1 -StorageServiceName TodorTestStorage

where the D:\pcg\T.cert is the certificate which is already uploaded to Azure too.
The package and the configuration are the local copies of the application that is already running on Azure.
I've tried to deploy them manually and they are working.

After executing this script I receive the following error message:

PS C:\Windows\SysWOW64\WindowsPowerShell\v1.0> D:\PSScripts\dt2.ps1
New-Deployment : The remote server returned an unexpected response: (400) Bad Request.
At D:\PSScripts\dt2.ps1:1 char:15
+ New-Deployment <<<<  -subscriptionId bef7722c-1a13-4c9f-b7f6-fafc0a958b35 -certificate D:\pcg\T.cer -serviceName 1Cli
ckDeploymentTest -slot Staging -package D:\pcg\CloudTodorTest.cspkg -configuration D:\pcg\ServiceConfiguration.cscfg -l
abel lbl1 -StorageServiceName TodorTestStorage | Get-OperationStatus -WaitToComplete
    + CategoryInfo          : CloseError: (:) [New-Deployment], ProtocolException
    + FullyQualifiedErrorId : Microsoft.Samples.AzureManagementTools.PowerShell.HostedServices.NewDeploymentCommand

I can execute other cmdlets. For example to check the current deployments.

答:
Check the case of the service name and deployment slot and other parameters you're specifying - I seem to recall that the service name has to be all lower case because it is used in DNS.

The Azure API is very finicky about case sensitivity of some of the arguments, and if you get it wrong you'll get a Bad Request response with no further info.

If the problem were with the subscription id or the certificate, you'd get a Not Authorized response.  I think you've gotten past authorization and are failing because something in the request itself is invalid.


问:
Loading Image Gallery taking too time in Razor View
I use a image gallery plugin called Unite Gallery plugin in an ASP.NET MVC project in order to display images stored in database. However, loading all of the images at the same time takes too long time (because each photo is in 1MB-4MB size and loading 500 photos at the same time on page load is not a good idea) and I think there must be a better approach i.e. asenkron loading or partial loading.  Here is my Razor and Controller code. I have a look at many pages on the wweb and docs, but there is not an example in the documentation page. Do you have any idea?

```<code><div id="gallery" style="display:none;">

    @foreach (var item in Model)
    {
        if (item.FileData != null)
        {
            var base64 = Convert.ToBase64String(item.FileData);
            var imgSrc = String.Format("data:image/gif;base64,{0}", base64);

            <img alt='Image'
                    src="@imgSrc"
                    data-image="@imgSrc"
                    data-description='Image'>
        }
    }
</div>

<script type="text/javascript">

    jQuery(document).ready(function () {
    var gallery = jQuery("#gallery").unitegallery({
        gallery_theme: "default" //theme skin
    });

    gallery.on("item_change", function (num, data) {
        if((num%15) == 0)
        {
            $.ajax({
                url: '@Url.Action("List", "PhotoContest")',
                data: { isAll: isAllChecked, page: num }, //??? I pass the page parameter???
              success: function(data){
                //call is successfully completed and we got result in data

                //??? NO IDEA ???

              },
              error:function (xhr, ajaxOptions, thrownError){
                              //some errror, some show err msg to user and log the error
                              alert(xhr.responseText);
                            }
              });
        }
    });

});

</script>

public ActionResult List(string query)
{
    var model = db.Photo.Select(m => new PhotoViewModel
    {
        Id = m.Id,
        Name = m.Name,
        StatusId = m.StatusId,
        SubmitDate = m.SubmitDate,
        FileAttachments = m.FileAttachments,
        SubmitNo = m.SubmitNo
    })
    .ToArray();

    return View("List", model);
}
</code>```

Update:

After trying to apply @Kris's perfect approach, I encountered the error shown below. There is not a fix or solution regarding to this specific problem on the web. Any idea?

The image after page load overloads div and gallery borders as shown below:

答:
I don't think there's just one issue here. First, loading 100s of images all at once is going to be slow no matter what you do. For this point @Kris probably has the right idea. I'm unfamiliar with this particular library, but if it provides a way to progressively load in a handful of images at a time, you should definitely make use of that.

The second issue is that you're using base64-encoded data URIs. Images encoded in this way are roughly 150% as large as the actual image data itself. In other words, you're adding greater stress to an already stressed situation. Instead, you should have an action that returns the image data, something like:

```<code>public ActionResult GetImage(int id)
{
    var image = db.Images.Find(id);
    if (image == null)
    {
        return new HttpNotFoundResult();
    }

    return File(image.FileData, image.FileType);
}
</code>```

You can get somewhat creative here by caching the database query result or even the entire response, but be advised that you'll need a significant amount of RAM, since you're going to be storing a lot of image data there.

Third, there's the issue of using a database to store image data in the first place. Just because databases provide a blob type, doesn't mean you need to use it. The most performant approach is always going to be serving directly from the filesystem, as IIS can serve static files directly, without involving all the ASP.NET machinery. Instead of storing the image data in your database, write the image to a filesystem location and then merely store the path to the image in the database. You could then optimize even further by actually offloading all the images to a CDN, ensuring super-fast delivery and taking virtually all load off your server.

Body:
I use a image gallery plugin called Unite Gallery plugin in an ASP.NET MVC project in order to display images stored in database. However, loading all of the images at the same time takes too long time (because each photo is in 1MB-4MB size and loading 500 photos at the same time on page load is not a good idea) and I think there must be a better approach i.e. asenkron loading or partial loading.  Here is my Razor and Controller code. I have a look at many pages on the wweb and docs, but there is not an example in the documentation page. Do you have any idea?

    @foreach (var item in Model)
    {
        if (item.FileData != null)
        {
            var base64 = Convert.ToBase64String(item.FileData);
            var imgSrc = String.Format("data:image/gif;base64,{0}", base64);

        }
    }

public ActionResult List(string query)
{
    var model = db.Photo.Select(m => new PhotoViewModel
    {
        Id = m.Id,
        Name = m.Name,
        StatusId = m.StatusId,
        SubmitDate = m.SubmitDate,
        FileAttachments = m.FileAttachments,
        SubmitNo = m.SubmitNo
    })
    .ToArray();

    return View("List", model);
}

Update:

After trying to apply @Kris's perfect approach, I encountered the error shown below. There is not a fix or solution regarding to this specific problem on the web. Any idea?

The image after page load overloads div and gallery borders as shown below:

Body:
I don't think there's just one issue here. First, loading 100s of images all at once is going to be slow no matter what you do. For this point @Kris probably has the right idea. I'm unfamiliar with this particular library, but if it provides a way to progressively load in a handful of images at a time, you should definitely make use of that.

The second issue is that you're using base64-encoded data URIs. Images encoded in this way are roughly 150% as large as the actual image data itself. In other words, you're adding greater stress to an already stressed situation. Instead, you should have an action that returns the image data, something like:

public ActionResult GetImage(int id)
{
    var image = db.Images.Find(id);
    if (image == null)
    {
        return new HttpNotFoundResult();
    }

    return File(image.FileData, image.FileType);
}

You can get somewhat creative here by caching the database query result or even the entire response, but be advised that you'll need a significant amount of RAM, since you're going to be storing a lot of image data there.

Third, there's the issue of using a database to store image data in the first place. Just because databases provide a blob type, doesn't mean you need to use it. The most performant approach is always going to be serving directly from the filesystem, as IIS can serve static files directly, without involving all the ASP.NET machinery. Instead of storing the image data in your database, write the image to a filesystem location and then merely store the path to the image in the database. You could then optimize even further by actually offloading all the images to a CDN, ensuring super-fast delivery and taking virtually all load off your server.


问:
Changing class type using Jquery
I am using this code to fetch the data from startup.php.The response of the PHP file is JSON with 3 fields. One of the field in JSON response is a status message. How to change the value of div class .content based on the status message. I need to do that to change the color of the text displayed in the content DIV based on the status message. .content is the class name of the DIV

```<code>var loadinggif = '../img/loading.gif';
$(document).ready(function(){
    // set up the click event
        $('body').on('click','.btnbg', function() {
                var toLoad = '../vr/startup.php';
                $('.content').empty();
                $('.content').slideUp('slow', loadContent);
                $('#load').remove();
                $('#waiting').append('<div id="load"><img src="' + loadinggif + '" alt="Loading" /></div>');
                $('#load').fadeIn('normal');
                function loadContent() {

                    var userName = $('#userName').val();
                    var remote_addr = $('#remote_addr').val();
                    var forwarded_for = $('#forwarded_for').val();
                    var url = $('#url').val();
                    //$('#forwarded_for1').val()'';
  var _post = {'userName': userName, 'ipAddr1':remote_addr,'ipAddr2':forwarded_for, 'url':url};

   $('.content').load(toLoad, _post , function(response, status, xhr)

if (status == 'error') {
                        var msg = "Sorry but there was an error: ";
                        $(".content").html(msg + xhr.status + " " + xhr.statusText);
                    }
            }).slideDown('slow', hideLoader());
                }
                function hideLoader() {
                        $('#load').fadeOut('normal');
                }
                return false;
        });
</code>```

答:
Use removeClass() and addClass().

Here is an example:

```<code>$('.content').removeClass("styleOne").addClass("styleTwo");
</code>```

Edit

```<code>if(response == "Worked Fine"){
    $('.content').removeClass("default").addClass("styleGreen");
}else{
     $('.content').removeClass("default").addClass("styleRed");
}
</code>```

Title: Changing class type using Jquery

Body:
I am using this code to fetch the data from startup.php.The response of the PHP file is JSON with 3 fields. One of the field in JSON response is a status message. How to change the value of div class .content based on the status message. I need to do that to change the color of the text displayed in the content DIV based on the status message. .content is the class name of the DIV

var loadinggif = '../img/loading.gif';
$(document).ready(function(){
    // set up the click event
        $('body').on('click','.btnbg', function() {
                var toLoad = '../vr/startup.php';
                $('.content').empty();
                $('.content').slideUp('slow', loadContent);
                $('#load').remove();
                $('#waiting').append('

');
                $('#load').fadeIn('normal');
                function loadContent() {

                    var userName = $('#userName').val();
                    var remote_addr = $('#remote_addr').val();
                    var forwarded_for = $('#forwarded_for').val();
                    var url = $('#url').val();
                    //$('#forwarded_for1').val()'';
  var _post = {'userName': userName, 'ipAddr1':remote_addr,'ipAddr2':forwarded_for, 'url':url};

   $('.content').load(toLoad, _post , function(response, status, xhr)

if (status == 'error') {
                        var msg = "Sorry but there was an error: ";
                        $(".content").html(msg + xhr.status + " " + xhr.statusText);
                    }
            }).slideDown('slow', hideLoader());
                }
                function hideLoader() {
                        $('#load').fadeOut('normal');
                }
                return false;
        });

Body:
Use removeClass() and addClass().

Here is an example:

$('.content').removeClass("styleOne").addClass("styleTwo");

Edit

if(response == "Worked Fine"){
    $('.content').removeClass("default").addClass("styleGreen");
}else{
     $('.content').removeClass("default").addClass("styleRed");
}


问:
SonataAdminBundle: how to create a SonataBlock and save it to database?
I try to create a new block from SonataBlockBundle, edit the content block and want to save it to database.

in my composer.json, i got:

```<code>    "sonata-project/admin-bundle": "^2.3.0",
    "sonata-project/doctrine-orm-admin-bundle": "^2.3.4",
    "sonata-project/media-bundle": "2.3.x-dev",
    "sonata-project/core-bundle": "^2.3.0",
    "sonata-project/intl-bundle": "^2.3.0",
    "doctrine/doctrine-migrations-bundle": "dev-master",
    "symfony-cmf/block-bundle": "^1.3.1",
    "jackalope/jackalope-doctrine-dbal": "1.2.*",
    "sonata-project/doctrine-phpcr-admin-bundle": "^1.2",
    "doctrine/doctrine-cache-bundle": "1.0.*"
</code>```

In the dashboard, i got no menu to create a new block, and i got this error in the console:

```<code>The following document types provided in valid_children are invalid: Symfony\Cmf\Bundle\ContentBundle\Doctrine\Phpcr\StaticContent The class names provided could not be loaded
</code>```

Can i use the symfony-cmf/block-bundle as a standalone without install all the symfony-cmf ?

How to simply create a SonataBlock, and save it to database ?

答:
I'm not sure if you can mix in symfony-cmf/block-bundle with SonataAdminBundle.  But I can tell you, how to display Block's (SonataBlockBundle) on your dashboard.

Include the SonataBlockBundle described in SonataBlockBundle's
Installation
Documentation.

Refer to SonataAdminBundle's Dashboard
Documentation
to configure blocks on your dashboard.

In short it's pretty easy to configure more blocks (or even custom ones, just register them):

```<code># app/config/config.yml
sonata_admin:
    dashboard:
        blocks:
            -
                position: top
                type:     sonata.block.service.text
                settings:
                    content: >
                        <p>My dashboard block</p>
                        <p>Feel free to extend me</p>
</code>```

Body:
I try to create a new block from SonataBlockBundle, edit the content block and want to save it to database.

in my composer.json, i got:

    "sonata-project/admin-bundle": "^2.3.0",
    "sonata-project/doctrine-orm-admin-bundle": "^2.3.4",
    "sonata-project/media-bundle": "2.3.x-dev",
    "sonata-project/core-bundle": "^2.3.0",
    "sonata-project/intl-bundle": "^2.3.0",
    "doctrine/doctrine-migrations-bundle": "dev-master",
    "symfony-cmf/block-bundle": "^1.3.1",
    "jackalope/jackalope-doctrine-dbal": "1.2.*",
    "sonata-project/doctrine-phpcr-admin-bundle": "^1.2",
    "doctrine/doctrine-cache-bundle": "1.0.*"

In the dashboard, i got no menu to create a new block, and i got this error in the console:

The following document types provided in valid_children are invalid: Symfony\Cmf\Bundle\ContentBundle\Doctrine\Phpcr\StaticContent The class names provided could not be loaded

Can i use the symfony-cmf/block-bundle as a standalone without install all the symfony-cmf ?

How to simply create a SonataBlock, and save it to database ?

Body:
I'm not sure if you can mix in symfony-cmf/block-bundle with SonataAdminBundle.  But I can tell you, how to display Block's (SonataBlockBundle) on your dashboard.

Include the SonataBlockBundle described in SonataBlockBundle's
Installation
Documentation.

Refer to SonataAdminBundle's Dashboard
Documentation
to configure blocks on your dashboard.

In short it's pretty easy to configure more blocks (or even custom ones, just register them):

# app/config/config.yml
sonata_admin:
    dashboard:
        blocks:
            -
                position: top
                type:     sonata.block.service.text
                settings:
                    content: >
                        <p>My dashboard block</p>
                        <p>Feel free to extend me</p>


问:
Using ionic2 tags inside custom components
Ionic Setup:

Ionic Framework: 2.3.0

Ionic App Scripts: 1.1.4

Angular Core: 2.4.8

Angular Compiler CLI: 2.4.8

Node: 4.2.6

I'm new at ionic and angular and I'm trying to create a custom component using ionic tags, take a look at my code:

mynavbar.component.ts

```<code>import {Component} from "@angular/core";
import {IONIC_DIRECTIVES} from 'ionic-angular';

@Component({
  selector: 'my-navbar',
  directives: [IONIC_DIRECTIVES],
  templateUrl: 'mynavbar.component.html'
})

export class MyNavbarComponent {}
</code>```

and here is my templateUrl:

```<code><ion-header>
  <ion-toolbar>
    <ion-buttons start>
       <button ion-button icon-only>
         <ion-icon name="contact"></ion-icon>
       </button>
    </ion-buttons>
    <ion-title>MyApp</ion-title>
    <ion-buttons end>
       <button ion-button icon-only>
         <ion-icon name="pin"></ion-icon>
       </button>
    </ion-buttons>
  </ion-toolbar>
  <ion-segment color="primary">
    <ion-segment-button value="pessoas">
       Pessoas
    </ion-segment-button>
    <ion-segment-button value="grupos">
     Grupos
    </ion-segment-button>
  </ion-segment>
 </ion-header>
</code>```

and I'm receiving this error: has no exported member 'IONIC_DIRECTIVES'. I'm trying to import the IONIC_DIRECTIVES because I saw some anwsers here saying to import that in our component if we want to use ionic tags inside custom components but I'm receiving this error.

@edit If I choose to not import Ionic_Directives I receive no error but all ionic tags that I use in the custom component lose all style

答:
If you have created your project using Ionic2 template project, there is no  need of importing IONIC_DIRECTIVES.

Remove that import  of IONIC_DIRECTIVES and it's entry from directives decorator.

Body:
Ionic Setup:

Ionic Framework: 2.3.0

Ionic App Scripts: 1.1.4

Angular Core: 2.4.8

Angular Compiler CLI: 2.4.8

Node: 4.2.6

I'm new at ionic and angular and I'm trying to create a custom component using ionic tags, take a look at my code:

mynavbar.component.ts

import {Component} from "@angular/core";
import {IONIC_DIRECTIVES} from 'ionic-angular';

@Component({
  selector: 'my-navbar',
  directives: [IONIC_DIRECTIVES],
  templateUrl: 'mynavbar.component.html'
})

export class MyNavbarComponent {}

and here is my templateUrl:

<ion-header>
  <ion-toolbar>
    <ion-buttons start>
       <button ion-button icon-only>
         <ion-icon name="contact"></ion-icon>
       </button>
    </ion-buttons>
    <ion-title>MyApp</ion-title>
    <ion-buttons end>
       <button ion-button icon-only>
         <ion-icon name="pin"></ion-icon>
       </button>
    </ion-buttons>
  </ion-toolbar>
  <ion-segment color="primary">
    <ion-segment-button value="pessoas">
       Pessoas
    </ion-segment-button>
    <ion-segment-button value="grupos">
     Grupos
    </ion-segment-button>
  </ion-segment>
 </ion-header>

and I'm receiving this error: has no exported member 'IONIC_DIRECTIVES'. I'm trying to import the IONIC_DIRECTIVES because I saw some anwsers here saying to import that in our component if we want to use ionic tags inside custom components but I'm receiving this error.

@edit If I choose to not import Ionic_Directives I receive no error but all ionic tags that I use in the custom component lose all style


问:
Extract data from a promise Object or Array

I have an API that returns json. The json has 100 objects, each having
  image url and description of the image. I use ng-repeat to show the
  images and modal attached that pops-up when I click the images with
  its description.

I have 2 templates and 2 controllers for the normal and modal components. I already have images on my HTML and I just need to pass the same data returned from the factory into the ModalInstanceController so that I can show description on image-click.

Do I need to call the factory method to get the data inside the
  ModalInstanceController or pass the data from controller (which is an
  array that contains promise with resolve). The issue is I passed the
  ietms with resolve but can't extract it inside ModalInstanceController as
  it's an array containing promise (in console it says 'value was evaluated just now' and I can't use .then() to an array.

My code structure is :

JSON Factory

```<code>(function() {
  angular
    .module('Brastlewark')
    .factory('GnomeFactory', GnomeFactory)

  function GnomeFactory($http) {
    let allGnomes = { getAllGnomes }

    function getAllGnomes() {
      const url = 'https://raw.githubusercontent.com/rrafols/mobile_test/master/data.json'
      return $http.get(url)
        .then(response => response.data.Brastlewark)
    }
    return allGnomes
  }
})()
</code>```

Main Controller that opens modal-instance

```<code>(function() {
  angular
    .module('Brastlewark')
    .controller('DetailsController', DetailsController)

  function DetailsController(GnomeFactory, $log, $uibModal) {
    let vm = this

    GnomeFactory.getAllGnomes()
      .then((data) => {
        vm.gnomeList = data
        return vm.gnomeList
      })

    // opening modal window to trigger model instance controller to act
    vm.showModal = (index) => {
      $log.log(`Button with index ${index} was clicked !!`)
      let configModal = {
        animation: true,
        templateUrl: 'myModal.html',
        size: 'sm',
        controller: 'ModalController',
        resolve: {
          gnomeData: () => vm.gnomeList
        }
      }
      let modalInstance = $uibModal.open(configModal)
      modalInstance.result.then(console.log, console.log)
    }
  }
})()
</code>```

ModalController

```<code>angular
  .module('Brastlewark')
  .controller('ModalController', ModalController)

function ModalController($scope, $uibModalInstance, $log, gnomeData) {

  $scope.gnomeList = gnomeData
  $scope.ok = function() {
    $uibModalInstance.close($scope)
  }
  $scope.cancel = () => {
    $uibModalInstance.dismiss('cancel')
  }
}
</code>```

Template for both

```<code>    <section id="details">
      <ul>
        <li ng-repeat="gnome in vm.gnomeList">
          <button type="button" ng-click="vm.showModal($index)">
            <img ng-src={{gnome.thumbnail}}>
          </button>
        </li>
      </ul>
    </section>

    <!-- @modal template start -->
    <script type="text/ng-template" id="myModal.html">
      <div class="modal-body" id="modalbody">
        <ul>
          <p>Friends : </p>
          <li ng-repeat="friend in gnomeList.friends">
            <span>{{friend}}</span>
          </li>
        </ul>
        <div class="modal-footer">
          <button class="btn btn-primary" type="button" ng-click="ok()">OK</button>
          <button class="btn btn-warning" type="button" ng-click="cancel()">Cancel</button>
        </div>
    </script>
</code>```

NOTE: IT SHOWS MODAL AND INDEX OF IMAGE CLICKED... But doesn't receive the array.

答:
Change your service to, (returning only API promise)

```<code>(function() {
  angular
    .module('Brastlewark')
    .factory('GnomeFactory', GnomeFactory)

  function GnomeFactory($http) {
    let allGnomes = { getAllGnomes }

    function getAllGnomes() {
      const url = 'https://raw.githubusercontent.com/rrafols/mobile_test/master/data.json'
      return $http.get(url)
    }
    return allGnomes
  }
})()
</code>```

returning just an API promise return $http.get(url)

Now your controller, handle the promise returned from the service using then

```<code>(function() {
  angular
    .module('Brastlewark')
    .controller('DetailsController', DetailsController)

  function DetailsController(GnomeFactory, $log, $uibModal) {
    let vm = this

    GnomeFactory.getAllGnomes()
      .then((data) => {
        vm.gnomeList = data.data.Brastlewark
        return vm.gnomeList
      },(data) => {
       console.log('error')
      })

    // opening modal window to trigger model instance controller to act
    vm.showModal = (index) => {
      $log.log(`Button with index ${index} was clicked !!`)
      let configModal = {
        animation: true,
        templateUrl: 'myModal.html',
        size: 'sm',
        controller: 'ModalController',
        resolve: {
          gnomeData: () => vm.gnomeList
        }
      }
      let modalInstance = $uibModal.open(configModal)
      modalInstance.result.then(console.log, console.log)
    }
  }
})()
</code>```

Body:
I have an API that returns json. The json has 100 objects, each having
  image url and description of the image. I use ng-repeat to show the
  images and modal attached that pops-up when I click the images with
  its description.

I have 2 templates and 2 controllers for the normal and modal components. I already have images on my HTML and I just need to pass the same data returned from the factory into the ModalInstanceController so that I can show description on image-click.

Do I need to call the factory method to get the data inside the
  ModalInstanceController or pass the data from controller (which is an
  array that contains promise with resolve). The issue is I passed the
  ietms with resolve but can't extract it inside ModalInstanceController as
  it's an array containing promise (in console it says 'value was evaluated just now' and I can't use .then() to an array.

My code structure is :

JSON Factory

(function() {
  angular
    .module('Brastlewark')
    .factory('GnomeFactory', GnomeFactory)

  function GnomeFactory($http) {
    let allGnomes = { getAllGnomes }

    function getAllGnomes() {
      const url = 'https://raw.githubusercontent.com/rrafols/mobile_test/master/data.json'
      return $http.get(url)
        .then(response => response.data.Brastlewark)
    }
    return allGnomes
  }
})()

Main Controller that opens modal-instance

(function() {
  angular
    .module('Brastlewark')
    .controller('DetailsController', DetailsController)

  function DetailsController(GnomeFactory, $log, $uibModal) {
    let vm = this

    GnomeFactory.getAllGnomes()
      .then((data) => {
        vm.gnomeList = data
        return vm.gnomeList
      })

    // opening modal window to trigger model instance controller to act
    vm.showModal = (index) => {
      $log.log(`Button with index ${index} was clicked !!`)
      let configModal = {
        animation: true,
        templateUrl: 'myModal.html',
        size: 'sm',
        controller: 'ModalController',
        resolve: {
          gnomeData: () => vm.gnomeList
        }
      }
      let modalInstance = $uibModal.open(configModal)
      modalInstance.result.then(console.log, console.log)
    }
  }
})()

ModalController

angular
  .module('Brastlewark')
  .controller('ModalController', ModalController)

function ModalController($scope, $uibModalInstance, $log, gnomeData) {

  $scope.gnomeList = gnomeData
  $scope.ok = function() {
    $uibModalInstance.close($scope)
  }
  $scope.cancel = () => {
    $uibModalInstance.dismiss('cancel')
  }
}

Template for both

          <button type="button" ng-click="vm.showModal($index)">

          </button>

NOTE: IT SHOWS MODAL AND INDEX OF IMAGE CLICKED... But doesn't receive the array.

Body:
Change your service to, (returning only API promise)

(function() {
  angular
    .module('Brastlewark')
    .factory('GnomeFactory', GnomeFactory)

  function GnomeFactory($http) {
    let allGnomes = { getAllGnomes }

    function getAllGnomes() {
      const url = 'https://raw.githubusercontent.com/rrafols/mobile_test/master/data.json'
      return $http.get(url)
    }
    return allGnomes
  }
})()

returning just an API promise return $http.get(url)

Now your controller, handle the promise returned from the service using then

(function() {
  angular
    .module('Brastlewark')
    .controller('DetailsController', DetailsController)

  function DetailsController(GnomeFactory, $log, $uibModal) {
    let vm = this

    GnomeFactory.getAllGnomes()
      .then((data) => {
        vm.gnomeList = data.data.Brastlewark
        return vm.gnomeList
      },(data) => {
       console.log('error')
      })

    // opening modal window to trigger model instance controller to act
    vm.showModal = (index) => {
      $log.log(`Button with index ${index} was clicked !!`)
      let configModal = {
        animation: true,
        templateUrl: 'myModal.html',
        size: 'sm',
        controller: 'ModalController',
        resolve: {
          gnomeData: () => vm.gnomeList
        }
      }
      let modalInstance = $uibModal.open(configModal)
      modalInstance.result.then(console.log, console.log)
    }
  }
})()


问:
Separate header and footer with MVC Codeigniter
I'm looking for a simple way to have the same header and footer displayed all the time whilst being able to switch out the main content area. I'm not sure how to achieve this with MVC.</p>

答:
You could create a master view.

views/master.php

```<code>$this->load->view('header');
echo $content;
$this->load->view('footer');
</code>```

And then create a base controller with a method to render the master view.  The content of the subview is loaded and passed to the master view.

libraries/MY_Controller.php

```<code>class MY_Controller extends Controller
{
    public function __construct()
    {
        parent::__construct();
    }

    public function master_view($content_view, $data)
    {
        $data['content'] = $this->load->view($content_view, $data, true);
        $this->load->view('master', $data);
    }
}
</code>```

Then extend this base controller and invoke the method of the base controller from your action methods.

controllers/items.php

```<code>class Items extends MY_Controller
{
    public function __construct()
    {
        parent::__construct();
    }

    public function index()
    {
        $data['items'] = $this->item_model->get_items();
        $this->master_view('items/index', $data);
    }
}
</code>```

It tends to be more DRY than loading the header and footer in each view.

Body:
You could create a master view.

views/master.php

$this->load->view('header');
echo $content;
$this->load->view('footer');

And then create a base controller with a method to render the master view.  The content of the subview is loaded and passed to the master view.

libraries/MY_Controller.php

class MY_Controller extends Controller
{
    public function __construct()
    {
        parent::__construct();
    }

    public function master_view($content_view, $data)
    {
        $data['content'] = $this->load->view($content_view, $data, true);
        $this->load->view('master', $data);
    }
}

Then extend this base controller and invoke the method of the base controller from your action methods.

controllers/items.php

class Items extends MY_Controller
{
    public function __construct()
    {
        parent::__construct();
    }

    public function index()
    {
        $data['items'] = $this->item_model->get_items();
        $this->master_view('items/index', $data);
    }
}

It tends to be more DRY than loading the header and footer in each view.


问:
VBA error 1004 - Runtime
I'm having a little 'error 1004' with my project and I can't find a way to correct it "properly".

I get an error when I use this code :

```<code>If Total_account = "OUI" Or (Total_account = "NON" And Range(Cfin).Row = "2") Then GoTo fin
</code>```

I am getting the error when the first condition is met:

```<code>If Total_account = "OUI"
</code>```

When I have Total_account = "NON" and Range(Cfin).Row = 2, no error.

The only way to fix I found was to do it like that, but it does not look good :

```<code>If Total_account = "OUI" Then GoTo fin
If (Total_account = "NON" And Range(Cfin).Row = "2") Then GoTo fin
</code>```

I also read the Microsoft support for this error but I don't get it : https://support.microsoft.com/fr-fr/help/963259/runtime-error-1004-method-range-of-object-global-failed

Could you help me understand/ find a way to correct this?
The error screenshot is attached to my post.

Thanks in advance !

Jean

答:
Its always good to put workSheet.Range(Cfin).Row instead of Range(Cfin).Row as Perhaps your code is behind Sheet1, so when you change the focus to Sheet2 the objects cannot be found issue will happen.

Please try below code.

```<code>Sub your_sub

Dim workSheet As Worksheet
Set workSheet = ActiveWorkbook.Sheets("Sheet1") 'guessing your looking at Sheet1

Dim Cfin As String
Cfin = "$C$2"

If Total_account = "OUI" Or (Total_account = "NON" And workSheet.(Cfin).Row = "2") Then GoTo fin

MsgBox "no" 'your code

fin:

MsgBox "yes" ' your code

End Sub
</code>```

Title: VBA error 1004 - Runtime

Body:
I'm having a little 'error 1004' with my project and I can't find a way to correct it "properly".

I get an error when I use this code :

If Total_account = "OUI" Or (Total_account = "NON" And Range(Cfin).Row = "2") Then GoTo fin

I am getting the error when the first condition is met:

If Total_account = "OUI"

When I have Total_account = "NON" and Range(Cfin).Row = 2, no error.

The only way to fix I found was to do it like that, but it does not look good :

If Total_account = "OUI" Then GoTo fin
If (Total_account = "NON" And Range(Cfin).Row = "2") Then GoTo fin

I also read the Microsoft support for this error but I don't get it : https://support.microsoft.com/fr-fr/help/963259/runtime-error-1004-method-range-of-object-global-failed

Could you help me understand/ find a way to correct this?
The error screenshot is attached to my post.

Thanks in advance !

Jean

Body:
Its always good to put workSheet.Range(Cfin).Row instead of Range(Cfin).Row as Perhaps your code is behind Sheet1, so when you change the focus to Sheet2 the objects cannot be found issue will happen.

Please try below code.

Sub your_sub

Dim workSheet As Worksheet
Set workSheet = ActiveWorkbook.Sheets("Sheet1") 'guessing your looking at Sheet1

Dim Cfin As String
Cfin = "$C$2"

If Total_account = "OUI" Or (Total_account = "NON" And workSheet.(Cfin).Row = "2") Then GoTo fin

MsgBox "no" 'your code

fin:

MsgBox "yes" ' your code

End Sub


问:
Gson Unicode characters conversion to Unicode character codes
Check out my code below. I have a JSON string which contains Unicode character codes. I convert it to my Java object and then convert it back to JSON string. However, you can see that input and output JSON strings don't match. Is it possible to convert my object to original JSON string using Gson? I want outputJson to be the same as inputJson.

```<code>static class Book {
    String description;
}

public static void test() {
    Gson gson = new Gson();

    String inputJson = "{\"description\":\"Tikrovi\\u0161kai para\\u0161ytas k\\u016brinys\"}";
    Book book = gson.fromJson(inputJson, Book.class);
    String outputJson = gson.toJson(book);

    System.out.println(inputJson);
    System.out.println(outputJson);
    // Prints:
    // {"description":"Tikrovi\u0161kai para\u0161ytas k\u016brinys"}
    // {"description":"Tikroviškai parašytas kūrinys"}
}
</code>```

答:
Unfortunately, Gson does not seem to support it. All JSON input/output is concentrated in Gson (as of 2.8.0) JsonReader and JsonWriter respectively. JsonReader can read Unicode escapes using its private readEscapeCharacter method. However, unlike JsonReader, JsonWriter simply writes a string to the backing Writer instance making no character corrections for characters above 127 except \u2028 and

\u2029. The only thing, probably, you can do here is writing a custom escaping Writer so that you could emit Unicode escapes.

final class EscapedWriter
        extends Writer {

    private static final char[] hex = {
            '0', '1', '2', '3',
            '4', '5', '6', '7',
            '8', '9', 'a', 'b',
            'c', 'd', 'e', 'f'
    };

    private final Writer writer;

    // I/O components are usually implemented in not thread-safe manner
    // so we can save some time on constructing a single UTF-16 escape
    private final char[] escape = { '\\', 'u', 0, 0, 0, 0 };

    EscapedWriter(final Writer writer) {
        this.writer = writer;
    }

    // This implementation is not very efficient and is open for enhancements:
    // * constructing a single "normalized" buffer character array so that it could be passed to the downstream writer
    //   rather than writing characters one by one
    // * etc...
    @Override
    public void write(final char[] buffer, final int offset, final int length)
            throws IOException {
        for ( int i = offset; i < length; i++ ) {
            final int ch = buffer[i];
            if ( ch < 128 ) {
                writer.write(ch);
            } else {
                escape[2] = hex[(ch & 0xF000) >> 12];
                escape[3] = hex[(ch & 0x0F00) >> 8];
                escape[4] = hex[(ch & 0x00F0) >> 4];
                escape[5] = hex[ch & 0x000F];
                writer.write(escape);
            }
        }
    }

    @Override
    public void flush()
            throws IOException {
        writer.flush();
    }

    @Override
    public void close()
            throws IOException {
        writer.close();
    }

    // Some java.io.Writer subclasses may use java.lang.Object.toString() to materialize their accumulated state by design
    // so it has to be overridden and forwarded as well
    @Override
    public String toString() {
        return writer.toString();
    }

}
```

<p>This writer is NOT well-tested, and does not respect <code>\u2028</code> and <code>\u2029</code>. And then just configure the output destination when invoking the <code>toJson</code> method:</p>

<pre class="lang-java prettyprint-override"><code>final String input = "{\"description\":\"Tikrovi\\u0161kai para\\u0161ytas k\\u016brinys\"}";
final Book book = gson.fromJson(input, Book.class);
final Writer output = new EscapedWriter(new StringWriter());
gson.toJson(book, output);
System.out.println(input);
System.out.println(output);
</code>```

Output:

{"description":"Tikrovi\u0161kai para\u0161ytas k\u016brinys"}

  {"description":"Tikrovi\u0161kai para\u0161ytas k\u016brinys"}

It's an interesting problem, and you might also raise an issue on google/gson to add a string writing configuration option - or at least to get some comments from the development team. I do believe they are very aware of such a behavior and made it work like that by design, however they could also shed some light on it (the only one I could think of now is that currently they have some more performance not making an additional transformation before writing a string, but it's a weak guess though).

Body:
Check out my code below. I have a JSON string which contains Unicode character codes. I convert it to my Java object and then convert it back to JSON string. However, you can see that input and output JSON strings don't match. Is it possible to convert my object to original JSON string using Gson? I want outputJson to be the same as inputJson.

static class Book {
    String description;
}

public static void test() {
    Gson gson = new Gson();

    String inputJson = "{\"description\":\"Tikrovi\\u0161kai para\\u0161ytas k\\u016brinys\"}";
    Book book = gson.fromJson(inputJson, Book.class);
    String outputJson = gson.toJson(book);

    System.out.println(inputJson);
    System.out.println(outputJson);
    // Prints:
    // {"description":"Tikrovi\u0161kai para\u0161ytas k\u016brinys"}
    // {"description":"Tikroviškai parašytas kūrinys"}
}

Body:
Unfortunately, Gson does not seem to support it. All JSON input/output is concentrated in Gson (as of 2.8.0) JsonReader and JsonWriter respectively. JsonReader can read Unicode escapes using its private readEscapeCharacter method. However, unlike JsonReader, JsonWriter simply writes a string to the backing Writer instance making no character corrections for characters above 127 except \u2028 and

\u2029. The only thing, probably, you can do here is writing a custom escaping Writer so that you could emit Unicode escapes.

final class EscapedWriter
        extends Writer {

    private static final char[] hex = {
            '0', '1', '2', '3',
            '4', '5', '6', '7',
            '8', '9', 'a', 'b',
            'c', 'd', 'e', 'f'
    };

    private final Writer writer;

    // I/O components are usually implemented in not thread-safe manner
    // so we can save some time on constructing a single UTF-16 escape
    private final char[] escape = { '\\', 'u', 0, 0, 0, 0 };

    EscapedWriter(final Writer writer) {
        this.writer = writer;
    }

    // This implementation is not very efficient and is open for enhancements:
    // * constructing a single "normalized" buffer character array so that it could be passed to the downstream writer
    //   rather than writing characters one by one
    // * etc...
    @Override
    public void write(final char[] buffer, final int offset, final int length)
            throws IOException {
        for ( int i = offset; i < length; i++ ) {
            final int ch = buffer[i];
            if ( ch < 128 ) {
                writer.write(ch);
            } else {
                escape[2] = hex[(ch & 0xF000) >> 12];
                escape[3] = hex[(ch & 0x0F00) >> 8];
                escape[4] = hex[(ch & 0x00F0) >> 4];
                escape[5] = hex[ch & 0x000F];
                writer.write(escape);
            }
        }
    }

    @Override
    public void flush()
            throws IOException {
        writer.flush();
    }

    @Override
    public void close()
            throws IOException {
        writer.close();
    }

    // Some java.io.Writer subclasses may use java.lang.Object.toString() to materialize their accumulated state by design
    // so it has to be overridden and forwarded as well
    @Override
    public String toString() {
        return writer.toString();
    }

}

This writer is NOT well-tested, and does not respect \u2028 and \u2029. And then just configure the output destination when invoking the toJson method:

final String input = "{\"description\":\"Tikrovi\\u0161kai para\\u0161ytas k\\u016brinys\"}";
final Book book = gson.fromJson(input, Book.class);
final Writer output = new EscapedWriter(new StringWriter());
gson.toJson(book, output);
System.out.println(input);
System.out.println(output);

Output:

{"description":"Tikrovi\u0161kai para\u0161ytas k\u016brinys"}

  {"description":"Tikrovi\u0161kai para\u0161ytas k\u016brinys"}

It's an interesting problem, and you might also raise an issue on google/gson to add a string writing configuration option - or at least to get some comments from the development team. I do believe they are very aware of such a behavior and made it work like that by design, however they could also shed some light on it (the only one I could think of now is that currently they have some more performance not making an additional transformation before writing a string, but it's a weak guess though).


问:
How to read data from more than 1 text files using regular Expression in java?
Given more than one files in a directory

I have to read only the text files from a directory and print all the information inside it.

My Implementation:

```<code>File filepath=new File("c:/test");
Pattern p=Pattern.compile("[a-zA-Z0-9_]+.txt");
String s1[]=filepath.list();
for (int i=0;i<s1.length;i++){
 Matcher m=p.matcher(s1[i]);
 if(m.find()&&m.equals(s1));
 System.out.println(s1[i]);
 File file1=new File(s1[i]);
 readFromFile(file1);
 }

 static void readFromFile(File filename) throws IOException{
 String line = null;
 FileReader fileReader = new FileReader(filename); //1

 BufferedReader bufferedReader = new BufferedReader(fileReader);
 while((line = bufferedReader.readLine()) != null) {
 System.out.println(line);
    }
    bufferedReader.close();
    fileReader.close();

}
</code>```

While running the above program i am getting NullPointer at position 1 as indicated in the code.

Though I know the approaches using fileList method in file class I can read all the files in a directory and I also know that i can use endsWith method in String classto read only text file.

But I wanted to know how using above implementation I can read all the data inside the text files.

Can anyone guide me on this how to correctly handle the above approach.

答:
You probably have a problem while reading the file.

To understand what problem exactly do you have - "file not found" or maybe "insufficient read permissions" - always catch and print the exception when opening files for reading or writing (and also for reading directories):

```<code>public static void main (String[] args) {
    readFromFile(new File("nonexistant.txt"));
}

public static void readFromFile(File file) {
    try (FileReader fileReader = new FileReader(file);
         BufferedReader bufferedReader = new BufferedReader(fileReader)) {
        for (String line = bufferedReader.readLine();
             line != null;
             line = bufferedReader.readLine()) {

            System.out.println(line);
        }
    } catch (Exception ex) {
            System.err.print(ex);
    }
}
</code>```

Here it prints the reason:

```<code>java.io.FileNotFoundException: nonexistant.txt (No such file or directory)
</code>```

Once you have fixed this issue, move to the file parsing.

Body:
Given more than one files in a directory

I have to read only the text files from a directory and print all the information inside it.

My Implementation:

File filepath=new File("c:/test");
Pattern p=Pattern.compile("[a-zA-Z0-9_]+.txt");
String s1[]=filepath.list();
for (int i=0;i<s1.length;i++){
 Matcher m=p.matcher(s1[i]);
 if(m.find()&&m.equals(s1));
 System.out.println(s1[i]);
 File file1=new File(s1[i]);
 readFromFile(file1);
 }

 static void readFromFile(File filename) throws IOException{
 String line = null;
 FileReader fileReader = new FileReader(filename); //1

 BufferedReader bufferedReader = new BufferedReader(fileReader);
 while((line = bufferedReader.readLine()) != null) {
 System.out.println(line);
    }
    bufferedReader.close();
    fileReader.close();

}

While running the above program i am getting NullPointer at position 1 as indicated in the code.

Though I know the approaches using fileList method in file class I can read all the files in a directory and I also know that i can use endsWith method in String classto read only text file.

But I wanted to know how using above implementation I can read all the data inside the text files.

Can anyone guide me on this how to correctly handle the above approach.

Body:
You probably have a problem while reading the file.

To understand what problem exactly do you have - "file not found" or maybe "insufficient read permissions" - always catch and print the exception when opening files for reading or writing (and also for reading directories):

public static void main (String[] args) {
    readFromFile(new File("nonexistant.txt"));
}

public static void readFromFile(File file) {
    try (FileReader fileReader = new FileReader(file);
         BufferedReader bufferedReader = new BufferedReader(fileReader)) {
        for (String line = bufferedReader.readLine();
             line != null;
             line = bufferedReader.readLine()) {

            System.out.println(line);
        }
    } catch (Exception ex) {
            System.err.print(ex);
    }
}

Here it prints the reason:

java.io.FileNotFoundException: nonexistant.txt (No such file or directory)

Once you have fixed this issue, move to the file parsing.