问:
How to Search an array of object in Swift 3
I am trying to search an array of objects that I'm pulling from a Firebase database. The data is loading fine but when I try to search nothing shows. I've only been learning iOS/Swift development for about 6 weeks now. Below is code I have.

The app was crashing as soon as I clicked into the search bar.
I managed to get the search code to stop crashing but I'm getting no returns in my search. Is this because I'm search a Firebase database? I'm loading the firebase data into an array so it should be searchable right?

```<code>import UIKit
import Firebase

class ServicesTableViewController: UITableViewController, UISearchResultsUpdating {

    var services = [Service]()
    var filteredSearch = [Service]()

    var searchController: UISearchController!
    var resultsController = UITableViewController()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Turn this back on to cache data
        FIRDatabase.database().persistenceEnabled = true

        fetchServices()

        self.resultsController.tableView.dataSource = self
        self.resultsController.tableView.delegate = self

        self.searchController = UISearchController(searchResultsController: self.resultsController)
        self.tableView.tableHeaderView = searchController.searchBar
        self.searchController.searchResultsUpdater = self

        searchController.dimsBackgroundDuringPresentation = false
        searchController.searchBar.placeholder = "Search services..."
        searchController.searchBar.tintColor = UIColor.white
        searchController.searchBar.barTintColor = UIColor(red: 164.0/255.0, green: 45.0/255.0, blue: 9.0/255.0, alpha: 1.0)

        navigationItem.backBarButtonItem = UIBarButtonItem(title: " ", style: .plain, target: nil, action: nil)
    }

    // MARK: - Search Controller

    func filterContent(for searchText: String) {
        filteredSearch = services.filter({ (service) -> Bool in
            if let name = service.name {
                let isMatch = name.localizedCaseInsensitiveContains(searchText)
                return isMatch
            }

            return false
        })
    }

    func updateSearchResults(for searchController: UISearchController) {
        if let searchText = searchController.searchBar.text {
            filterContent(for: searchText)
            tableView.reloadData()
        }
    }

    // MARK: Database connection and data fetch

    func fetchServices () {

        FIRDatabase.database().reference().child("services").observe(.childAdded, with: { (snapshot) in

            print(snapshot)

            if let dictionary = snapshot.value as? [String: AnyObject] {

                let service = Service()
                service.setValuesForKeys(dictionary)

                self.services.append(service)

                self.tableView.reloadData()

            }

        })

    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {

        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if searchController.isActive {
            return filteredSearch.count
        } else {
            return services.count
        }
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellIdentifier = "Cell"
        let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! ServicesTableViewCell

        // Check to see if the user is searching or not
        let service = (searchController.isActive) ? filteredSearch[indexPath.row] : services[indexPath.row]

//        let service = services[indexPath.row]
        cell.programLabel.text = service.name
        cell.programLabel.font = UIFont(name: "Avenir-Medium", size: 18.0)
        cell.programLabel.textColor = UIColor(red: 0.0/255.0, green: 0.0/255.0, blue: 0.0/255.0, alpha: 1.0)
        cell.branchLabel.text = service.branch
        cell.branchLabel.font = UIFont(name: "Avenir-Medium", size: 14.0)
        cell.branchLabel.textColor = UIColor(red: 90.0/255.0, green: 86.0/255.0, blue: 92.0/255.0, alpha: 1.0)
        cell.servicesLabel.text = service.shortDesc
        cell.servicesLabel.font = UIFont(name: "Avenir-Light", size: 14.0)
        cell.servicesLabel.textColor = UIColor(red: 164.0/255.0, green: 45.0/255.0, blue: 9.0/255.0, alpha: 1.0)
        cell.thumbnailImageView.image = UIImage(named: service.imageName!)

        return cell
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "showServicesDetail" {
            if let indexPath = tableView.indexPathForSelectedRow {
                let destinationController = segue.destination as! ServicesDetailViewController
                destinationController.services = services[indexPath.row]
            }
        }
    }

}
</code>```

Here's my current storyboard. just two views and a nav controller,
enter image description here

答:
I have an array of object(codeDataObjectList)

```<code>    import Foundation

    class CodeDataObject:NSObject{

        private var collections:[String]?
        private var code: String?
        private var shortDescription: String?
        private var longDescription: String?
        private var sectionName: String?
        private var specialtyName: String?
        private var chapterName: String?
        private var isStarred: Bool?
        private var starredListIndex:Int?
        private var type: String?
        .
        .
        .
</code>```

below code can search a text in each object and you can update table data with filteredTableData

```<code>func  updateSearchResults(for searchController: UISearchController) {
        filteredTableData.removeAll(keepingCapacity: false)
        let searchPredicate = NSPredicate(format: "code CONTAINS[c] %@ OR longDescription CONTAINS[c] %@ OR shortDescription CONTAINS[c] %@", searchController.searchBar.text!, searchController.searchBar.text!, searchController.searchBar.text!)
        let array = (self.codeDataObjectList as NSArray).filtered(using: searchPredicate)
        filteredTableData = array as! [CodeDataObject]
        self.tableView.reloadData()
    }
</code>```

Body:
I am trying to search an array of objects that I'm pulling from a Firebase database. The data is loading fine but when I try to search nothing shows. I've only been learning iOS/Swift development for about 6 weeks now. Below is code I have.

The app was crashing as soon as I clicked into the search bar.
I managed to get the search code to stop crashing but I'm getting no returns in my search. Is this because I'm search a Firebase database? I'm loading the firebase data into an array so it should be searchable right?

import UIKit
import Firebase

class ServicesTableViewController: UITableViewController, UISearchResultsUpdating {

    var services = [Service]()
    var filteredSearch = [Service]()

    var searchController: UISearchController!
    var resultsController = UITableViewController()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Turn this back on to cache data
        FIRDatabase.database().persistenceEnabled = true

        fetchServices()

        self.resultsController.tableView.dataSource = self
        self.resultsController.tableView.delegate = self

        self.searchController = UISearchController(searchResultsController: self.resultsController)
        self.tableView.tableHeaderView = searchController.searchBar
        self.searchController.searchResultsUpdater = self

        searchController.dimsBackgroundDuringPresentation = false
        searchController.searchBar.placeholder = "Search services..."
        searchController.searchBar.tintColor = UIColor.white
        searchController.searchBar.barTintColor = UIColor(red: 164.0/255.0, green: 45.0/255.0, blue: 9.0/255.0, alpha: 1.0)

        navigationItem.backBarButtonItem = UIBarButtonItem(title: " ", style: .plain, target: nil, action: nil)
    }

    // MARK: - Search Controller

    func filterContent(for searchText: String) {
        filteredSearch = services.filter({ (service) -> Bool in
            if let name = service.name {
                let isMatch = name.localizedCaseInsensitiveContains(searchText)
                return isMatch
            }

            return false
        })
    }

    func updateSearchResults(for searchController: UISearchController) {
        if let searchText = searchController.searchBar.text {
            filterContent(for: searchText)
            tableView.reloadData()
        }
    }

    // MARK: Database connection and data fetch

    func fetchServices () {

        FIRDatabase.database().reference().child("services").observe(.childAdded, with: { (snapshot) in

            print(snapshot)

            if let dictionary = snapshot.value as? [String: AnyObject] {

                let service = Service()
                service.setValuesForKeys(dictionary)

                self.services.append(service)

                self.tableView.reloadData()

            }

        })

    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {

        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if searchController.isActive {
            return filteredSearch.count
        } else {
            return services.count
        }
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellIdentifier = "Cell"
        let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! ServicesTableViewCell

        // Check to see if the user is searching or not
        let service = (searchController.isActive) ? filteredSearch[indexPath.row] : services[indexPath.row]

//        let service = services[indexPath.row]
        cell.programLabel.text = service.name
        cell.programLabel.font = UIFont(name: "Avenir-Medium", size: 18.0)
        cell.programLabel.textColor = UIColor(red: 0.0/255.0, green: 0.0/255.0, blue: 0.0/255.0, alpha: 1.0)
        cell.branchLabel.text = service.branch
        cell.branchLabel.font = UIFont(name: "Avenir-Medium", size: 14.0)
        cell.branchLabel.textColor = UIColor(red: 90.0/255.0, green: 86.0/255.0, blue: 92.0/255.0, alpha: 1.0)
        cell.servicesLabel.text = service.shortDesc
        cell.servicesLabel.font = UIFont(name: "Avenir-Light", size: 14.0)
        cell.servicesLabel.textColor = UIColor(red: 164.0/255.0, green: 45.0/255.0, blue: 9.0/255.0, alpha: 1.0)
        cell.thumbnailImageView.image = UIImage(named: service.imageName!)

        return cell
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "showServicesDetail" {
            if let indexPath = tableView.indexPathForSelectedRow {
                let destinationController = segue.destination as! ServicesDetailViewController
                destinationController.services = services[indexPath.row]
            }
        }
    }

}

Here's my current storyboard. just two views and a nav controller,
enter image description here

Body:
I have an array of object(codeDataObjectList)

    import Foundation

    class CodeDataObject:NSObject{

        private var collections:[String]?
        private var code: String?
        private var shortDescription: String?
        private var longDescription: String?
        private var sectionName: String?
        private var specialtyName: String?
        private var chapterName: String?
        private var isStarred: Bool?
        private var starredListIndex:Int?
        private var type: String?
        .
        .
        .

below code can search a text in each object and you can update table data with filteredTableData

func  updateSearchResults(for searchController: UISearchController) {
        filteredTableData.removeAll(keepingCapacity: false)
        let searchPredicate = NSPredicate(format: "code CONTAINS[c] %@ OR longDescription CONTAINS[c] %@ OR shortDescription CONTAINS[c] %@", searchController.searchBar.text!, searchController.searchBar.text!, searchController.searchBar.text!)
        let array = (self.codeDataObjectList as NSArray).filtered(using: searchPredicate)
        filteredTableData = array as! [CodeDataObject]
        self.tableView.reloadData()
    }


来源: stackexchange

问:
If statement doesn't check the condition for an excel cell value in c#
I have the code like above

```<code>if (worksheet.UsedRange.Cells[rowvalue,columnvalue].Value2.ToString() == "0")
    {
      Statement1
      Statement2
    }
</code>```

It doesn't  recognize the condition i think because it is number. The point is that in excel the number is stored as text.

I tried with .text but it doesn't check the condition anyway. If i put the same condition for a cell that contains text, like  if (worksheet.UsedRange.Cells[rowvalue,columnvalue].Text == "sometext") it recognize the condition.
What can i do at this point? Any Idea?

答: Perhaps, the cell with zero value is represented somehow different. You can just check with Debugger and compare against the result. Regards.</p>

ContentLicense: CC BY-SA 3.0

Body:
I have the code like above

if (worksheet.UsedRange.Cells[rowvalue,columnvalue].Value2.ToString() == "0")
    {
      Statement1
      Statement2
    }

It doesn't  recognize the condition i think because it is number. The point is that in excel the number is stored as text.

I tried with .text but it doesn't check the condition anyway. If i put the same condition for a cell that contains text, like  if (worksheet.UsedRange.Cells[rowvalue,columnvalue].Text == "sometext") it recognize the condition.
What can i do at this point? Any Idea?


问:
How to implement horizontall scalability using NodeJs
So, I've web application which structure is based on this file structure: https://scotch.io/tutorials/setting-up-a-mean-stack-single-page-application .
My app also has a connection to mongoDB on Mlab.

what my app does:

allows users to login/signup;

retrieves data from mlab;

retrieved data can be rated by users;

retrieved data can be deleted by admin;

users can add data to db (data is training plans);

Now I need to make my app horizontally scalable, but I am a bit lost here:

•Sine I assume there i no real-time activities I shoudn't need something like socket.io?
•Should I add some sort of MQ (rabbitMQ, ZMQ, etc.): If so, perhaps any pointers on how to, because most of the examples just use simple text messages.

•I am quite sure I would need some load balancer. Nginx, HaProxy... I probably should change my express server setup to listen to multiple ports first, is that right?

Or am I completely wrong about this?

P.S.: Hope this isn't too broad question.

答:
Different needs require different approaches :)

These can vary according to your needs. Not every scalable application has to have them.If you want the application to be asynchronous, you can take all the requests in a queue and return to the client instantly.You may then need a push mechanism to notify the client that the operation is over. (Socket.io, RabbitMQ etc)

Of course you will need a reverse proxy to distribute requests to different servers load balanced or workload basis (HAProxy etc.)

The first thing you need to pay attention to when you want to scale the application is to have a stateless structure.Or get them out of the process.(For example session, cache, file server)The second thing you need to be aware of is the authentication phase.A client that logged in from ServerA may encounter "unauthorized" on ServerB on subsequent requests.You should also think about the resources used by the application.While these resources serve a single server, they will begin to respond to millions of requests from five to ten servers simultaneously.There are things like monitoring instances.And a lot of things like that.

These are the things you should really think about :)


问:
Binding XAML to Dictionary
Consider the following code:

```<code>public class Person {
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
}

public class HealthInfo {
public int BMI { get; set; }
public int HeartRate { get; set; }
public string DietPlan { get; set; }
}

Dictionary<Person, HealthInfo> myPersonInfo = new Dictionary<Person, HealthInfo>();

myPersonInfo.Add( new Person { Id = 1, Name = "Name1", Surname = "Surname1" }, new HealthInfo { BMI = 1, DietPlan = "Banting", HeartRate = 20 } );
myPersonInfo.Add( new Person { Id = 1, Name = "Name2", Surname = "Surname2" }, new HealthInfo { BMI = 1, DietPlan = "Banting", HeartRate = 20 } );
myPersonInfo.Add( new Person { Id = 1, Name = "Name3", Surname = "Surname3" }, new HealthInfo { BMI = 1, DietPlan = "Banting", HeartRate = 20 } );
myPersonInfo.Add( new Person { Id = 1, Name = "Name4", Surname = "Surname4" }, new HealthInfo { BMI = 1, DietPlan = "Banting", HeartRate = 20 } );
</code>```

I am trying to bind to this Dictionary(myPersonInfo ) from my xaml
For each person a tab gets created, where the tab Header will be the name of the person and then the content of that tab will display the HealtInfo.

I having dificulties binding to this dictionary in my XAML

I have the following:

```<code><TabControl ItemsSource="{Binding myPersonInfo.Keys}" SelectedIndex="0">
                <TabControl.ItemTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding Path=Name}"/>
                    </DataTemplate>
                </TabControl.ItemTemplate>
                <TabControl.ContentTemplate>
                   <DataTemplate>
                       <TextBlock Text="{Binding Path=Key.Value.BMI}"/>
                   </DataTemplate>
                </TabControl.ContentTemplate>
</TabControl>
</code>```

How do I use the properties of the Key(Person) for the ItemTemplate
and
How do I use the properties of the Value(HealtInfo) for the ContentTemplate of the current Key?

答:
You need to change bindings in xaml.

```<code><TabControl ItemsSource="{Binding myPersonInfo}" SelectedIndex="0">
        <TabControl.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Path=Key.Name}"/>
            </DataTemplate>
        </TabControl.ItemTemplate>
        <TabControl.ContentTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Value.BMI}"/>
            </DataTemplate>
        </TabControl.ContentTemplate>
    </TabControl>
</code>```

Also, myPersonInfo should be a property. So declare it like this:

```<code>public Dictionary<Person, HealthInfo> myPersonInfo { get; set; }
</code>```

Although this code will work, consider refactoring your models in order to make it cleaner.

Title: Binding XAML to Dictionary

Body:
Consider the following code:

public class Person {
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
}

public class HealthInfo {
public int BMI { get; set; }
public int HeartRate { get; set; }
public string DietPlan { get; set; }
}

Dictionary<Person, HealthInfo> myPersonInfo = new Dictionary<Person, HealthInfo>();

myPersonInfo.Add( new Person { Id = 1, Name = "Name1", Surname = "Surname1" }, new HealthInfo { BMI = 1, DietPlan = "Banting", HeartRate = 20 } );
myPersonInfo.Add( new Person { Id = 1, Name = "Name2", Surname = "Surname2" }, new HealthInfo { BMI = 1, DietPlan = "Banting", HeartRate = 20 } );
myPersonInfo.Add( new Person { Id = 1, Name = "Name3", Surname = "Surname3" }, new HealthInfo { BMI = 1, DietPlan = "Banting", HeartRate = 20 } );
myPersonInfo.Add( new Person { Id = 1, Name = "Name4", Surname = "Surname4" }, new HealthInfo { BMI = 1, DietPlan = "Banting", HeartRate = 20 } );

I am trying to bind to this Dictionary(myPersonInfo ) from my xaml
For each person a tab gets created, where the tab Header will be the name of the person and then the content of that tab will display the HealtInfo.

I having dificulties binding to this dictionary in my XAML

I have the following:

<TabControl ItemsSource="{Binding myPersonInfo.Keys}" SelectedIndex="0">
                <TabControl.ItemTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding Path=Name}"/>
                    </DataTemplate>
                </TabControl.ItemTemplate>
                <TabControl.ContentTemplate>
                   <DataTemplate>
                       <TextBlock Text="{Binding Path=Key.Value.BMI}"/>
                   </DataTemplate>
                </TabControl.ContentTemplate>
</TabControl>

How do I use the properties of the Key(Person) for the ItemTemplate
and
How do I use the properties of the Value(HealtInfo) for the ContentTemplate of the current Key?

Body:
You need to change bindings in xaml.

<TabControl ItemsSource="{Binding myPersonInfo}" SelectedIndex="0">
        <TabControl.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Path=Key.Name}"/>
            </DataTemplate>
        </TabControl.ItemTemplate>
        <TabControl.ContentTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Value.BMI}"/>
            </DataTemplate>
        </TabControl.ContentTemplate>
    </TabControl>

Also, myPersonInfo should be a property. So declare it like this:

public Dictionary<Person, HealthInfo> myPersonInfo { get; set; }

Although this code will work, consider refactoring your models in order to make it cleaner.


问:
Linq select from database table where matching property from List
I have a List with records of following class which is something like this

```<code>  public class TestRecord
  {
     public int RecordsId{get;set;}
public string Name{get;set;}
-- and more such properties.

  }
</code>```

Now I have database table which I access from linq which contains RecordId column , values which will match RecordId value from above List.

```<code>  var result=from p in _context.Details
</code>```

however I am thinking I could do where/ contains on this linq query and provide it with a clause to match RecordId from a list

```<code> List<TestRecord> records -- this has let's say 100 records.
</code>```

Doing simply this does not work as linq can't join with generic List

```<code>    var finalresult = from p in context.details
                      join a in records on p.recordId equals a.recordId
</code>```

Any solutions for this using Linq?

答:
i got a solution in vb.net. I guess it will no problem for you to translate.

My Class TestRecord:

```<code>Public Class TestRecord
Private _RecordsID As Integer
Private _Name As String
Public Property RecordsID As Integer
    Get
        Return _RecordsID
    End Get
    Set(value As Integer)
        _RecordsID = value
    End Set

End Property
Public Property Name As String
    Get
        Return _Name
    End Get
    Set(value As String)
        _Name = value
    End Set

End Property
</code>```

End Class

Then, your main Sub (or anything else)

```<code>   Dim records As New List(Of TestRecord)
    Dim context As New DataTable()
    context.Columns.Add("DataTableRecordID")
    context.Columns.Add("Name")
    For i As Integer = 0 To 100
        records.Add(New TestRecord With {
            .RecordsID = i,
            .Name = "TestUser" & i.ToString()})

        context.Rows.Add(i, "TestUser" & i.ToString())
    Next

    Dim FinalResult = From p In context.AsEnumerable()
                      Join a In records.AsEnumerable() On p.Field(Of String)("DataTableRecordID") Equals a.RecordsID
</code>```

I got a little loop at the beginning to create some datarows and a datatable. I guess you use datatable (or Dataset) in your "context" => context.details example.

In the linq query, you can you set your field in the datatable and the generic list (TestRecord) will give you the needed column (a.RecordID) from itself.

Sry for my bad english x)

Body:
I have a List with records of following class which is something like this

  public class TestRecord
  {
     public int RecordsId{get;set;}
public string Name{get;set;}
-- and more such properties.

  }

Now I have database table which I access from linq which contains RecordId column , values which will match RecordId value from above List.

  var result=from p in _context.Details

however I am thinking I could do where/ contains on this linq query and provide it with a clause to match RecordId from a list

 List<TestRecord> records -- this has let's say 100 records.

Doing simply this does not work as linq can't join with generic List

    var finalresult = from p in context.details
                      join a in records on p.recordId equals a.recordId

Any solutions for this using Linq?

Body:
i got a solution in vb.net. I guess it will no problem for you to translate.

My Class TestRecord:

Public Class TestRecord
Private _RecordsID As Integer
Private _Name As String
Public Property RecordsID As Integer
    Get
        Return _RecordsID
    End Get
    Set(value As Integer)
        _RecordsID = value
    End Set

End Property
Public Property Name As String
    Get
        Return _Name
    End Get
    Set(value As String)
        _Name = value
    End Set

End Property

End Class

Then, your main Sub (or anything else)

   Dim records As New List(Of TestRecord)
    Dim context As New DataTable()
    context.Columns.Add("DataTableRecordID")
    context.Columns.Add("Name")
    For i As Integer = 0 To 100
        records.Add(New TestRecord With {
            .RecordsID = i,
            .Name = "TestUser" & i.ToString()})

        context.Rows.Add(i, "TestUser" & i.ToString())
    Next

    Dim FinalResult = From p In context.AsEnumerable()
                      Join a In records.AsEnumerable() On p.Field(Of String)("DataTableRecordID") Equals a.RecordsID

I got a little loop at the beginning to create some datarows and a datatable. I guess you use datatable (or Dataset) in your "context" => context.details example.

In the linq query, you can you set your field in the datatable and the generic list (TestRecord) will give you the needed column (a.RecordID) from itself.

Sry for my bad english x)


问:
Mysql Query to Merge Two Condition Into One Row
I just get confused. Already tried to search this whole site or google but didn't find the 'nearest' solution.

Ok let's say I have this table structure.

```<code>id date       finger_id finger_time is_enter
1  2017-03-30  2          09:00       1
2  2017-03-30  2          17:13       0
3  2017-03-31  4          09:10       1
4  2017-03-31  3          09:01       1
5. 2017-03-31  3          17:00       0
</code>```

I want to make the table to be like below.

```<code>date       finger_id  enter_time  exit_time
2017-03-30   2        09:00       17:13
2017-03-30   4        09:10
2017-03-31   3        09:10       17:00
</code>```

I have made sql statement but it turns like this.

```<code>date       finger_id  enter_time   exit_time
2017-03-30  2         09:00
2017-03-30  2                       17:13
2017-03-31  4         09:10
2017-03-31  3         09:01
2017-03-31  3                       17:00
</code>```

I just want to know how to merge the is_enter 1 with is_enter 0 on the same date by the finger_id column.

Here's my sql query for the reference.

```<code>SELECT *
FROM `tbl_fingerprint`
    LEFT JOIN `tbl_employee` ON `tbl_employee`.`fingerprint_id`=`tbl_fingerprint`.`fingerprint_id`
    LEFT JOIN `tbl_position` ON `tbl_position`.`position_id`=`tbl_employee`.`position_id`
WHERE `fingerprint_date` >= '2017-03-01'
AND `fingerprint_date` <= '2017-04-01'
GROUP BY `tbl_fingerprint`.`fingerprint_id`,
         `tbl_fingerprint`.`fingerprint_date`,
         `tbl_fingerprint`.`is_enter`
ORDER BY `fingerprint_date` ASC LIMIT 30
</code>```

Thanks for your help guys.

答:
```<code>SELECT * FROM `tbl_fingerprint`
LEFT JOIN `tbl_employee` ON `tbl_employee`.`fingerprint_id`=`tbl_fingerprint`.`fingerprint_id`
LEFT JOIN `tbl_position` ON `tbl_position`.`position_id`=`tbl_employee`.`position_id`
LEFT JOIN (SELECT * FROM tbl_fingerprint WHERE is_enter = 0) a
    ON a.finger_id = tbl_fingerprint.finger_id AND a.date = tbl_fingerprint.date
WHERE `fingerprint_date` >= '2017-03-01' AND `fingerprint_date` <= '2017-04-01' AND tbl_fingerprint.is_enter = 1
GROUP BY `tbl_fingerprint`.`fingerprint_id`, `tbl_fingerprint`.`fingerprint_date`, `tbl_fingerprint`.`is_enter`
ORDER BY `fingerprint_date` ASC LIMIT 30
</code>```

Body:
I just get confused. Already tried to search this whole site or google but didn't find the 'nearest' solution.

Ok let's say I have this table structure.

id date       finger_id finger_time is_enter
1  2017-03-30  2          09:00       1
2  2017-03-30  2          17:13       0
3  2017-03-31  4          09:10       1
4  2017-03-31  3          09:01       1
5. 2017-03-31  3          17:00       0

I want to make the table to be like below.

date       finger_id  enter_time  exit_time
2017-03-30   2        09:00       17:13
2017-03-30   4        09:10
2017-03-31   3        09:10       17:00

I have made sql statement but it turns like this.

date       finger_id  enter_time   exit_time
2017-03-30  2         09:00
2017-03-30  2                       17:13
2017-03-31  4         09:10
2017-03-31  3         09:01
2017-03-31  3                       17:00

I just want to know how to merge the is_enter 1 with is_enter 0 on the same date by the finger_id column.

Here's my sql query for the reference.

SELECT *
FROM `tbl_fingerprint`
    LEFT JOIN `tbl_employee` ON `tbl_employee`.`fingerprint_id`=`tbl_fingerprint`.`fingerprint_id`
    LEFT JOIN `tbl_position` ON `tbl_position`.`position_id`=`tbl_employee`.`position_id`
WHERE `fingerprint_date` >= '2017-03-01'
AND `fingerprint_date` <= '2017-04-01'
GROUP BY `tbl_fingerprint`.`fingerprint_id`,
         `tbl_fingerprint`.`fingerprint_date`,
         `tbl_fingerprint`.`is_enter`
ORDER BY `fingerprint_date` ASC LIMIT 30

Thanks for your help guys.


问:
Merge multiple group ids to form a single consolidated group id?
I have following dataset in pandas Dataframe.

```
group_id sub_group_id
0           0
0           1
1           0
2           0
2           1
2           2
3           0
3           0
```

But the I want to those group ids and form a consolidated group id

```
group_id sub_group_id consolidated_group_id
0            0                    0
0            1                    1
1            0                    2
2            0                    3
2            1                    4
2            2                    5
2            2                    5
3            0                    6
3            0                    6
```

Is there any generic or mathematical way to do it?

答:
You need convert values to tuples and then use factorize:

```<code>df['consolidated_group_id'] = pd.factorize(df.apply(tuple,axis=1))[0]
print (df)

   group_id  sub_group_id  consolidated_group_id
0         0             0                      0
1         0             1                      1
2         1             0                      2
3         2             0                      3
4         2             1                      4
5         2             2                      5
6         3             0                      6
7         3             0                      6
</code>```

Numpy solutions are a bit modify this answer - change ordering by [::-1] with selecting by [0] for return array (numpy.unique):

```<code>a = df.values

def unique_return_inverse_2D(a): # a is array
    a1D = a.dot(np.append((a.max(0)+1)[:0:-1].cumprod()[::-1],1))
    return np.unique(a1D, return_inverse=1)[::-1][0]

def unique_return_inverse_2D_viewbased(a): # a is array
    a = np.ascontiguousarray(a)
    void_dt = np.dtype((np.void, a.dtype.itemsize * np.prod(a.shape[1:])))
    return np.unique(a.view(void_dt).ravel(), return_inverse=1)[::-1][0]

df['consolidated_group_id'] = unique_return_inverse_2D(a)
df['consolidated_group_id1'] = unique_return_inverse_2D_viewbased(a)
print (df)
   group_id  sub_group_id  consolidated_group_id  consolidated_group_id1
0         0             0                      0                       0
1         0             1                      1                       1
2         1             0                      2                       2
3         2             0                      3                       3
4         2             1                      4                       4
5         2             2                      5                       5
6         3             0                      6                       6
7         3             0                      6                       6
</code>```

Body:
I have following dataset in pandas Dataframe.

group_id sub_group_id
0           0
0           1
1           0
2           0
2           1
2           2
3           0
3           0

But the I want to those group ids and form a consolidated group id

group_id sub_group_id consolidated_group_id
0            0                    0
0            1                    1
1            0                    2
2            0                    3
2            1                    4
2            2                    5
2            2                    5
3            0                    6
3            0                    6

Is there any generic or mathematical way to do it?

Body:
You need convert values to tuples and then use factorize:

df['consolidated_group_id'] = pd.factorize(df.apply(tuple,axis=1))[0]
print (df)

   group_id  sub_group_id  consolidated_group_id
0         0             0                      0
1         0             1                      1
2         1             0                      2
3         2             0                      3
4         2             1                      4
5         2             2                      5
6         3             0                      6
7         3             0                      6

Numpy solutions are a bit modify this answer - change ordering by [::-1] with selecting by [0] for return array (numpy.unique):

a = df.values

def unique_return_inverse_2D(a): # a is array
    a1D = a.dot(np.append((a.max(0)+1)[:0:-1].cumprod()[::-1],1))
    return np.unique(a1D, return_inverse=1)[::-1][0]

def unique_return_inverse_2D_viewbased(a): # a is array
    a = np.ascontiguousarray(a)
    void_dt = np.dtype((np.void, a.dtype.itemsize * np.prod(a.shape[1:])))
    return np.unique(a.view(void_dt).ravel(), return_inverse=1)[::-1][0]

df['consolidated_group_id'] = unique_return_inverse_2D(a)
df['consolidated_group_id1'] = unique_return_inverse_2D_viewbased(a)
print (df)
   group_id  sub_group_id  consolidated_group_id  consolidated_group_id1
0         0             0                      0                       0
1         0             1                      1                       1
2         1             0                      2                       2
3         2             0                      3                       3
4         2             1                      4                       4
5         2             2                      5                       5
6         3             0                      6                       6
7         3             0                      6                       6


问:
gridview asp.net
I have a gridview which was working fine with a small dataset in development. In production it has to bind to thousands of records, which is making it slower to load. Is there a way to improve performance, like retrieving the data during gridview pageindex changing?</p>

答: First and formost turn off ViewState.</p>

Title: gridview asp.net

Body: First and formost turn off ViewState.

ContentLicense: CC BY-SA 2.5


问:
android picker hide upper and lower value
```<code>numberPicker1= (NumberPicker) findViewById(R.id.numberPicker1);
final String genders[] = { "red", "blue", "green"};
    numberPicker1.setMinValue(0);
    numberPicker1.setMaxValue(genders.length - 1);
    numberPicker1.setDisplayedValues(genders);

    numberPicker1.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);;
    NumberPicker.OnValueChangeListener myValChangedListener = new NumberPicker.OnValueChangeListener() {
        @Override
        public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
            Toast.makeText(MainActivity.this,
                    "Value: " + genders[newVal], Toast.LENGTH_LONG).show();
        }
    };
</code>```

it disply random picker
how to hide previous one and next one value/string?

答:
Unfortunately I find out there is no way to do it so...
For them who want alternate solution....
I applied Viewpager instead of number picker to make it vertical i tried link and applied Onpagechangelistner.
Simply done...

Sorry for those who are looking for solve issue For Numbericker!!

Body:
numberPicker1= (NumberPicker) findViewById(R.id.numberPicker1);
final String genders[] = { "red", "blue", "green"};
    numberPicker1.setMinValue(0);
    numberPicker1.setMaxValue(genders.length - 1);
    numberPicker1.setDisplayedValues(genders);

    numberPicker1.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);;
    NumberPicker.OnValueChangeListener myValChangedListener = new NumberPicker.OnValueChangeListener() {
        @Override
        public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
            Toast.makeText(MainActivity.this,
                    "Value: " + genders[newVal], Toast.LENGTH_LONG).show();
        }
    };

it disply random picker
how to hide previous one and next one value/string?


问:
Invalid payload - Slack API JSON
I am using a Groovy script to send a POST using the Slack API, at present I am getting invalid_payload returned and I think this is most likely due to the formatting of my JSON. I know the Slack API expects it JSON with double quotes but I can't seem to be able to pass a variable into the JSON object:

```<code>SUCCESS_MESSAGE = '{"attachments": [{"color": "#2A9B3A", "author_name": ${DEV_NAME}, "title": "Build Status", "title_link": ${BUILD_URL}, "text": "Successful Build" }]}'
def response = ["curl", "-X", "POST", "-H", "Content-Type: application/json", "-d", "${SUCCESS_MESSAGE}", "https://hooks.slack.com/services/${SLACK_WEBHOOK}"].execute().text
</code>```

How should I correctly format my SUCCESS_MESSAGE var so I don't get the error?

答:
You need to quote your DEV_NAME and BUILD_URL variable expansions so the JSON string is valid.

Your whole string needs to be enclosed in " instead of ' so the variables are actually expanded

And you need to escape the " inside your string so they appear in your JSON string.

SUCCESS_MESSAGE = "{\"attachments\": [{\"color\": \"#2A9B3A\", \"author_name\": \"${DEV_NAME}\", \"title\": \"Build Status\", \"title_link\": \"${BUILD_URL}\", \"text\": \"Successful Build\" }]}"`

Alternatively you can generate the JSON in much nicer programmatic way. Which would be helpful if your notifications got a bit more complicated:

```<code>def notification = [
  attachments: [
    [
      color: "#2A9B3A",
      author_name: DEV_NAME,
      title: "Build Status",
      title_link: BUILD_URL,
      text: "Successful Build"
    ]
  ]
]

def response = ["curl", "-X", "POST", "-H", "Content-Type: application/json", "-d", JsonOutput.toJson(notification), "https://hooks.slack.com/services/${SLACK_WEBHOOK}"].execute().text
</code>```

ContentLicense: CC BY-SA 4.0

Title: Invalid payload - Slack API JSON

Body:
I am using a Groovy script to send a POST using the Slack API, at present I am getting invalid_payload returned and I think this is most likely due to the formatting of my JSON. I know the Slack API expects it JSON with double quotes but I can't seem to be able to pass a variable into the JSON object:

SUCCESS_MESSAGE = '{"attachments": [{"color": "#2A9B3A", "author_name": ${DEV_NAME}, "title": "Build Status", "title_link": ${BUILD_URL}, "text": "Successful Build" }]}'
def response = ["curl", "-X", "POST", "-H", "Content-Type: application/json", "-d", "${SUCCESS_MESSAGE}", "https://hooks.slack.com/services/${SLACK_WEBHOOK}"].execute().text

How should I correctly format my SUCCESS_MESSAGE var so I don't get the error?

Body:
You need to quote your DEV_NAME and BUILD_URL variable expansions so the JSON string is valid.

Your whole string needs to be enclosed in " instead of ' so the variables are actually expanded

And you need to escape the " inside your string so they appear in your JSON string.

SUCCESS_MESSAGE = "{\"attachments\": [{\"color\": \"#2A9B3A\", \"author_name\": \"${DEV_NAME}\", \"title\": \"Build Status\", \"title_link\": \"${BUILD_URL}\", \"text\": \"Successful Build\" }]}"`

Alternatively you can generate the JSON in much nicer programmatic way. Which would be helpful if your notifications got a bit more complicated:

def notification = [
  attachments: [
    [
      color: "#2A9B3A",
      author_name: DEV_NAME,
      title: "Build Status",
      title_link: BUILD_URL,
      text: "Successful Build"
    ]
  ]
]

def response = ["curl", "-X", "POST", "-H", "Content-Type: application/json", "-d", JsonOutput.toJson(notification), "https://hooks.slack.com/services/${SLACK_WEBHOOK}"].execute().text


问:
can i set logstash default elasticsearch mapping through elasticsearch-template.json
I use logstash + elasticsearch to collect syslog and want to set ttl for log ageing

I find a file named elasticsearch-template.json in the logstash,the path is logstash/logstash-1.4.2/lib/logstash/outputs/elasticsearch/elasticsearch-template.json

I add ttl info in the file like this:

```<code>{
  "template" : "logstash-*",
  "settings" : {
    "index.refresh_interval" : "5s"
  },
  "mappings" : {
    "_default_" : {
       "_all" : {"enabled" : true},
       "dynamic_templates" : [ {
         "string_fields" : {
           "match" : "*",
           "match_mapping_type" : "string",
           "mapping" : {
             "type" : "string", "index" : "analyzed", "omit_norms" : true,
               "fields" : {
                 "raw" : {"type": "string", "index" : "not_analyzed", "ignore_above" : 256}
               }
           }
         }
       } ],
        "_ttl": {
         "enabled": true,
         "default": "1d"
       },
       "properties" : {
         "@version": { "type": "string", "index": "not_analyzed" },
         "geoip"  : {
           "type" : "object",
             "dynamic": true,
             "path": "full",
             "properties" : {
               "location" : { "type" : "geo_point" }
             }
         }
       }
    }
  }
}
</code>```

then restart logstash, delete all elasticsearch index.
I check the new index's mapping in the elasticsearch, but it didn't work in this way.

How can I config the index template?

答:
I've created new template.json file and defined path to it into elasticsearch output block of logstash.yml config file:

```<code>stdout { codec => json_lines }

elasticsearch {

"hosts" => ["ip:port"]
"index" => "name-of-index-%{+dd.MM.YYYY}"
template => "/{path-to-logstash-folder}/templates/your-template.json"
template_overwrite => true
manage_template => false
}
</code>```

document_type for Elastic I defined into input block of logstash.yml config file:

```<code>input {

file {
path => "/your-path-to-directory/*.log"
type => "name-of-type"
 }
}
</code>```

There is my template.json file

```<code>{
"name-of-index": {
"order": 0,
"version": 50001,
"template": "name-of-index-*",
"settings": {
  "index": {
    "refresh_interval": "5s"
  }
},
"mappings": {
  "_default_": {
    "dynamic_templates": [
      {
        "message_field": {
          "path_match": "message",
          "mapping": {
            "norms": false,
            "type": "text"
          },
          "match_mapping_type": "string"
        }
      },
      {
        "string_fields": {
          "mapping": {
            "norms": false,
            "type": "text",
            "fields": {
              "keyword": {
                "type": "keyword"
              }
            }
          },
          "match_mapping_type": "string",
          "match": "*"
        }
      }
    ],
    "_all": {
      "norms": false,
      "enabled": true
    },
    "properties": {
      "@timestamp": {
        "include_in_all": false,
        "type": "date"
      },
      "geoip": {
        "dynamic": true,
        "properties": {
          "ip": {
            "type": "ip"
          },
          "latitude": {
            "type": "half_float"
          },
          "location": {
            "type": "geo_point"
          },
          "longitude": {
            "type": "half_float"
          }
        }
      },
      "@version": {
        "include_in_all": false,
        "type": "keyword"
      }
    }
  }
},
"aliases": {}
 }
 }
</code>```

Body:
I use logstash + elasticsearch to collect syslog and want to set ttl for log ageing

I find a file named elasticsearch-template.json in the logstash,the path is logstash/logstash-1.4.2/lib/logstash/outputs/elasticsearch/elasticsearch-template.json

I add ttl info in the file like this:

{
  "template" : "logstash-*",
  "settings" : {
    "index.refresh_interval" : "5s"
  },
  "mappings" : {
    "_default_" : {
       "_all" : {"enabled" : true},
       "dynamic_templates" : [ {
         "string_fields" : {
           "match" : "*",
           "match_mapping_type" : "string",
           "mapping" : {
             "type" : "string", "index" : "analyzed", "omit_norms" : true,
               "fields" : {
                 "raw" : {"type": "string", "index" : "not_analyzed", "ignore_above" : 256}
               }
           }
         }
       } ],
        "_ttl": {
         "enabled": true,
         "default": "1d"
       },
       "properties" : {
         "@version": { "type": "string", "index": "not_analyzed" },
         "geoip"  : {
           "type" : "object",
             "dynamic": true,
             "path": "full",
             "properties" : {
               "location" : { "type" : "geo_point" }
             }
         }
       }
    }
  }
}

then restart logstash, delete all elasticsearch index.
I check the new index's mapping in the elasticsearch, but it didn't work in this way.

How can I config the index template?

Body:
I've created new template.json file and defined path to it into elasticsearch output block of logstash.yml config file:

stdout { codec => json_lines }

elasticsearch {

"hosts" => ["ip:port"]
"index" => "name-of-index-%{+dd.MM.YYYY}"
template => "/{path-to-logstash-folder}/templates/your-template.json"
template_overwrite => true
manage_template => false
}

document_type for Elastic I defined into input block of logstash.yml config file:

input {

file {
path => "/your-path-to-directory/*.log"
type => "name-of-type"
 }
}

There is my template.json file

{
"name-of-index": {
"order": 0,
"version": 50001,
"template": "name-of-index-*",
"settings": {
  "index": {
    "refresh_interval": "5s"
  }
},
"mappings": {
  "_default_": {
    "dynamic_templates": [
      {
        "message_field": {
          "path_match": "message",
          "mapping": {
            "norms": false,
            "type": "text"
          },
          "match_mapping_type": "string"
        }
      },
      {
        "string_fields": {
          "mapping": {
            "norms": false,
            "type": "text",
            "fields": {
              "keyword": {
                "type": "keyword"
              }
            }
          },
          "match_mapping_type": "string",
          "match": "*"
        }
      }
    ],
    "_all": {
      "norms": false,
      "enabled": true
    },
    "properties": {
      "@timestamp": {
        "include_in_all": false,
        "type": "date"
      },
      "geoip": {
        "dynamic": true,
        "properties": {
          "ip": {
            "type": "ip"
          },
          "latitude": {
            "type": "half_float"
          },
          "location": {
            "type": "geo_point"
          },
          "longitude": {
            "type": "half_float"
          }
        }
      },
      "@version": {
        "include_in_all": false,
        "type": "keyword"
      }
    }
  }
},
"aliases": {}
 }
 }


问:
Assume val and opaque type constructs in F*
I'm new to F* and although the tutorial is well-written I'm missing some good API page for reference.

So I need the precise meaning for the following constructs:

```<code>assume val name: type
</code>```

I'd say this line registers into the solver the name being used?

```<code>opaque type name (...) ...
</code>```

What is the effect of calling a type opaque? What about the lists of parameters it may take?

Please include the references you may have used to give this answer.

答:
The meaning of assume val name : Type is to assume an axiom inhabiting Type which can be accessed by name. Since it is an axiom, it won't have an implementation and can lead to logical inconsistencies if misused (for example by assuming a natural number strictly smaller than 0).

The F* tutorial is not exactly up to date with the multiple changes that happened over the last year and opaque is an instance of that problem.
From the compiler source (as of writing, in src/tosyntax/FStar.ToSyntax.fs) :

The 'opaque' qualifier is deprecated since its use was strangely schizophrenic. There were two overloaded uses:
  (1) Given 'opaque val f : t', the behavior was to exclude the definition of 'f' to the SMT solver. This corresponds roughly to the new 'irreducible' qualifier.
  (2) Given 'opaque type t = t'', the behavior was to provide the definition of 't' to the SMT solver, but not to inline it, unless absolutely required for unification. This corresponds roughly to the behavior of 'unfoldable' (which is currently the default).

Body:
I'm new to F* and although the tutorial is well-written I'm missing some good API page for reference.

So I need the precise meaning for the following constructs:

assume val name: type

I'd say this line registers into the solver the name being used?

opaque type name (...) ...

What is the effect of calling a type opaque? What about the lists of parameters it may take?

Please include the references you may have used to give this answer.


问:
"Denormalized data" when trying to export from Excel to XML
I've been having this particular problem for quite a while now.
Essentially, I've got an Excel list of various products that need to be exported to an XML file. The instant I map the first XML element to the first row of data - A recurring customer number in this case - I get the "denormalized data" error. Now, as far as I understand, this means Excel is unhappy with the customer number being the same for every row:

(The LKZ row is formatted as plain text but changing the formatting to  numbers doesn't seem to help either.)

Copying the data to a new Excel sheet does work but ONLY for a single row.
Exporting it will consequently only export a single row of data.

I'm not certain the XML scheme that we got provided with is entirely correct:

I tried setting the maxOccurs to unbounded but I either didn't do it right or I'm on the wrong track in that regard. (If somebody would be nice enough to give an example of how maxOccurs SHOULD look it'd be appreciated.)

答:
Looks like nobody really has an answer. Can't blame you guys.

I ended up brute forcing the issue by writing a macro that creates an entirely new XML file. If anyone cares, here is the code. Keep in mind I don't usually work with VBA so it's probably not super elegant.

```<code>Sub Text()

Dim arrHeader() As String, Max As Integer, Col As Integer, arrContent() As String, Row As Integer
Dim filesys, testfile, XTab As String

STab = "    "
Max = 1

Set filesys = CreateObject("Scripting.FileSystemObject")
Set testfile = filesys.CreateTextFile("C:\Users\edvpr\Desktop\test.xml", True)

testfile.WriteLine "<?xml version=""1.0"" encoding=""UTF-8""?>"
testfile.WriteLine "<ottopartner xmlns=""http://www.ottogroupb2b.com/ottopartner"">"

Do
    Max = Max + 1
Loop Until Cells(1, Max) = ""
Col = 1
ReDim arrHeader(1 To Max - 1) As String
Do
    arrHeader(Col) = Cells(1, Col)
    Col = Col + 1
Loop Until Col = Max

Row = 2
ReDim arrContent(1 To Max - 1) As String
Do
    Col = 1
    If Row = 2 Then
    Do
        arrContent(Col) = Cells(Row, Col)

        If arrContent(Col) <> "" And arrHeader(Col) = "LKZ" Then
            testfile.WriteLine "<" + Trim(arrHeader(Col)) + ">" + Trim(arrContent(Col)) + "</" + Trim(arrHeader(Col)) + ">"
            testfile.WriteLine "<Styles>"
        End If
    Col = Col + 1
    Loop Until Col = Max
    End If

    Col = 1

    Do
        arrContent(Col) = Cells(Row, Col)
        If Trim(arrContent(Col)) <> "" And Trim(arrHeader(Col)) <> "LKZ" Then
            If Trim(arrHeader(Col)) = "OrderQuantityDefault" Then
                XTab = STab + STab
                testfile.WriteLine XTab + "<Item>"
            End If

            If Trim(arrHeader(Col)) = "InvoicingStartDate" Then
                XTab = STab + STab + STab
                testfile.WriteLine XTab + "<SKU>"
            End If

            If Trim(arrHeader(Col)) = "StyleNo" Then
                If Row > 2 Then
                    testfile.WriteLine XTab + "</SKU>"
                    XTab = STab + STab
                    testfile.WriteLine XTab + "</Item>"
                    XTab = STab
                    testfile.WriteLine XTab + "</Style>"
                End If

                XTab = STab
                testfile.WriteLine XTab + "<Style>"
            End If

            testfile.WriteLine XTab + STab + "<" + Trim(arrHeader(Col)) + ">" + Trim(arrContent(Col)) + "</" + Trim(arrHeader(Col)) + ">"
        End If
        Col = Col + 1
    Loop Until Col = Max

    Row = Row + 1

Loop Until Cells(Row, 1) = ""
testfile.WriteLine "</SKU>"
testfile.WriteLine "</Item>"
testfile.WriteLine "</Style>"
testfile.WriteLine "</Styles>"
testfile.WriteLine "</ottopartner>"

testfile.Close

End Sub
</code>```

The macro reads the first line left to right to create the tags, then fills them with the rest of the data top to bottom. It also indents the XML because OCD.

Body:
Looks like nobody really has an answer. Can't blame you guys.

I ended up brute forcing the issue by writing a macro that creates an entirely new XML file. If anyone cares, here is the code. Keep in mind I don't usually work with VBA so it's probably not super elegant.

Sub Text()

Dim arrHeader() As String, Max As Integer, Col As Integer, arrContent() As String, Row As Integer
Dim filesys, testfile, XTab As String

STab = "    "
Max = 1

Set filesys = CreateObject("Scripting.FileSystemObject")
Set testfile = filesys.CreateTextFile("C:\Users\edvpr\Desktop\test.xml", True)

testfile.WriteLine "<?xml version=""1.0"" encoding=""UTF-8""?>"
testfile.WriteLine "<ottopartner xmlns=""http://www.ottogroupb2b.com/ottopartner"">"

Do
    Max = Max + 1
Loop Until Cells(1, Max) = ""
Col = 1
ReDim arrHeader(1 To Max - 1) As String
Do
    arrHeader(Col) = Cells(1, Col)
    Col = Col + 1
Loop Until Col = Max

Row = 2
ReDim arrContent(1 To Max - 1) As String
Do
    Col = 1
    If Row = 2 Then
    Do
        arrContent(Col) = Cells(Row, Col)

        If arrContent(Col) <> "" And arrHeader(Col) = "LKZ" Then
            testfile.WriteLine "<" + Trim(arrHeader(Col)) + ">" + Trim(arrContent(Col)) + "</" + Trim(arrHeader(Col)) + ">"
            testfile.WriteLine "<Styles>"
        End If
    Col = Col + 1
    Loop Until Col = Max
    End If

    Col = 1

    Do
        arrContent(Col) = Cells(Row, Col)
        If Trim(arrContent(Col)) <> "" And Trim(arrHeader(Col)) <> "LKZ" Then
            If Trim(arrHeader(Col)) = "OrderQuantityDefault" Then
                XTab = STab + STab
                testfile.WriteLine XTab + "<Item>"
            End If

            If Trim(arrHeader(Col)) = "InvoicingStartDate" Then
                XTab = STab + STab + STab
                testfile.WriteLine XTab + "<SKU>"
            End If

            If Trim(arrHeader(Col)) = "StyleNo" Then
                If Row > 2 Then
                    testfile.WriteLine XTab + "</SKU>"
                    XTab = STab + STab
                    testfile.WriteLine XTab + "</Item>"
                    XTab = STab
                    testfile.WriteLine XTab + "</Style>"
                End If

                XTab = STab
                testfile.WriteLine XTab + "<Style>"
            End If

            testfile.WriteLine XTab + STab + "<" + Trim(arrHeader(Col)) + ">" + Trim(arrContent(Col)) + "</" + Trim(arrHeader(Col)) + ">"
        End If
        Col = Col + 1
    Loop Until Col = Max

    Row = Row + 1

Loop Until Cells(Row, 1) = ""
testfile.WriteLine "</SKU>"
testfile.WriteLine "</Item>"
testfile.WriteLine "</Style>"
testfile.WriteLine "</Styles>"
testfile.WriteLine "</ottopartner>"

testfile.Close

End Sub

The macro reads the first line left to right to create the tags, then fills them with the rest of the data top to bottom. It also indents the XML because OCD.


问:
C terminology: header vs. signature
the word header as far as I know is usually in reference to a header file while the word signature is in reference to the arguments and return type of the function. For example, in my experience this would be called a signature:

```<code>int ptInPoly(Point q, Point p[], int n)
</code>```

My professor is calling this a header in my assignments. I have found this confusing and would like to know if this different use terminology is common or something that only he does. Thanks

Here is some more context around the use of the term header:

"Your program must have a function with header: int ptInPoly(Point q, Point p[], int n) that determines if point q is in the polygon given in p"

答:
I had the same problem and I understood that this

```<code>int ptInPoly(Point q, Point p[], int n)
</code>```

is a header, but this

```<code> ptInPoly(Point q, Point p[], int n)
</code>```

is called signature. it is given a different name because in function overloading the signature of the function(function name + parameter list) is important.

Title: C terminology: header vs. signature

Body:
the word header as far as I know is usually in reference to a header file while the word signature is in reference to the arguments and return type of the function. For example, in my experience this would be called a signature:

int ptInPoly(Point q, Point p[], int n)

My professor is calling this a header in my assignments. I have found this confusing and would like to know if this different use terminology is common or something that only he does. Thanks

Here is some more context around the use of the term header:

"Your program must have a function with header: int ptInPoly(Point q, Point p[], int n) that determines if point q is in the polygon given in p"

Body:
I had the same problem and I understood that this

int ptInPoly(Point q, Point p[], int n)

is a header, but this

 ptInPoly(Point q, Point p[], int n)

is called signature. it is given a different name because in function overloading the signature of the function(function name + parameter list) is important.


问:
Change taskbar icon at runtime on deployed app
I would like to change taskbar icon to notify the user when a new message is received like outlook when you receive a new mail.

I already search solution on web and it's all about changing the window icon like this:

```<code>Uri iconUri = new Uri("Resources/envelop.ico", UriKind.Relative);
this.Icon = BitmapFrame.Create(iconUri);
</code>```

It's working well on Visual Studio but I found out that it's not changing my task bar on deployed app because it's a read-only variable. And worse it's change only the top-left attached icon that I didn't want to change anyways.

So is there a way to do it? Outlook did it and Chrome too so there must be a way.

UPDATE

To force the icon refresh on my deployed app I have to pin/unpin my icon taskbar, unfortunately this is a user command only so I can't do this in wpf programmatically without exploiting some dirty manners which would be too unstable.

Actually I'm trying to find a way to refresh Icon cache without doing it for each Windows OS or version.

答:
Here is a small working demo doing the job !

Add Icons:

Chose 2 Icons (for example Outlook Standard & Outlook MailReceived):

Add this to the code behind of your MainWindow

```<code>public partial class MainWindow : Window
{
    private int _imgId;

    public MainWindow()
    {
        InitializeComponent();
        this.Loaded += MainWindow_Loaded;
    }

    private void MainWindow_Loaded(object sender, RoutedEventArgs e)
    {
        //Start timer to periodically change the App Icon:
        new System.Threading.Thread(() =>
        {
            System.Timers.Timer timer = new System.Timers.Timer();
            timer.Interval = 100;
            timer.AutoReset = true;
            timer.Elapsed += Timer_Elapsed;
            timer.Start();
        }).Start();
    }

    private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        try
        {
            //Change AppIcon on UI-Thread
            Dispatcher.Invoke(() =>
            {
                /* CHANGE YOUR ICONS HERE !!! */
                BitmapSource ms_icon = System.Windows.Interop.Imaging.CreateBitmapSourceFromHIcon(Properties.Resources.Microsoft_logo.Handle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
                BitmapSource so_icon = System.Windows.Interop.Imaging.CreateBitmapSourceFromHIcon(Properties.Resources.images.Handle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
                if (_imgId == 0)
                {
                    this.Icon = so_icon;
                    _imgId = 1;
                }
                else
                {
                    this.Icon = ms_icon;
                    _imgId = 0;
                }
            });
        }
        catch (Exception ex)
        {
            System.Diagnostics.Trace.WriteLine(ex.Message);
        }
    }
}
</code>```

Will produce this output (switch every 100ms):

Body:
I would like to change taskbar icon to notify the user when a new message is received like outlook when you receive a new mail.

I already search solution on web and it's all about changing the window icon like this:

Uri iconUri = new Uri("Resources/envelop.ico", UriKind.Relative);
this.Icon = BitmapFrame.Create(iconUri);

It's working well on Visual Studio but I found out that it's not changing my task bar on deployed app because it's a read-only variable. And worse it's change only the top-left attached icon that I didn't want to change anyways.

So is there a way to do it? Outlook did it and Chrome too so there must be a way.

UPDATE

To force the icon refresh on my deployed app I have to pin/unpin my icon taskbar, unfortunately this is a user command only so I can't do this in wpf programmatically without exploiting some dirty manners which would be too unstable.

Actually I'm trying to find a way to refresh Icon cache without doing it for each Windows OS or version.

Body:
Here is a small working demo doing the job !

Add Icons:

Chose 2 Icons (for example Outlook Standard & Outlook MailReceived):

Add this to the code behind of your MainWindow

public partial class MainWindow : Window
{
    private int _imgId;

    public MainWindow()
    {
        InitializeComponent();
        this.Loaded += MainWindow_Loaded;
    }

    private void MainWindow_Loaded(object sender, RoutedEventArgs e)
    {
        //Start timer to periodically change the App Icon:
        new System.Threading.Thread(() =>
        {
            System.Timers.Timer timer = new System.Timers.Timer();
            timer.Interval = 100;
            timer.AutoReset = true;
            timer.Elapsed += Timer_Elapsed;
            timer.Start();
        }).Start();
    }

    private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        try
        {
            //Change AppIcon on UI-Thread
            Dispatcher.Invoke(() =>
            {
                /* CHANGE YOUR ICONS HERE !!! */
                BitmapSource ms_icon = System.Windows.Interop.Imaging.CreateBitmapSourceFromHIcon(Properties.Resources.Microsoft_logo.Handle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
                BitmapSource so_icon = System.Windows.Interop.Imaging.CreateBitmapSourceFromHIcon(Properties.Resources.images.Handle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
                if (_imgId == 0)
                {
                    this.Icon = so_icon;
                    _imgId = 1;
                }
                else
                {
                    this.Icon = ms_icon;
                    _imgId = 0;
                }
            });
        }
        catch (Exception ex)
        {
            System.Diagnostics.Trace.WriteLine(ex.Message);
        }
    }
}

Will produce this output (switch every 100ms):


问:
Jackson Json: Converting a Json Tree Node to an Java Object and add it to an ArrayList
I'm still new to Java and parsing Json. I'm trying to build a Comic Webapp with Spring. The Database is a Json File, which holds an Array of different Comics.
I wanted to convert the Json Array to Java Objects and put it into an ArrayList but I seem to make a mistake somewhere along the way.  Maybe you can tell me what I'm doing wrong? While doing a JUnit Test I get the following error:

```<code>Error com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "Comic" (class de.uni_koeln.comics.data.Comic), not marked as ignorable (6 known properties: , "title", "issue", "id", "box", "publisher", "comment"])
 at [Source: N/A; line: -1, column: -1] (through reference chain: de.uni_koeln.comics.data.Comic["Comic"])
</code>```

Comic.class

```<code>package de.uni_koeln.comics.data;

import de.uni_koeln.comics.service.JsonImportService;

public class Comic {
    private JsonImportService jservice;

public String title;
public int id;
public int issue;
public int box;
public String publisher;
public String comment;

public Comic() {

}
public Comic(String title, int issue, int box, String publisher, String   comment) {
        this.title = title;
        this.issue = issue;
        this.box = box;
        this.comment = comment;
        this.publisher = publisher;
    }

//setter and getter
</code>```

`
JsonImportService

```<code>package de.uni_koeln.comics.service;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

@Service
public class JsonImportService {
    private List<Comic> comicList;

    @Test
    public void readComicJson() throws JsonParseException, JsonMappingException, IOException {

        ObjectMapper mapper = new ObjectMapper();
        JsonNode root = mapper.readTree(new File("src/main/resources/Comics.json"));
    Comic comic = mapper.treeToValue(root, Comic.class);

    JsonNode contactNode = root.path("Comic");
    if (contactNode.isArray()) {
        for (JsonNode node : contactNode) {

            String title = node.path("Title").asText();
            int issue = node.path("Issue #").asInt();
            int box = node.path("Box #").asInt();
            String publisher = node.path("Publisher").asText();
            String comment = node.path("Comments").asText();

            comic.setTitle(title);
            comic.setIssue(issue);
            comic.setBox(box);
            comic.setPublisher(publisher);
            comic.setComment(comment);
            comicList.add(new Comic(title,box,issue,publisher,comment));
        }
    }
}

public List<Comic> getComicList() {
    return comicList;
}
</code>```

答:
Try to use the @JsonIgnoreProperties annotation like blow.

@JsonIgnoreProperties(ignoreUnknown = true)

public class Comic {

}

Body:
I'm still new to Java and parsing Json. I'm trying to build a Comic Webapp with Spring. The Database is a Json File, which holds an Array of different Comics.
I wanted to convert the Json Array to Java Objects and put it into an ArrayList but I seem to make a mistake somewhere along the way.  Maybe you can tell me what I'm doing wrong? While doing a JUnit Test I get the following error:

Error com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "Comic" (class de.uni_koeln.comics.data.Comic), not marked as ignorable (6 known properties: , "title", "issue", "id", "box", "publisher", "comment"])
 at [Source: N/A; line: -1, column: -1] (through reference chain: de.uni_koeln.comics.data.Comic["Comic"])

Comic.class

package de.uni_koeln.comics.data;

import de.uni_koeln.comics.service.JsonImportService;

public class Comic {
    private JsonImportService jservice;

public String title;
public int id;
public int issue;
public int box;
public String publisher;
public String comment;

public Comic() {

}
public Comic(String title, int issue, int box, String publisher, String   comment) {
        this.title = title;
        this.issue = issue;
        this.box = box;
        this.comment = comment;
        this.publisher = publisher;
    }

//setter and getter

`
JsonImportService

package de.uni_koeln.comics.service;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

@Service
public class JsonImportService {
    private List<Comic> comicList;

    @Test
    public void readComicJson() throws JsonParseException, JsonMappingException, IOException {

        ObjectMapper mapper = new ObjectMapper();
        JsonNode root = mapper.readTree(new File("src/main/resources/Comics.json"));
    Comic comic = mapper.treeToValue(root, Comic.class);

    JsonNode contactNode = root.path("Comic");
    if (contactNode.isArray()) {
        for (JsonNode node : contactNode) {

            String title = node.path("Title").asText();
            int issue = node.path("Issue #").asInt();
            int box = node.path("Box #").asInt();
            String publisher = node.path("Publisher").asText();
            String comment = node.path("Comments").asText();

            comic.setTitle(title);
            comic.setIssue(issue);
            comic.setBox(box);
            comic.setPublisher(publisher);
            comic.setComment(comment);
            comicList.add(new Comic(title,box,issue,publisher,comment));
        }
    }
}

public List<Comic> getComicList() {
    return comicList;
}


问:
Local late initialization in Kotlin
How can I late-initialize a variable in a funtion, since lateinit is not allowed for local variables? Otherwise, what is the good pattern for this case:

```<code>private fun displaySelectedScreen(itemID: Int) {
    //creating fragment object
    val fragment: Fragment
    //initializing the fragment object which is selected
    when (itemID) {
        R.id.nav_schedule -> fragment = ScheduleFragment()
        R.id.nav_coursework -> fragment = CourseworkFragment()
        R.id.nav_settings -> {
            val i = Intent(this, SettingsActivity::class.java)
            startActivity(i)
        }
        else -> throw IllegalArgumentException()
    }
    //replacing the fragment, if not Settings Activity
    if (itemID != R.id.nav_settings) {
        val ft = supportFragmentManager.beginTransaction()
        ft.replace(R.id.content_frame, fragment)// Error: Variable 'fragment' must be initialized
        ft.commit()
    }
    drawerLayout.closeDrawer(GravityCompat.START)
}
</code>```

答:
when is an expression, so

```<code>val fragment: Fragment = when (itemID) {
    R.id.nav_schedule -> ScheduleFragment()
    R.id.nav_coursework -> CourseworkFragment()
    ...
    else -> throw IllegalArgumentException()
}
</code>```

will work for this use case.

There is no lateinit equivalent for local variables. Other language constructs like try or if are expressions as well, so this is never needed.

Update 2017-11-19

Kotlin 1.2 supports lateinit for local variables, so

```<code>lateinit val fragment: Fragment
</code>```

works starting with Kotlin 1.2.

Title: Local late initialization in Kotlin

Body:
How can I late-initialize a variable in a funtion, since lateinit is not allowed for local variables? Otherwise, what is the good pattern for this case:

private fun displaySelectedScreen(itemID: Int) {
    //creating fragment object
    val fragment: Fragment
    //initializing the fragment object which is selected
    when (itemID) {
        R.id.nav_schedule -> fragment = ScheduleFragment()
        R.id.nav_coursework -> fragment = CourseworkFragment()
        R.id.nav_settings -> {
            val i = Intent(this, SettingsActivity::class.java)
            startActivity(i)
        }
        else -> throw IllegalArgumentException()
    }
    //replacing the fragment, if not Settings Activity
    if (itemID != R.id.nav_settings) {
        val ft = supportFragmentManager.beginTransaction()
        ft.replace(R.id.content_frame, fragment)// Error: Variable 'fragment' must be initialized
        ft.commit()
    }
    drawerLayout.closeDrawer(GravityCompat.START)
}

Body:
when is an expression, so

val fragment: Fragment = when (itemID) {
    R.id.nav_schedule -> ScheduleFragment()
    R.id.nav_coursework -> CourseworkFragment()
    ...
    else -> throw IllegalArgumentException()
}

will work for this use case.

There is no lateinit equivalent for local variables. Other language constructs like try or if are expressions as well, so this is never needed.

Update 2017-11-19

Kotlin 1.2 supports lateinit for local variables, so

lateinit val fragment: Fragment

works starting with Kotlin 1.2.


问:
Array AND() ? Logical ANDing of all elements
I have an array and I want to find out if there is at least one false value in it. I was thinking of creating an array_and() function, that just performs a logical AND on all the elements. It would return true if all values are true, otherwise false. Am I over-engineering?

答:
It would return true if all values are true, otherwise false.

Returns true if array is non empty and contains no false elements:

```<code>function array_and(arary $arr)
{
  return $arr && array_reduce($arr, function($a, $b) { return $a && $b; }, true));
}
</code>```

(Note that you would need strict comparison if you wanted to test against the false type.)

Am I over-engineering?

Yes, because you could use:

```<code>in_array(false, $arr, true);
</code>```

Body:
It would return true if all values are true, otherwise false.

Returns true if array is non empty and contains no false elements:

function array_and(arary $arr)
{
  return $arr && array_reduce($arr, function($a, $b) { return $a && $b; }, true));
}

(Note that you would need strict comparison if you wanted to test against the false type.)

Am I over-engineering?

Yes, because you could use:

in_array(false, $arr, true);


问:
How to read JSON message in request on RESTful service side.
I'm trying to read JSON data sent from a client on a service.
Whatever I try I'm getting an empty object in the console.
//My service

```<code> @Path("signup")
    public class signupservice {

          @POST
          @Consumes(MediaType.APPLICATION_JSON)
          @Produces(MediaType.APPLICATION_JSON)
          public JSONObject Signmeup( JSONObject inputJsonObj) throws JSONException {

            String fname  = inputJsonObj.toString();
            System.out.println(fname);
            JSONObject outputJsonObj = new JSONObject();
            outputJsonObj.put("output", "output");
            return outputJsonObj;
          }
    }
</code>```

I'm sending the request from postman.

答:
If you want to get first_name and last_name from JSON that you send from client on a service. You can try this.</p>

```<code>@Path("signup")
public class signupservice {
    @POST
    @Consumes("application/json")
    @Produces(MediaType.APPLICATION_JSON)
    public JSONObject Signmeup(String inputJsonObj) throws JSONException {
        JSONObject innerJson = new JSONObject(inputJsonObj);
        //Get first_name and last_name from JSON
        String fname  = innerJson.getString("first_name");
        String lname  = innerJson.getString("last_name");
        System.out.println(fname);
        System.out.println(lname);

        JSONObject outputJsonObj = new JSONObject();
        outputJsonObj.put("output", "output");
        return outputJsonObj;
    }
}
</code>```

Body:
I'm trying to read JSON data sent from a client on a service.
Whatever I try I'm getting an empty object in the console.
//My service

 @Path("signup")
    public class signupservice {

          @POST
          @Consumes(MediaType.APPLICATION_JSON)
          @Produces(MediaType.APPLICATION_JSON)
          public JSONObject Signmeup( JSONObject inputJsonObj) throws JSONException {

            String fname  = inputJsonObj.toString();
            System.out.println(fname);
            JSONObject outputJsonObj = new JSONObject();
            outputJsonObj.put("output", "output");
            return outputJsonObj;
          }
    }

I'm sending the request from postman.

Body:
If you want to get first_name and last_name from JSON that you send from client on a service. You can try this.

@Path("signup")
public class signupservice {
    @POST
    @Consumes("application/json")
    @Produces(MediaType.APPLICATION_JSON)
    public JSONObject Signmeup(String inputJsonObj) throws JSONException {
        JSONObject innerJson = new JSONObject(inputJsonObj);
        //Get first_name and last_name from JSON
        String fname  = innerJson.getString("first_name");
        String lname  = innerJson.getString("last_name");
        System.out.println(fname);
        System.out.println(lname);

        JSONObject outputJsonObj = new JSONObject();
        outputJsonObj.put("output", "output");
        return outputJsonObj;
    }
}


问:
How to read two inputs separated by space in a single line?
I want to read two input values. First value should be an integer and the second value should be a float.

I saw Read two variables in a single line with Python, but it applies only if both the values are of same type. Do I have any other way?

Example input, first is int and second is float. The inputs should be on a single line:

```<code>20 150.50
</code>```

http://www.codechef.com/problems/HS08TEST/

I'm very new to Python.

答:
In Python 2.7, I use this

A,B = raw_input().split(" ")
A = int(A)
B = float(B)
print(A)
print(B)
```
<p>Output:</p>
```34 6.9

34

6.9
```

Body:
I want to read two input values. First value should be an integer and the second value should be a float.

I saw Read two variables in a single line with Python, but it applies only if both the values are of same type. Do I have any other way?

Example input, first is int and second is float. The inputs should be on a single line:

20 150.50

http://www.codechef.com/problems/HS08TEST/

I'm very new to Python.

LastEditorDisplayName: Roger Pate

Body:
In Python 2.7, I use this

A,B = raw_input().split(" ")
A = int(A)
B = float(B)
print(A)
print(B)

Output:

34 6.9

34

6.9


问:
Real-time navigation for Web development
For an app I'm building, I need real-time navigation. I've chosen Google maps, but I'm noticing there's nothing on real-time navigation for websites.

What are my options? Am I better off going with another provider, like Bing or Mapquest?

答:
of course there is.

the real-time navigation is nothing more but capturing the current position of the user and displaying it or laying on top of the Google Map or other map.

you have to choose the technology on the server or back-end service to handle the capturing / storing positions in the database. I'm sure the server language or stack that you are using (node, php, asp..etc) has some libs for that already..
this is the Google page that uses cloud DB solution and native browser caps for capturing your position.. and this is the jsfiddle with example how to capture your current position... simple oneliner right :)

https://jsfiddle.net/api/post/library/pure/

```<code>navigator.geolocation.getCurrentPosition(function(position)
</code>```

start from that and build it up gradually, good luck!

kres

Body:
of course there is.

the real-time navigation is nothing more but capturing the current position of the user and displaying it or laying on top of the Google Map or other map.

you have to choose the technology on the server or back-end service to handle the capturing / storing positions in the database. I'm sure the server language or stack that you are using (node, php, asp..etc) has some libs for that already..
this is the Google page that uses cloud DB solution and native browser caps for capturing your position.. and this is the jsfiddle with example how to capture your current position... simple oneliner right :)

https://jsfiddle.net/api/post/library/pure/

navigator.geolocation.getCurrentPosition(function(position)

start from that and build it up gradually, good luck!

kres


问:
Which is more secure: External browser or ChromeTab for authorization?
I am developing cordova based hybrid mobile apps targeted for android and iOS smartphones.

Update: Embedded webview approach is no longer supported by Google

Usecase: The application authenticate user and then would be accessing Google Calendar API's, and finally display user events on the app.

Note: I will be Using 3-legged OAuth and Google Data APIs without the client libraries.

Question
For invoking OAuth requests to Google, shall I used external browser or ChromeTabs?

Which approach is best suitable from security point of view?
Thanks!

答:
From security point of view, it's the same, Chrome Custom Tabs rely on Chrome browser information and there is no difference on the security.

This is what official doc about Chrome Custom Tabs

Security: the browser uses Google's Safe Browsing to protect the user
  and the device from dangerous sites.

From app integration point of view, it's better to use Chrome Custom Tabs because you don't push the user out of the app for the login. But be aware that Chrome Custom Tabs are only available on Jellybean and greater (API 16) and needs Chrome 45 installed on the device.


问:
How do i pass my input/output to this network?
I seem to have some problems starting my learning... I am not sure why..
the network is multi input (72 1d arrays) and output is a 1d array length 24. the 1d array output consist of numbers related to 145 different classes.

So: 72 inputs => 24 outputs

Minimal working example - without the input/output being set.

```<code>import keras
from keras.utils import np_utils
from keras import metrics
from keras.models import Sequential
from keras.layers.core import Dense, Activation, Lambda, Reshape,Flatten
from keras.layers import Conv1D,Conv2D, MaxPooling2D, MaxPooling1D, Reshape, ZeroPadding2D
from keras.utils import np_utils
from keras.layers.advanced_activations import LeakyReLU, PReLU
from keras.layers.advanced_activations import ELU
from keras.models import Model
from keras.layers import Input, Dense
from keras.layers import Dropout
from keras import backend as K
from keras.callbacks import ReduceLROnPlateau
from keras.callbacks import CSVLogger
from keras.callbacks import EarlyStopping
from keras.models import load_model
from keras.layers.merge import Concatenate
import numpy as np

def chunks(l, n):
    """Yield successive n-sized chunks from l."""
    for i in range(0, len(l), n):
        yield l[i:i + n]

nano_train_input = []
nano_train_output = []
nano_test_input = []
nano_test_output = []

##   Creating train input:
for i in range(974):
    nano_train_input.append(np.random.random((78,684,4)))
    nano_train_output.append(np.random.randint(145,size=(228)).tolist())

##   Creating test input:
for i in range(104):
    nano_test_input.append(np.random.random((78,684,4)))
    nano_test_output.append(np.random.randint(145,size=(228)).tolist())

def model(train_input, train_output, test_input, test_output, names=0):

    #   Paper uses dimension (40 x 45 =(15 * 3))
    #   Filter size 5
    #   Pooling size
    #   I use dimension (78  x 72 = (24 * 3)
    #   Filter size 9

    print "In model"
    i = 0
    print_once = True
    data_test_output = []
    data_test_input = []
    for matrix in test_input:
        row,col,channel = matrix.shape
        remove_output = (col/3)%24
        remove_input  = col%72
        if remove_output > 0 :
            test_output[i] = test_output[i][:-(remove_output)]
        for split in chunks(test_output[i],24):
            data_test_output.append(np.array(split))
        if remove_input > 0:
            out = np.split(matrix[:,:-(remove_input),:-1],matrix[:,:-(remove_input),:-1].shape[1]/72,axis=1)
        else:
            out = np.split(matrix[:,:,:-1],matrix[:,:,:-1].shape[1]/72,axis=1)
        data_test_input.extend(out)
        del out
        i=i+1 # Increment

    i=0
    data_train_output = []
    data_train_input = []
    for matrix in train_input:
        row,col,channel = matrix.shape
        remove_output = (col/3)%24
        remove_input  = col%72
        if remove_output > 0 :
            train_output[i] = train_output[i][:-(remove_output)]
        for split in chunks(train_output[i],24):
            data_train_output.append(np.array(split))
        if remove_input > 0:
            out = np.split(matrix[:,:-(remove_input),:-1],matrix[:,:-(remove_input),:-1].shape[1]/72,axis=1)
        else:
            out = np.split(matrix[:,:,:-1],matrix[:,:,:-1].shape[1]/72,axis=1)
        data_train_input.extend(out)
        del out
        i=i+1 # Increment

    print
    print "Len:"
    print len(data_train_input)
    print len(data_train_output)
    print len(data_test_input)
    print len(data_test_output)
    print
    print "Type[0]:"
    print type(data_train_input[0])
    print type(data_train_output[0])
    print type(data_test_input[0])
    print type(data_test_output[0])
    print
    print "Type:"
    print type(data_train_input)
    print type(data_train_output)
    print type(data_test_input)
    print type(data_test_output)
    print
    print "shape of [0]:"
    print data_train_input[0].shape
    print data_train_output[0].shape
    print data_test_input[0].shape
    print data_test_output[0].shape

    list_of_input = [Input(shape = (78,3)) for i in range(72)]
    list_of_conv_output = []
    list_of_max_out = []

    for i in range(72):
        list_of_conv_output.append(Conv1D(filters = 32 , kernel_size = 6 , padding = "same", activation = 'relu')(list_of_input[i]))
        list_of_max_out.append(MaxPooling1D(pool_size=3)(list_of_conv_output[i]))

    merge = keras.layers.concatenate(list_of_max_out)

    reshape = Flatten()(merge)

    dense1 = Dense(units = 500, activation = 'relu',    name = "dense_1")(reshape)
    dense2 = Dense(units = 250, activation = 'relu',    name = "dense_2")(dense1)
    dense3 = Dense(units = 24 , activation = 'softmax', name = "dense_3")(dense2)

    model = Model(inputs = list_of_input , outputs = dense3)
    model.compile(loss="categorical_crossentropy", optimizer="adam" , metrics = [metrics.sparse_categorical_accuracy])

    reduce_lr=ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=3, verbose=1, mode='auto', epsilon=0.01, cooldown=0, min_lr=0.000000000000000000001)
    stop  = EarlyStopping(monitor='val_loss', min_delta=0, patience=5, verbose=1, mode='auto')

    print "Train!"

    print model.summary()

    hist_current = model.fit(x = ,
                        y = ,
                        shuffle=False,
                        validation_data=(,),
                        validation_split=0.1,
                        epochs=150000,
                        verbose=1,
                        callbacks=[reduce_lr,stop])

model(nano_train_input,nano_train_output,nano_test_input, nano_test_output)
</code>```

The input and output is stored as a list of numpy.ndarrays.
This is a minimal working example.. how am I supposed to pass the input an output?

答:
If you take a look at your code and outputs you indeed have what you say: 24 outputs (data_train_outputs[0].shape). However, if you look at your layer output of Keras, you have this as output:

```<code>dense_3 (Dense)                  (None, 26, 145)       36395
</code>```

I would say that this should be an array with shape (None, 24)....

I suggest you add a reshape layer to get the output you want to have!

Body:
I seem to have some problems starting my learning... I am not sure why..
the network is multi input (72 1d arrays) and output is a 1d array length 24. the 1d array output consist of numbers related to 145 different classes.

So: 72 inputs => 24 outputs

Minimal working example - without the input/output being set.

import keras
from keras.utils import np_utils
from keras import metrics
from keras.models import Sequential
from keras.layers.core import Dense, Activation, Lambda, Reshape,Flatten
from keras.layers import Conv1D,Conv2D, MaxPooling2D, MaxPooling1D, Reshape, ZeroPadding2D
from keras.utils import np_utils
from keras.layers.advanced_activations import LeakyReLU, PReLU
from keras.layers.advanced_activations import ELU
from keras.models import Model
from keras.layers import Input, Dense
from keras.layers import Dropout
from keras import backend as K
from keras.callbacks import ReduceLROnPlateau
from keras.callbacks import CSVLogger
from keras.callbacks import EarlyStopping
from keras.models import load_model
from keras.layers.merge import Concatenate
import numpy as np

def chunks(l, n):
    """Yield successive n-sized chunks from l."""
    for i in range(0, len(l), n):
        yield l[i:i + n]

nano_train_input = []
nano_train_output = []
nano_test_input = []
nano_test_output = []

##   Creating train input:
for i in range(974):
    nano_train_input.append(np.random.random((78,684,4)))
    nano_train_output.append(np.random.randint(145,size=(228)).tolist())

##   Creating test input:
for i in range(104):
    nano_test_input.append(np.random.random((78,684,4)))
    nano_test_output.append(np.random.randint(145,size=(228)).tolist())

def model(train_input, train_output, test_input, test_output, names=0):

    #   Paper uses dimension (40 x 45 =(15 * 3))
    #   Filter size 5
    #   Pooling size
    #   I use dimension (78  x 72 = (24 * 3)
    #   Filter size 9

    print "In model"
    i = 0
    print_once = True
    data_test_output = []
    data_test_input = []
    for matrix in test_input:
        row,col,channel = matrix.shape
        remove_output = (col/3)%24
        remove_input  = col%72
        if remove_output > 0 :
            test_output[i] = test_output[i][:-(remove_output)]
        for split in chunks(test_output[i],24):
            data_test_output.append(np.array(split))
        if remove_input > 0:
            out = np.split(matrix[:,:-(remove_input),:-1],matrix[:,:-(remove_input),:-1].shape[1]/72,axis=1)
        else:
            out = np.split(matrix[:,:,:-1],matrix[:,:,:-1].shape[1]/72,axis=1)
        data_test_input.extend(out)
        del out
        i=i+1 # Increment

    i=0
    data_train_output = []
    data_train_input = []
    for matrix in train_input:
        row,col,channel = matrix.shape
        remove_output = (col/3)%24
        remove_input  = col%72
        if remove_output > 0 :
            train_output[i] = train_output[i][:-(remove_output)]
        for split in chunks(train_output[i],24):
            data_train_output.append(np.array(split))
        if remove_input > 0:
            out = np.split(matrix[:,:-(remove_input),:-1],matrix[:,:-(remove_input),:-1].shape[1]/72,axis=1)
        else:
            out = np.split(matrix[:,:,:-1],matrix[:,:,:-1].shape[1]/72,axis=1)
        data_train_input.extend(out)
        del out
        i=i+1 # Increment

    print
    print "Len:"
    print len(data_train_input)
    print len(data_train_output)
    print len(data_test_input)
    print len(data_test_output)
    print
    print "Type[0]:"
    print type(data_train_input[0])
    print type(data_train_output[0])
    print type(data_test_input[0])
    print type(data_test_output[0])
    print
    print "Type:"
    print type(data_train_input)
    print type(data_train_output)
    print type(data_test_input)
    print type(data_test_output)
    print
    print "shape of [0]:"
    print data_train_input[0].shape
    print data_train_output[0].shape
    print data_test_input[0].shape
    print data_test_output[0].shape

    list_of_input = [Input(shape = (78,3)) for i in range(72)]
    list_of_conv_output = []
    list_of_max_out = []

    for i in range(72):
        list_of_conv_output.append(Conv1D(filters = 32 , kernel_size = 6 , padding = "same", activation = 'relu')(list_of_input[i]))
        list_of_max_out.append(MaxPooling1D(pool_size=3)(list_of_conv_output[i]))

    merge = keras.layers.concatenate(list_of_max_out)

    reshape = Flatten()(merge)

    dense1 = Dense(units = 500, activation = 'relu',    name = "dense_1")(reshape)
    dense2 = Dense(units = 250, activation = 'relu',    name = "dense_2")(dense1)
    dense3 = Dense(units = 24 , activation = 'softmax', name = "dense_3")(dense2)

    model = Model(inputs = list_of_input , outputs = dense3)
    model.compile(loss="categorical_crossentropy", optimizer="adam" , metrics = [metrics.sparse_categorical_accuracy])

    reduce_lr=ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=3, verbose=1, mode='auto', epsilon=0.01, cooldown=0, min_lr=0.000000000000000000001)
    stop  = EarlyStopping(monitor='val_loss', min_delta=0, patience=5, verbose=1, mode='auto')

    print "Train!"

    print model.summary()

    hist_current = model.fit(x = ,
                        y = ,
                        shuffle=False,
                        validation_data=(,),
                        validation_split=0.1,
                        epochs=150000,
                        verbose=1,
                        callbacks=[reduce_lr,stop])

model(nano_train_input,nano_train_output,nano_test_input, nano_test_output)

The input and output is stored as a list of numpy.ndarrays.
This is a minimal working example.. how am I supposed to pass the input an output?

Body:
If you take a look at your code and outputs you indeed have what you say: 24 outputs (data_train_outputs[0].shape). However, if you look at your layer output of Keras, you have this as output:

dense_3 (Dense)                  (None, 26, 145)       36395

I would say that this should be an array with shape (None, 24)....

I suggest you add a reshape layer to get the output you want to have!


问:
Mysql Query to Merge Two Condition Into One Row
I just get confused. Already tried to search this whole site or google but didn't find the 'nearest' solution.

Ok let's say I have this table structure.

```<code>id date       finger_id finger_time is_enter
1  2017-03-30  2          09:00       1
2  2017-03-30  2          17:13       0
3  2017-03-31  4          09:10       1
4  2017-03-31  3          09:01       1
5. 2017-03-31  3          17:00       0
</code>```

I want to make the table to be like below.

```<code>date       finger_id  enter_time  exit_time
2017-03-30   2        09:00       17:13
2017-03-30   4        09:10
2017-03-31   3        09:10       17:00
</code>```

I have made sql statement but it turns like this.

```<code>date       finger_id  enter_time   exit_time
2017-03-30  2         09:00
2017-03-30  2                       17:13
2017-03-31  4         09:10
2017-03-31  3         09:01
2017-03-31  3                       17:00
</code>```

I just want to know how to merge the is_enter 1 with is_enter 0 on the same date by the finger_id column.

Here's my sql query for the reference.

```<code>SELECT *
FROM `tbl_fingerprint`
    LEFT JOIN `tbl_employee` ON `tbl_employee`.`fingerprint_id`=`tbl_fingerprint`.`fingerprint_id`
    LEFT JOIN `tbl_position` ON `tbl_position`.`position_id`=`tbl_employee`.`position_id`
WHERE `fingerprint_date` >= '2017-03-01'
AND `fingerprint_date` <= '2017-04-01'
GROUP BY `tbl_fingerprint`.`fingerprint_id`,
         `tbl_fingerprint`.`fingerprint_date`,
         `tbl_fingerprint`.`is_enter`
ORDER BY `fingerprint_date` ASC LIMIT 30
</code>```

Thanks for your help guys.

答:
You can do a group by date and finger_id fields and use conditional expression (case or if()) within an aggregate function to get the expected outcome. The conditional statements within the aggregate function make sure that they return value only if the right value is set in is_enter field. I leave out the employee details, since those do not form part of your question:

```<code>SELECT date, fingerprint_id, max(if(is_enter=1,finger_time,null) as enter_time, max(if(is_enter=0,finger_time,null) as exit_time
FROM `tbl_fingerprint`
WHERE `fingerprint_date` >= '2017-03-01'
AND `fingerprint_date` <= '2017-04-01'
GROUP BY `tbl_fingerprint`.`fingerprint_id`,
         `tbl_fingerprint`.`fingerprint_date`,
ORDER BY `fingerprint_date` ASC LIMIT 30
</code>```

Body:
I just get confused. Already tried to search this whole site or google but didn't find the 'nearest' solution.

Ok let's say I have this table structure.

id date       finger_id finger_time is_enter
1  2017-03-30  2          09:00       1
2  2017-03-30  2          17:13       0
3  2017-03-31  4          09:10       1
4  2017-03-31  3          09:01       1
5. 2017-03-31  3          17:00       0

I want to make the table to be like below.

date       finger_id  enter_time  exit_time
2017-03-30   2        09:00       17:13
2017-03-30   4        09:10
2017-03-31   3        09:10       17:00

I have made sql statement but it turns like this.

date       finger_id  enter_time   exit_time
2017-03-30  2         09:00
2017-03-30  2                       17:13
2017-03-31  4         09:10
2017-03-31  3         09:01
2017-03-31  3                       17:00

I just want to know how to merge the is_enter 1 with is_enter 0 on the same date by the finger_id column.

Here's my sql query for the reference.

SELECT *
FROM `tbl_fingerprint`
    LEFT JOIN `tbl_employee` ON `tbl_employee`.`fingerprint_id`=`tbl_fingerprint`.`fingerprint_id`
    LEFT JOIN `tbl_position` ON `tbl_position`.`position_id`=`tbl_employee`.`position_id`
WHERE `fingerprint_date` >= '2017-03-01'
AND `fingerprint_date` <= '2017-04-01'
GROUP BY `tbl_fingerprint`.`fingerprint_id`,
         `tbl_fingerprint`.`fingerprint_date`,
         `tbl_fingerprint`.`is_enter`
ORDER BY `fingerprint_date` ASC LIMIT 30

Thanks for your help guys.

Body:
You can do a group by date and finger_id fields and use conditional expression (case or if()) within an aggregate function to get the expected outcome. The conditional statements within the aggregate function make sure that they return value only if the right value is set in is_enter field. I leave out the employee details, since those do not form part of your question:

SELECT date, fingerprint_id, max(if(is_enter=1,finger_time,null) as enter_time, max(if(is_enter=0,finger_time,null) as exit_time
FROM `tbl_fingerprint`
WHERE `fingerprint_date` >= '2017-03-01'
AND `fingerprint_date` <= '2017-04-01'
GROUP BY `tbl_fingerprint`.`fingerprint_id`,
         `tbl_fingerprint`.`fingerprint_date`,
ORDER BY `fingerprint_date` ASC LIMIT 30