问:
Subversion, renaming, Wha?
So i have a funny problem.

Subversion, you are not allowed to rename items with the same name if the only difference is capitalization.  Netbeans has subversion.  Netbeans allows you to rename files if the capitalization changes.

I renamed something called eventCreator.php to EventCreator.php in subversion and uploaded (it is a class).  Everything went fine in Netbeans.  In fact, I made about 10 more commits. I tried to download it on another computer, and this is the error that happens

"Can't open file
C:\xampp\htdocs\MyProject\scripts.svn\tmp\text-base\eventCreator.php.svn-base':
The system cannot find the file specified."

My repository is located at DreamHost.  So i go to dreamhost and i am able to go into the scripts folder and see both eventCreator.php and EventCreator.php in the repository, yet i cannot download it with either netbeans or tortoiseSVN.
Any Help?

答:
Subversion is case sensitive. If you tell it store 20 files all with different combination of case, it'll store it.  Now, when you check those files out of the repository, the platform you're on may either warn you, refuse to check out (as it did in your case), or just overwrite the content of the first file written with the second, third, you get the idea.

To resolve this, zerkms' answer is right on track.  Delete the rendition of the file you don't want with a repo browser or some tool (command line if need be) that works directly with the repository on the server.

To keep this from happening again, use the case-insensitive.py script from the Subversion project in your pre-commit hook script.  It'll do a check to see if there is already file in the repository with a different case when the commit is adding a file.  If there is, it'll allow you to reject the commit until it's resolved.

Since you have a third party hosting your Subversion repository, contact them about getting this hook applied if you cannot do with their management tools.

Title: Subversion, renaming, Wha?


来源: stackexchange

问:
How to execute business logic handler in a separate thread pool using netty
I have a handler that needs to execute some business logic and I want that to be executed in a separate thread pool to not block the io event loop. I have added DefaultEventExecutorGroup into the pipeline as specified in http://netty.io/4.0/api/io/netty/channel/ChannelPipeline.html javadoc and http://netty.io/wiki/new-and-noteworthy-in-4.0.html#no-more-executionhandler---its-in-the-core wiki:

```<code>ch.pipeline().addLast(new DefaultEventExecutorGroup(10), new ServerHandler());
</code>```

Just for testing purposes my ServerHandler just puts the current thread to sleep for 5 seconds:

```<code>protected void channelRead0(ChannelHandlerContext ctx, Command cmd) throws Exception {
    System.out.println("Starting.");

    try {
        Thread.currentThread().sleep(5000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    System.out.println("Finished.");
}
</code>```

But apparently the business logic is still executed synchronously:

```<code>Starting.
Finished.
Starting.
Finished.
Starting.
Finished.
</code>```

What am I missing?

答: Because the Netty handle the request which is sended from same socket by the same EventExecutor,so you can start more than one client,and see the result.

ContentLicense: CC BY-SA 3.0

Body:
I have a handler that needs to execute some business logic and I want that to be executed in a separate thread pool to not block the io event loop. I have added DefaultEventExecutorGroup into the pipeline as specified in http://netty.io/4.0/api/io/netty/channel/ChannelPipeline.html javadoc and http://netty.io/wiki/new-and-noteworthy-in-4.0.html#no-more-executionhandler---its-in-the-core wiki:

ch.pipeline().addLast(new DefaultEventExecutorGroup(10), new ServerHandler());

Just for testing purposes my ServerHandler just puts the current thread to sleep for 5 seconds:

protected void channelRead0(ChannelHandlerContext ctx, Command cmd) throws Exception {
    System.out.println("Starting.");

    try {
        Thread.currentThread().sleep(5000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    System.out.println("Finished.");
}

But apparently the business logic is still executed synchronously:

Starting.
Finished.
Starting.
Finished.
Starting.
Finished.

What am I missing?


问:
unabe to Reload data in tableview via userdefault
I am a newbie and learning  ios programming. I have made a custom table view cell. I am trying to append data in it via user defaults but its not storing the data, every time i go back the app refreshes  making the table view blank screen.

```<code>// data sent from here

class ViewController: UIViewController {

    @IBOutlet weak var textfield: UITextField!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    @IBAction func submit(_ sender: AnyObject) {

        performSegue(withIdentifier: "move", sender: nil)
    }
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let destination = segue.destination as? secondviewcontroller

        destination?.list.append(textfield.text!)

        let defaults = UserDefaults.standard
        defaults.set(destination?.list, forKey: "listarray")
        UserDefaults.standard.synchronize()

    }
}

// here i want to retreive
class secondviewcontroller: UIViewController {

    @IBOutlet weak var tblView: UITableView!
    var list = ["fahad","Ali","tahir"]

   var abc = ""

override func viewDidLoad() {
    super.viewDidLoad()
    tblView.dataSource  = self;
    tblView.delegate = self;

    let storedarray = UserDefaults.standard.object(forKey: "listarray")

    print("hi\(storedarray)")
}

override func viewDidAppear(_ animated: Bool) {
     tblView.register(TableViewCell.self, forCellReuseIdentifier: "TableViewCell")
    tblView.reloadData()
}

@IBAction func backbtn(_ sender: AnyObject) {
    dismiss(animated: true, completion: nil)
}
</code>```

}

import UIKit

class secondviewcontroller: UIViewController {

```<code>@IBOutlet weak var tblView: UITableView!
var list = ["fahad","Ali","tahir"]
</code>```

var abc = ""

```<code>override func viewDidLoad() {
    super.viewDidLoad()
    tblView.dataSource  = self;
    tblView.delegate = self;

}

override func viewDidAppear(_ animated: Bool) {
     tblView.register(TableViewCell.self, forCellReuseIdentifier: "TableViewCell")
    let storedarray = UserDefaults.standard.object(forKey: "listarray")

    print("hi\(storedarray)")
    tblView.reloadData()
}

@IBAction func backbtn(_ sender: AnyObject) {
    dismiss(animated: true, completion: nil)
}
</code>```

}

extension secondviewcontroller : UITableViewDataSource , UITableViewDelegate{

```<code>func numberOfSections(in tableView: UITableView) -> Int {

    return 1;
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    print (list)
    return list.count;
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    var cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell", for: indexPath) as! TableViewCell;
    cell.textlabel.text = list[indexPath.row];

    return cell;

}
</code>```

}

```<code>// my custom table view
import UIKit

class   TableViewCell: UITableViewCell {

    @IBOutlet weak var textlabel: UILabel!
    override func awakeFromNib() {
        super.awakeFromNib()
    }
}
</code>```

My UI storyboardgetting this error

答:
you must subclass the UITableViewDelegate and UITableViewDataSource methods and implement the required methods for it to display the data in your custom view.
refer to this: http://clean-swift.com/refactoring-table-view-data-source-and-delegate-methods/

try adding the code for stored array into the viewwillappear method..

Body:
I am a newbie and learning  ios programming. I have made a custom table view cell. I am trying to append data in it via user defaults but its not storing the data, every time i go back the app refreshes  making the table view blank screen.

// data sent from here

class ViewController: UIViewController {

    @IBOutlet weak var textfield: UITextField!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    @IBAction func submit(_ sender: AnyObject) {

        performSegue(withIdentifier: "move", sender: nil)
    }
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let destination = segue.destination as? secondviewcontroller

        destination?.list.append(textfield.text!)

        let defaults = UserDefaults.standard
        defaults.set(destination?.list, forKey: "listarray")
        UserDefaults.standard.synchronize()

    }
}

// here i want to retreive
class secondviewcontroller: UIViewController {

    @IBOutlet weak var tblView: UITableView!
    var list = ["fahad","Ali","tahir"]

   var abc = ""

override func viewDidLoad() {
    super.viewDidLoad()
    tblView.dataSource  = self;
    tblView.delegate = self;

    let storedarray = UserDefaults.standard.object(forKey: "listarray")

    print("hi\(storedarray)")
}

override func viewDidAppear(_ animated: Bool) {
     tblView.register(TableViewCell.self, forCellReuseIdentifier: "TableViewCell")
    tblView.reloadData()
}

@IBAction func backbtn(_ sender: AnyObject) {
    dismiss(animated: true, completion: nil)
}

}

import UIKit

class secondviewcontroller: UIViewController {

@IBOutlet weak var tblView: UITableView!
var list = ["fahad","Ali","tahir"]

var abc = ""

override func viewDidLoad() {
    super.viewDidLoad()
    tblView.dataSource  = self;
    tblView.delegate = self;

}

override func viewDidAppear(_ animated: Bool) {
     tblView.register(TableViewCell.self, forCellReuseIdentifier: "TableViewCell")
    let storedarray = UserDefaults.standard.object(forKey: "listarray")

    print("hi\(storedarray)")
    tblView.reloadData()
}

@IBAction func backbtn(_ sender: AnyObject) {
    dismiss(animated: true, completion: nil)
}

}

extension secondviewcontroller : UITableViewDataSource , UITableViewDelegate{

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

    return 1;
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    print (list)
    return list.count;
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    var cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell", for: indexPath) as! TableViewCell;
    cell.textlabel.text = list[indexPath.row];

    return cell;

}

}

// my custom table view
import UIKit

class   TableViewCell: UITableViewCell {

    @IBOutlet weak var textlabel: UILabel!
    override func awakeFromNib() {
        super.awakeFromNib()
    }
}

My UI storyboardgetting this error


问:
endswith() matching?
I am using the code below to match using endswith in Python.

```<code>while not buff.endswith('/abc #'):
</code>```

But I run into a problem when the line ends as shown below:

```<code>('console /abc/xyz* #')

('console /abc/xyz/pqrs* #')
</code>```

Now how to match with endswith for "/abc" anywhere, but # must be the last character?

答:
If the number of paths you're trying to match is small, you can supply a tuple to the endswith method.

```<code>>>> buffs = ["console /abc #", "console /abc/d #", "console /abc/xyz/* #"]
>>> for b in buffs: print(b.endswith("#"))
...
True
True
True
>>> for b in buffs: print(b.endswith("/abc #"))
...
True
False
False
>>> for b in buffs: print(b.endswith(("/abc #", "/abc/d #")))
...
True
True
False
>>>
</code>```

Otherwise you'll need to use a regular expression for your search, e.g.

```<code>>>> import re
>>> p = re.compile(r"/abc.*#$")  # match "/abc", anything, "#", then EoL
>>> for b in buffs: print(p.search(b) != None)
...
True
True
True
</code>```

Title: endswith() matching?

Body:
I am using the code below to match using endswith in Python.

while not buff.endswith('/abc #'):

But I run into a problem when the line ends as shown below:

('console /abc/xyz* #')

('console /abc/xyz/pqrs* #')

Now how to match with endswith for "/abc" anywhere, but # must be the last character?

Body:
If the number of paths you're trying to match is small, you can supply a tuple to the endswith method.

>>> buffs = ["console /abc #", "console /abc/d #", "console /abc/xyz/* #"]
>>> for b in buffs: print(b.endswith("#"))
...
True
True
True
>>> for b in buffs: print(b.endswith("/abc #"))
...
True
False
False
>>> for b in buffs: print(b.endswith(("/abc #", "/abc/d #")))
...
True
True
False
>>>

Otherwise you'll need to use a regular expression for your search, e.g.

>>> import re
>>> p = re.compile(r"/abc.*#$")  # match "/abc", anything, "#", then EoL
>>> for b in buffs: print(p.search(b) != None)
...
True
True
True


问:
MySql select - groupBy very upset?
Maybe this question will be too wide but i really need this so:

I have table with ~80k rows and ~160 columns (a lot i know). And unfortunately i have routine selects for example:

```<code>SELECT hotelName
     , country
     , locality
     , destination
     , foodType
     , hotelStars
     , departureDateFrom
     , departureDateTo
     , MIN(price)
  FROM table
 WHERE locality
   IN (
     '1', '2', '3'
   )
   AND visible IS NOT NULL
   AND departureDateFrom >= (?)
   AND departureDateTo <= (?)
   AND foodType = (?)
   AND hotelStars = (?)
   AND country
   IN (
     '1', '2', '3'
   )
 GROUP
    BY hotelId
 ORDER
    BY price ASC
</code>```

In table are tours. So you can have 250 records with same hotel name, locality... but with different price or departureDate. Primary key is id which in this example does not figure. hotelId is id from another system and it purpose in this project is only for 'get hotel detail' and groupBy (guarantees unique hotel to results)

point is - i must in every select make groupBy + MIN() + order.

So main problem is long query time ~250ms per request.

Average my select have 10-15 columns. I think the problem is because select 'touches' ~70% rows and AFTER that is groupBy and it will return ~200-400 results.

I have most used columns indexed of course. (column for MIN(), groupBy and order are indexed too)

Caching is imposible in this case.

Data structure i can't influence.

Have I some other options to make it quicker?

Will be helpful reduce number of columns? Let say to 60 columns?

UPDATE

table was reduced to 65 columns

all indexes was dropped now is only one (BTREE) on column hotelId for groupBy

some datatypes was optimized for example int(11) to int(5) on hotelId

And we are now on -25% response time, so now we are on ~190ms.

Any ideas to get some acceptable response time? Our goal is ~100ms (still a lot but acceptable).

From profiler:

starting    0.000101

checking permissions    0.000007

Opening tables  0.000013

init    0.000046

System lock     0.000011

optimizing  0.000016

statistics  0.000096

preparing   0.000020

Creating tmp table  0.000029

Sorting for group   0.000011

Sorting result  0.000006

executing   0.000004

Sending data    0.176949

Creating sort index     0.000916

end     0.000009

query end   0.000011

removing tmp table  0.000602

query end   0.000008

closing tables  0.000012

freeing items   0.000052

cleaning up     0.000033

答:
The numbers you provide sound like the entire table is cached in RAM.  So, it is probably not I/O-bound.

Touching 56K rows takes time, regardless.

The best index may be this composite INDEX(col1, col2, col3).  (Please adjust your terminology between "rows" and "columns".)

GROUP BY col5  ORDER BY col6 will necessarily create two temp tables, and sort each.

It is usually improper to GROUP BY col5 while SELECTing columns (col2, col3, col6) that are (apparently) not dependent on the GROUP BY column(s).  You will get random values for those three columns.  OK, maybe col5 is UNIQUE, therefor there is no problem.  (Please provide the real names if you can; it will help us to help you.)

I suspect you have a lot of variety in the columns involved, otherwise, I would suggest a "covering" INDEX(col1, col2, col3, col4, col5, col6) - the first 3 columns in that order, the rest in any order.

Oh, what is the PRIMARY KEY?  It may matter.

Title: MySql select - groupBy very upset?

Body:
Maybe this question will be too wide but i really need this so:

I have table with ~80k rows and ~160 columns (a lot i know). And unfortunately i have routine selects for example:

SELECT hotelName
     , country
     , locality
     , destination
     , foodType
     , hotelStars
     , departureDateFrom
     , departureDateTo
     , MIN(price)
  FROM table
 WHERE locality
   IN (
     '1', '2', '3'
   )
   AND visible IS NOT NULL
   AND departureDateFrom >= (?)
   AND departureDateTo <= (?)
   AND foodType = (?)
   AND hotelStars = (?)
   AND country
   IN (
     '1', '2', '3'
   )
 GROUP
    BY hotelId
 ORDER
    BY price ASC

In table are tours. So you can have 250 records with same hotel name, locality... but with different price or departureDate. Primary key is id which in this example does not figure. hotelId is id from another system and it purpose in this project is only for 'get hotel detail' and groupBy (guarantees unique hotel to results)

point is - i must in every select make groupBy + MIN() + order.

So main problem is long query time ~250ms per request.

Average my select have 10-15 columns. I think the problem is because select 'touches' ~70% rows and AFTER that is groupBy and it will return ~200-400 results.

I have most used columns indexed of course. (column for MIN(), groupBy and order are indexed too)

Caching is imposible in this case.

Data structure i can't influence.

Have I some other options to make it quicker?

Will be helpful reduce number of columns? Let say to 60 columns?

UPDATE

table was reduced to 65 columns

all indexes was dropped now is only one (BTREE) on column hotelId for groupBy

some datatypes was optimized for example int(11) to int(5) on hotelId

And we are now on -25% response time, so now we are on ~190ms.

Any ideas to get some acceptable response time? Our goal is ~100ms (still a lot but acceptable).

From profiler:

starting    0.000101

checking permissions    0.000007

Opening tables  0.000013

init    0.000046

System lock     0.000011

optimizing  0.000016

statistics  0.000096

preparing   0.000020

Creating tmp table  0.000029

Sorting for group   0.000011

Sorting result  0.000006

executing   0.000004

Sending data    0.176949

Creating sort index     0.000916

end     0.000009

query end   0.000011

removing tmp table  0.000602

query end   0.000008

closing tables  0.000012

freeing items   0.000052

cleaning up     0.000033


问:
QTableWidget: How can I get tighter lines with less vertical spacing padding?
The QTableWdiget is fabulous for simple grid displays.  Changing colors, fonts, etc is straightforward.

However, I did not manage to give the grid a 'tighter' look with less vertical whitespace.  I see that the Qt documentation talks (eg here) about

margin

border

padding

around widgets, but when I set these I only get changes around the entire grid widget rather than inside.

How can I set this (with a style sheet, or hard-coded options) directly to make the QTableWidget display tighter?

答: QTableWidget -> verticalHeader -> setMinimumSectionSize() is the right way, and it can be set in ui.</p>

ContentLicense: CC BY-SA 2.5


问:
Delphi Comport not getting the complete Data
I have this code:

```<code>procedure Tfrm_main.cport_scanningRxChar(Sender: TObject; Count: Integer);
begin
  cport_scanning.ReadStr(data, Count);
  memo3.Text := data;
end;
</code>```

The actual result is:

```<code>memo3.text := M000000;
</code>```

Then it changed into:

```<code>memo3.text := 021111D;
</code>```

The expected result:

```<code>memo3.text := M000000021111D;
</code>```

答:
In future, it would help to indicate what component you're using, especially since TComPort does not come with Delphi.

The answer is because OnRxChar can be called before all data has been received. Your code should read:

```<code>procedure Tfrm_main.cport_scanningRxChar(Sender: TObject; Count: Integer);
begin
  cport_scanning.ReadStr(data, Count);
  memo3.Text := memo3.Text + data;
end;
</code>```

Body:
I have this code:

procedure Tfrm_main.cport_scanningRxChar(Sender: TObject; Count: Integer);
begin
  cport_scanning.ReadStr(data, Count);
  memo3.Text := data;
end;

The actual result is:

memo3.text := M000000;

Then it changed into:

memo3.text := 021111D;

The expected result:

memo3.text := M000000021111D;

Body:
In future, it would help to indicate what component you're using, especially since TComPort does not come with Delphi.

The answer is because OnRxChar can be called before all data has been received. Your code should read:

procedure Tfrm_main.cport_scanningRxChar(Sender: TObject; Count: Integer);
begin
  cport_scanning.ReadStr(data, Count);
  memo3.Text := memo3.Text + data;
end;


问:
Copy only executable files (cross platform)
I want to copy executable files from one directory to another.

The source directory includes all sorts of files I don't care about (build artifacts). I want to grab only the executable files, using a bash script that works on both OS X and Linux.

By executable, I mean a file that has the executable permission, and would pass test -x $filename.

I know I can write some python script but then I would be introducing a dependency on python (just to copy files!) which is something I really want to avoid.

Note: I've seem a couple of similar questions but the answers seem to only work on Linux (as the questions specifically asked about Linux). Please do not mark this as duplicate unless the duplicate question is indeed about cross platform copying of executable files only.

答:
After some experimentation, this seems to work on both OS X and Ubuntu

```<code>find "$src_dir" -maxdepth 1 -type f -exec test -x {} \; -exec cp {} "$dest_dir/" \;
</code>```

Note that the -maxdepth 1 is specific to my use case where I don't care about recursively going through all the directories.

-type f is necessary because directories also count as executables

I pass two -exec flags. The exec flag not only executes the command but also counts as a filter so that if the command returns a non-zero exit code, the file is filtered out.

The way to use exec is write out whatever command you want, use {} to supply the current file, and terminate with \;

The first -exec returns a success exit code only if the file is executable.

The second -exec performs the copy, but it's not executed if the first -exec fails.

Body:
After some experimentation, this seems to work on both OS X and Ubuntu

find "$src_dir" -maxdepth 1 -type f -exec test -x {} \; -exec cp {} "$dest_dir/" \;

Note that the -maxdepth 1 is specific to my use case where I don't care about recursively going through all the directories.

-type f is necessary because directories also count as executables

I pass two -exec flags. The exec flag not only executes the command but also counts as a filter so that if the command returns a non-zero exit code, the file is filtered out.

The way to use exec is write out whatever command you want, use {} to supply the current file, and terminate with \;

The first -exec returns a success exit code only if the file is executable.

The second -exec performs the copy, but it's not executed if the first -exec fails.


问:
getting value of array from certain index in php
I want to get the value of an array type given a certain index. The array's values are

$status = [1,2];

And I used these code to get the value:

$task_state = $status[1];

But it actually thought $status is a string and returns

'['

I know that this is actually quite simple, but I just can't seem to find the answer to my problem. Thank you

答:
If $status defined as a string, you can return php value of it with eval function like below:

```<code>$status = '[1,2]';
$status_array = eval('return ' . $status . ';');
$task_state = $status_array[0];
</code>```

Caution
  The eval() language construct is very dangerous because it allows execution of arbitrary PHP code. Its use thus is discouraged. If you have carefully verified that there is no other option than to use this construct, pay special attention not to pass any user provided data into it without properly validating it beforehand.

Body:
If $status defined as a string, you can return php value of it with eval function like below:

$status = '[1,2]';
$status_array = eval('return ' . $status . ';');
$task_state = $status_array[0];

Caution
  The eval() language construct is very dangerous because it allows execution of arbitrary PHP code. Its use thus is discouraged. If you have carefully verified that there is no other option than to use this construct, pay special attention not to pass any user provided data into it without properly validating it beforehand.


问:
Question about combo box and labels
I have a combo box that contains 5 items. I have one label on the window. What i would like to do is whenever a user clicks on one of the items in the combobox, text will populate that label. I would like to show information about whichever item is selected (IP address, etc.). Any help is appreciated. Thanks.

Code:

```<code>private void cmbGroups_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    //Combo box selection changed. Re-bind data
    string selectedGroup = (string)cmbGroups.SelectedItem;
    BindGrid(selectedGroup);
}
</code>```

Code:

```<code>    private void BindGrid(string selectedGroup)
    {
        //Re-bind the grid
        dgPortStatus.DataContext = _dicPortStatus[selectedGroup].Portstatus.DefaultView;

        InitializeColumns();
    }
</code>```

Code:

```<code>private void _UpdatePortStatus()
    {
        string[] files = Directory.GetFiles(System.Configuration.ConfigurationSettings.AppSettings["portStatusDir"], "PortStatus.*");

        foreach (string file in files)
        {

            PortStatus ps = new PortStatus();
            ps.ReadXml(new StreamReader(file));
            //ps.ReadXml(new FileStream(file, FileMode.Open, FileAccess.Read));

            if (!_dicPortStatus.ContainsKey(ps.General[0].Group))
            {
                _dicPortStatus.Add(ps.General[0].Group, ps);
            }

            PortStatus psOrig = _dicPortStatus[ps.General[0].Group];

            foreach (PortStatus.PortstatusRow psr in ps.Portstatus.Rows)
            {
                DataRow[] drs = psOrig.Portstatus.Select("PortNumber = '" + psr.PortNumber + "'");

                if (drs.Length == 1)
                {
                    DateTime curDt = DateTime.Parse(drs[0]["LastUpdateDateTimeUTC"].ToString());
                    DateTime newDt = psr.LastUpdateDateTimeUTC;

                    if (newDt > curDt)
                    {
                        drs[0]["LastUpdateDateTimeUTC"] = newDt;
                    }
                }
                else if (drs.Length == 0)
                {
                    psOrig.Portstatus.ImportRow(psr);
                }
                else
                {
                    throw new Exception("More than one of the same portnumber on PortStatus file: " + file);
                }
            }
        }

        foreach (string groupName in _dicPortStatus.Keys)
        {
            if (!cmbGroups.Items.Contains(groupName))
            {
                cmbGroups.Items.Add(groupName);
                cmbGroups.SelectedItem = groupName;
            }
        }
</code>```

Code:

```<code>private Dictionary<string, PortStatus> _dicPortStatus = new Dictionary<string, PortStatus>()
</code>```

答:
in Win Forms:</p>

```<code>comboBox.SelectedIndexChanged += onSelectedIndexChanged;

private void onSelectedIndexChanged(object sender, EventArgs e)
{
  object item = comboBox.SelectedItem;
  string text = //get text from item
  label.Text = text;
}
</code>```

Title: Question about combo box and labels

Body:
I have a combo box that contains 5 items. I have one label on the window. What i would like to do is whenever a user clicks on one of the items in the combobox, text will populate that label. I would like to show information about whichever item is selected (IP address, etc.). Any help is appreciated. Thanks.

Code:

private void cmbGroups_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    //Combo box selection changed. Re-bind data
    string selectedGroup = (string)cmbGroups.SelectedItem;
    BindGrid(selectedGroup);
}

Code:

    private void BindGrid(string selectedGroup)
    {
        //Re-bind the grid
        dgPortStatus.DataContext = _dicPortStatus[selectedGroup].Portstatus.DefaultView;

        InitializeColumns();
    }

Code:

private void _UpdatePortStatus()
    {
        string[] files = Directory.GetFiles(System.Configuration.ConfigurationSettings.AppSettings["portStatusDir"], "PortStatus.*");

        foreach (string file in files)
        {

            PortStatus ps = new PortStatus();
            ps.ReadXml(new StreamReader(file));
            //ps.ReadXml(new FileStream(file, FileMode.Open, FileAccess.Read));

            if (!_dicPortStatus.ContainsKey(ps.General[0].Group))
            {
                _dicPortStatus.Add(ps.General[0].Group, ps);
            }

            PortStatus psOrig = _dicPortStatus[ps.General[0].Group];

            foreach (PortStatus.PortstatusRow psr in ps.Portstatus.Rows)
            {
                DataRow[] drs = psOrig.Portstatus.Select("PortNumber = '" + psr.PortNumber + "'");

                if (drs.Length == 1)
                {
                    DateTime curDt = DateTime.Parse(drs[0]["LastUpdateDateTimeUTC"].ToString());
                    DateTime newDt = psr.LastUpdateDateTimeUTC;

                    if (newDt > curDt)
                    {
                        drs[0]["LastUpdateDateTimeUTC"] = newDt;
                    }
                }
                else if (drs.Length == 0)
                {
                    psOrig.Portstatus.ImportRow(psr);
                }
                else
                {
                    throw new Exception("More than one of the same portnumber on PortStatus file: " + file);
                }
            }
        }

        foreach (string groupName in _dicPortStatus.Keys)
        {
            if (!cmbGroups.Items.Contains(groupName))
            {
                cmbGroups.Items.Add(groupName);
                cmbGroups.SelectedItem = groupName;
            }
        }

Code:

private Dictionary<string, PortStatus> _dicPortStatus = new Dictionary<string, PortStatus>()

Body:
in Win Forms:

comboBox.SelectedIndexChanged += onSelectedIndexChanged;

private void onSelectedIndexChanged(object sender, EventArgs e)
{
  object item = comboBox.SelectedItem;
  string text = //get text from item
  label.Text = text;
}


问:
scrollView images are not in the center using midX?
I used two statements in my code when initializing newX variable which I believe they should give the same result but one didn't, which are:

```<code>( scrollView.frame.size.width / 2 ) - 75
</code>```

And

```<code>scrollView.frame.midX - 75
</code>```

here is my code, look for the comment at the middle:

```<code>class ViewController: UIViewController {

@IBOutlet weak var scrollView: UIScrollView!
var images = [UIImageView]()

var contentWidth: CGFloat = 0.0
override func viewDidAppear(_ animated: Bool) {

    for i in 0...2 {

        let image = UIImage(named: "icon\(i).png")
        let imageView = UIImageView(image: image)

        //  Here is the problem
        let newX = (scrollView.frame.size.width / 2 + scrollView.frame.size.width * CGFloat(i)) - 75
        let newY = scrollView.frame.midY - 75
        imageView.frame = CGRect(x: newX, y: newY, width: 150, height: 150)
        scrollView.addSubview(imageView)
        contentWidth += scrollView.frame.size.width

    }

    scrollView.contentSize = CGSize(width: contentWidth, height: view.frame.size.height)
    scrollView.clipsToBounds = false
    scrollView.backgroundColor = UIColor.purple
}}
</code>```

The first one perfectly centred the images, but when I replaced it with the second on it didn't center them as shown in the picture here
Code Representation . why?

答:
The difference is that midX is considering also the position of the scrollview's origin, so midX would be half the width of your scrollView + the X origin of your scrollView. (Similar to how minX is not always 0)

Width, on the other hand, is, well, the width of the scrollView, which is absolute.

Body:
I used two statements in my code when initializing newX variable which I believe they should give the same result but one didn't, which are:

( scrollView.frame.size.width / 2 ) - 75

And

scrollView.frame.midX - 75

here is my code, look for the comment at the middle:

class ViewController: UIViewController {

@IBOutlet weak var scrollView: UIScrollView!
var images = [UIImageView]()

var contentWidth: CGFloat = 0.0
override func viewDidAppear(_ animated: Bool) {

    for i in 0...2 {

        let image = UIImage(named: "icon\(i).png")
        let imageView = UIImageView(image: image)

        //  Here is the problem
        let newX = (scrollView.frame.size.width / 2 + scrollView.frame.size.width * CGFloat(i)) - 75
        let newY = scrollView.frame.midY - 75
        imageView.frame = CGRect(x: newX, y: newY, width: 150, height: 150)
        scrollView.addSubview(imageView)
        contentWidth += scrollView.frame.size.width

    }

    scrollView.contentSize = CGSize(width: contentWidth, height: view.frame.size.height)
    scrollView.clipsToBounds = false
    scrollView.backgroundColor = UIColor.purple
}}

The first one perfectly centred the images, but when I replaced it with the second on it didn't center them as shown in the picture here
Code Representation . why?


问:
Why would SQL be very slow when doing updates?
Suddenly doing updates into a few tables have gotten 10 times slower than they used to be.  What are some good recommendations to determine root cause and optimization?  Could it be that indexing certain columns are causing updates to be slow?  Any other recommendations?

I guess more important than guesses would be help on the process of identifying the root cause or metrics around performance.

Is there anything in Fluent NHibernate that you can use to help identify the root cause of performance issues?

答: Its worth checking your growth settings on the data files, if you're doing a lot of inserts which forces regular file grows it can manifest as slowdown.</p>


问:
I can't fix the gap between body and footer
There seems to be a gap between the footer and main body. i want the body to touch the footer, as seen i want it to completely fill up the space in the middle.

https://ibb.co/dUpFJF

@charset "utf-8";

/* CSS Document */

body {
  font-family: 'Droid Sans', sans-serif;
  margin-top: 0px;
  margin-left: 0px;
  margin-right: 0px;
  margin-bottom: 0px;
  min-height: 100%;
}

.div_top1 {
  height: 30px;
  margin: 0 auto;
  width: 100%;
  border-bottom: 1px solid #FFF;
  background-color: #2d2d2d;
}

.div_top2 {
  height: 150px;
  width: 100%;
  background-color: #072135;
}

.main_container {
  width: 100%;
  margin: 0 auto;
  background-color: #FFF;
  overflow: auto;
  min-height: 100%;
  display: inline-block;
}

.container_right {
  height: 100%;
  padding-left: 20px;
  margin: 0 auto;
}

.container_left {
  float: left;
  text-align: left;
  border-right: 2px solid #5a5c5d;
  border-bottom: 1px solid #5a5c5d;
  height: 100%;
  overflow: hidden;
}

.bk {
  border-top: 4px solid #da6161;
  display: table;
  height: 200px;
  margin: 0 auto;
  margin-top: 30px;
  padding: 8px;
}

.icon {
  float: left;
  display: block;
}

.icon-bar {
  width: 70px;
  /* Set a specific width */
  background-color: #FFF;
  /* Dark-grey background */
  height: 100%;
}

.icon-bar a {
  display: block;
  /* Make the links appear below each other instead of side-by-side */
  text-align: center;
  /* Center-align text */
  padding: 16px;
  /* Add some padding */
  transition: all 0.3s ease;
  /* Add transition for hover effects */
  color: black;
  /* White text color */
  font-size: 27px;
  /* Increased font-size */
  height: 100%;
}

.icon-bar a:hover {
  background-color: #5a5c5d;
  /* Add a hover color */
}

.active {
  background-color: #818384;
  /* Add an active/current color */
}

Body:
When using floats you disturb the normal document flow. Change the definition of .foot as follows:

@charset "utf-8";

/* CSS Document */

body {
  font-family: 'Droid Sans', sans-serif;
  margin-top: 0px;
  margin-left: 0px;
  margin-right: 0px;
  margin-bottom: 0px;
  min-height: 100%;
}

.div_top1 {
  height: 30px;
  margin: 0 auto;
  width: 100%;
  border-bottom: 1px solid #FFF;
  background-color: #2d2d2d;
}

.div_top2 {
  height: 150px;
  width: 100%;
  background-color: #072135;
}

.main_container {
  width: 100%;
  margin: 0 auto;
  background-color: #FFF;
  overflow: auto;
  min-height: 100%;
  display: inline-block;
}

.container_right {
  height: 100%;
  padding-left: 20px;
  margin: 0 auto;
}

.container_left {
  float: left;
  text-align: left;
  border-right: 2px solid #5a5c5d;
  border-bottom: 1px solid #5a5c5d;
  height: 100%;
  overflow: hidden;
}

.bk {
  border-top: 4px solid #da6161;
  display: table;
  height: 200px;
  margin: 0 auto;
  margin-top: 30px;
  padding: 8px;
}

.icon {
  float: left;
  display: block;
}

.icon-bar {
  width: 70px;
  /* Set a specific width */
  background-color: #FFF;
  /* Dark-grey background */
  height: 100%;
}

.icon-bar a {
  display: block;
  /* Make the links appear below each other instead of side-by-side */
  text-align: center;
  /* Center-align text */
  padding: 16px;
  /* Add some padding */
  transition: all 0.3s ease;
  /* Add transition for hover effects */
  color: black;
  /* White text color */
  font-size: 27px;
  /* Increased font-size */
  height: 100%;
}

.icon-bar a:hover {
  background-color: #5a5c5d;
  /* Add a hover color */
}

.active {
  background-color: #818384;
  /* Add an active/current color */
}

<style>
/* Tooltip container */

.tooltip {
  position: relative;
  display: inline-block;
  border-bottom: 1px dotted black;
  /* If you want dots under the hoverable text */
}

/* Tooltip text */

.tooltip .tooltiptext {
  visibility: hidden;
  width: auto;
  background-color: #da6161;
  color: #fff;
  text-align: center;
  padding: 5px;
  border-radius: 6px;
  font-size: 20px;
  /* Position the tooltip text - see examples below! */
  position: absolute;
  z-index: 1;
  margin-left: 36px;
}

/* Show the tooltip text when you mouse over the tooltip container */

.tooltip:hover .tooltiptext {
  visibility: visible;
}

.foot {
  background-color: #2d2d2d;
  color: #FFF;
  text-align: center;
  float: left;
  height: 35px;
  width: 100%;
  border-top: 3px solid #9c9d9e;
  padding-top: 3px;
}

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

<body>
  <div class="div_top2"> </div>
  <div class="main_container">
    <div class="container_left">
      <div class="icon_menu">
        <div class="icon-bar">
          <a class="active tooltip" href="#">
            <span class="tooltiptext">Home</span>
            <i class="fa fa-home"></i>

          </a>
          <a class="tooltip" href="#">
            <span class="tooltiptext">My Story</span>
            <i class="fa fa-black-tie"></i>
          </a>
          <a href="#" class="tooltip">
            <span class="tooltiptext">Companies</span>
            <i class="fa fa-building"></i>
          </a>
          <a href="#" class="tooltip">
            <span class="tooltiptext">Blog</span>
            <i class="fa fa-paper-plane"></i>
          </a>

          <a href="#" class="tooltip">
            <span class="tooltiptext">Ask Me Anything</span>
            <i class="fa fa-quora"></i>

          </a>

          <a href="#" class="tooltip">
            <span class="tooltiptext">Contact</span>
            <i class="fa fa-address-card"></i>

          </a>

        </div>
      </div>

    </div>

    <div class="container_right">

      <div class="bk"></div>

    </div>

  </div>

  <div class="foot">
    Copyright 2017

  </div>


问:
VBA scripting on excel to delete rows with specific strings
I'm currently in the process of writing a macro on excel that deletes an entire row which includes a specific string. I am doing some data analytics and would like to filter out a spreadsheet with not needed information.

An arbitrary example:

How would I go about making a script that deletes rows that include the color red, blue, and yellow?

答:
I use this code.</p>

```<code>Sub test()
    Dim rngDB As Range, rngU As Range, rngF As Range
    Dim vColor, i As Integer, Adr As String

    Set rngDB = ActiveSheet.UsedRange
    vColor = Array("red", "yellow", "blue")

    For i = 0 To UBound(vColor)
        With rngDB
            Set rngF = .Find(vColor(i), LookIn:=xlValues, Lookat:=xlWhole)
            If rngF Is Nothing Then
            Else
                Adr = rngF.Address
                Do
                    If rngU Is Nothing Then
                        Set rngU = rngF
                    Else
                        Set rngU = Union(rngU, rngF)
                    End If
                    Set rngF = .FindNext(rngF)
                Loop Until Adr = rngF.Address Or rngF Is Nothing
            End If
        End With
    Next i
    If rngU Is Nothing Then
    Else
        rngU.EntireRow.Delete
    End If
End Sub
</code>```

Body:
I use this code.

Sub test()
    Dim rngDB As Range, rngU As Range, rngF As Range
    Dim vColor, i As Integer, Adr As String

    Set rngDB = ActiveSheet.UsedRange
    vColor = Array("red", "yellow", "blue")

    For i = 0 To UBound(vColor)
        With rngDB
            Set rngF = .Find(vColor(i), LookIn:=xlValues, Lookat:=xlWhole)
            If rngF Is Nothing Then
            Else
                Adr = rngF.Address
                Do
                    If rngU Is Nothing Then
                        Set rngU = rngF
                    Else
                        Set rngU = Union(rngU, rngF)
                    End If
                    Set rngF = .FindNext(rngF)
                Loop Until Adr = rngF.Address Or rngF Is Nothing
            End If
        End With
    Next i
    If rngU Is Nothing Then
    Else
        rngU.EntireRow.Delete
    End If
End Sub


问:
Solving a "expression must have pointer to class type" error
```<code>class testClass { public: int B, C; };

testClass u;
testClass * k = &u;
testClass ** m = &k;

*m->B = 1;//Error appears here
</code>```

I think I've followed the rules of pointer referencing correctly. I still have no idea why this is happening. Could someone help me?

答:
operator-> has higher precedence than operator*, so *m->B is equivalent as *(m->B); while m->B is not valid here.

You should change it to (*m)->B.

Body:
class testClass { public: int B, C; };

testClass u;
testClass * k = &u;
testClass ** m = &k;

*m->B = 1;//Error appears here

I think I've followed the rules of pointer referencing correctly. I still have no idea why this is happening. Could someone help me?


问:
Spring Boot & Thymeleaf - remove strict HTML error checking
I am using Spring Boot for an MVC application, and my view technology is Thymeleaf. One of the things I need to do is copy the HTML of an existing website (not my doing...) and render it using Thymeleaf. However, some of the website's source HTML contain unclosed HTML tags (such as <meta>, <link>, <input>), or HTML tags with elements not surrounded by quotes, for example:

```

<p>instead of</p>

<pre class="lang-html prettyprint-override"><code><div id="1"></div>
</code>```

Of course in the browser this works... But Thymeleaf will not allow this and doesn't serve the page. Is there any way to allow more lenient rules for this? I've searched Thymeleaf's documentation and Spring Boot reference and have found no answer.

Just for clarification - I've not even configured my own beans for Thyemeleaf, just added it to the classpath via maven as one of the spring-boot-starters. So right now these are default settings.

答:
Spring Boot 1.5.3 supports Thymeleaf 3. Thymeleaf 3 has full html5 markup support.

Add following lines to your pom.xml to override Thymeleaf version in Spring boot and you'll be able to use unclosed tags.

```<code><properties>
   <thymeleaf.version>3.0.6.RELEASE</thymeleaf.version>
   <thymeleaf-layout-dialect.version>2.2.1</thymeleaf-layout-dialect.version>
    ...
</properties>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am using Spring Boot for an MVC application, and my view technology is Thymeleaf. One of the things I need to do is copy the HTML of an existing website (not my doing...) and render it using Thymeleaf. However, some of the website's source HTML contain unclosed HTML tags (such as <meta>, <link>, <input>), or HTML tags with elements not surrounded by quotes, for example:

instead of

Of course in the browser this works... But Thymeleaf will not allow this and doesn't serve the page. Is there any way to allow more lenient rules for this? I've searched Thymeleaf's documentation and Spring Boot reference and have found no answer.

Just for clarification - I've not even configured my own beans for Thyemeleaf, just added it to the classpath via maven as one of the spring-boot-starters. So right now these are default settings.

Body:
Spring Boot 1.5.3 supports Thymeleaf 3. Thymeleaf 3 has full html5 markup support.

Add following lines to your pom.xml to override Thymeleaf version in Spring boot and you'll be able to use unclosed tags.

<properties>
   <thymeleaf.version>3.0.6.RELEASE</thymeleaf.version>
   <thymeleaf-layout-dialect.version>2.2.1</thymeleaf-layout-dialect.version>
    ...
</properties>


问:
How would I go about making this error message appear when form field is not right?
I have an if statement and I already have it working so if certain fields are not filled in it will not send. I then have an else, and I put it like so:

```<code>if(isset($_POST['submit'])) {
    if (!empty($name) && (!empty($email) || !empty($phone))) {
    mail( "EMAIL@hotmail.com", "Monthly Specials Email",
    "Name: $name
     Email: $email
     Phone Number: $phone
     Comment: $comment", "From: $email" );

    $error = "";

   } else {
    $error = "Please fill in the required fields.";
   }
}
</code>```

In the form, I have a span class like so:

```<code><span class="error">'.$error.'</span>
</code>```

I have it so the action of the form is set to blank so it will stay on the same page when sent, and all of the functions are in the same page as the form. How would I go about updating the error span?

Thanks so much for any help or tips!

答:
You don't need any AJAX.</p>

```<code>$error = '';
if (isset($_POST['submit'])) {
    if ( <<< insert check for required fields >>> ) {
        // handle form, send mail, etc
        // you may want to redirect on success to prevent double posting
    } else {
        $error = "Please fill in the required fields.";
    }
}
</code>```

Body:
I have an if statement and I already have it working so if certain fields are not filled in it will not send. I then have an else, and I put it like so:

if(isset($_POST['submit'])) {
    if (!empty($name) && (!empty($email) || !empty($phone))) {
    mail( "EMAIL@hotmail.com", "Monthly Specials Email",
    "Name: $name
     Email: $email
     Phone Number: $phone
     Comment: $comment", "From: $email" );

    $error = "";

   } else {
    $error = "Please fill in the required fields.";
   }
}

In the form, I have a span class like so:

'.$error.'

I have it so the action of the form is set to blank so it will stay on the same page when sent, and all of the functions are in the same page as the form. How would I go about updating the error span?

Thanks so much for any help or tips!

Body:
You don't need any AJAX.

$error = '';
if (isset($_POST['submit'])) {
    if ( <<< insert check for required fields >>> ) {
        // handle form, send mail, etc
        // you may want to redirect on success to prevent double posting
    } else {
        $error = "Please fill in the required fields.";
    }
}


问:
How to handle business rules in DDD + CQRS + Event Sourcing approach?
I'm trying to figure out how to deal with complex domain model using CQRS/ES approach. Let's imagine we have e.g. Order domain entity, which handles both state and behavior of order. It has a Status property with transition rules for switching between statuses (implementing State pattern or any other kind of state machine). According to DDD principles, this logic should be implemented in Order class (representing the Order model) itself, having methods like approve(), cancel(), ship(), etc.

Looking at different public examples of this kind architecture, it turns out that domain entity and aggregate root is the same, and it handles both the state and behavior and even its own projection from events. Isn't it a violation of SRP?

But my question is more concrete: if I want to process new command (and apply new event), should I reconstitute entity from event stream (i.e. from write model and write db) and call its behavioral methods (which applies events to state) to handle business rules? Or just handle commands and events themselves, without having any write-model entity?

Pseudocode to illustrate:

```<code>class ApproveOrderHandler
{
    private EventStore eventStore

    // ...

    public void handle(ApproveOrder event)
    {
        Order order = this.eventStore.findById(event.getOrderId()); // getting order projection from event store
        order.approve(); // handling business logic
        this.eventStore.save(order.releaseEvents()); // save new events (OrderApproved)
    }
}

class Order extends AbstractAggregate
{
    private Uuid id;

    private DateTime takenAt;

    private OrderStatus status;

    // ...

    public void approve()
    {
        this.status.approve(); // business rules blah blah
        this.Apply(new OrderApproved(this.id)); // applying event
    }

    // ...
}
</code>```

Isn't that overdoing or somewhat?

And what should I do with relationships between entities in event-sourcing? If they exist only in "read model", there is no point in domain entity class.

EDIT: or maybe I should store state snapshot in "read database" and recover entity for operations from it? But it breaks idea of "different models for read & write"...

EDIT2: fixed read/write models mistake

答:
TL;DR

But my question is more concrete: if I want to process new command (and apply new event), should I reconstitute entity from event stream (i.e. from write model and write db) and call its behavioral methods (which applies events to state) to handle business rules?

Yes.

Or just handle commands and events themselves, without having any write-model entity?

No.

Once more, with feeling

The command handler lives in the application component; the business model lives in the domain component.

The motivation for keeping these components separated: making model replacement cost effective.  What the domain experts care about, where the business gets its win, is the domain model.  We don't expect to write the business model once and get it correct for all of time -- much more likely that we will learn more about how we want the model to work, and therefore be delivering improvements to the model on a regular basis.  Therefore, its important that there not be a lot of drag to replace one version of the model with another -- we want the replacement to be easy; we want the amount of work required to make the change to be reflected in the business value we get.

So we want the good stuff separated from "the plumbing".

Keeping all of the business logic in the domain component gives you two easy wins; first, you don't ever have to guess about where the business logic lives -- whether the specifics of the use case are easy or hard, the business logic is going to be in the Order, not anywhere else.  Second, because the business logic is not in the command handler, you don't have to worry about creating a bunch of test doubles to satisfy those dependency requirements -- you can test against the domain model directly.

So, we use handlers to reconstitute entities and calling their business logic methods, NOT to handling business logic itself?

Almost -- we use repositories to reconstitute entities and aggregates to handle the business logic.  The role of the command handler is orchestration; it's the glue between the data model and the domain model.

Body:
I'm trying to figure out how to deal with complex domain model using CQRS/ES approach. Let's imagine we have e.g. Order domain entity, which handles both state and behavior of order. It has a Status property with transition rules for switching between statuses (implementing State pattern or any other kind of state machine). According to DDD principles, this logic should be implemented in Order class (representing the Order model) itself, having methods like approve(), cancel(), ship(), etc.

Looking at different public examples of this kind architecture, it turns out that domain entity and aggregate root is the same, and it handles both the state and behavior and even its own projection from events. Isn't it a violation of SRP?

But my question is more concrete: if I want to process new command (and apply new event), should I reconstitute entity from event stream (i.e. from write model and write db) and call its behavioral methods (which applies events to state) to handle business rules? Or just handle commands and events themselves, without having any write-model entity?

Pseudocode to illustrate:

class ApproveOrderHandler
{
    private EventStore eventStore

    // ...

    public void handle(ApproveOrder event)
    {
        Order order = this.eventStore.findById(event.getOrderId()); // getting order projection from event store
        order.approve(); // handling business logic
        this.eventStore.save(order.releaseEvents()); // save new events (OrderApproved)
    }
}

class Order extends AbstractAggregate
{
    private Uuid id;

    private DateTime takenAt;

    private OrderStatus status;

    // ...

    public void approve()
    {
        this.status.approve(); // business rules blah blah
        this.Apply(new OrderApproved(this.id)); // applying event
    }

    // ...
}

Isn't that overdoing or somewhat?

And what should I do with relationships between entities in event-sourcing? If they exist only in "read model", there is no point in domain entity class.

EDIT: or maybe I should store state snapshot in "read database" and recover entity for operations from it? But it breaks idea of "different models for read & write"...

EDIT2: fixed read/write models mistake


问:
How to set setContentView(); to GONE
I have my main layout which is, setContentView(R.layout.activity_detail),

```<code>protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_detail);
</code>```

how do i set the visibility of my layout as GONE within the below code

```<code>   if (extras.get("NAME").equals("Blog")) {
        Intent blog = new Intent(DetailActivity.this, ReportActivity.class);
        blog.putExtra("URL", "url");
        blog.putExtra("filename", "Blog");
        startActivity(blog);

  // I want to Perform the operation here

        }
</code>```

答:
Try this code:

1.

```<code> View view=findViewById(android.R.id.content)
 view.setVisibility(View.GONE);
</code>```

2.

```<code>View view= getWindow().getDecorView().findViewById(android.R.id.content)
view.setVisibility(View.GONE);
</code>```

3.

```<code>final  View view= = (ViewGroup) ((ViewGroup) this
            .findViewById(android.R.id.content)).getChildAt(0);
view.setVisibility(View.GONE);
</code>```

4.

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/root_view" >

   //...

</LinearLayout>

View view=findViewById(android.R.id.root_view)
view.setVisibility(View.GONE);
</code>```

Title: How to set setContentView(); to GONE

Body:
I have my main layout which is, setContentView(R.layout.activity_detail),

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_detail);

how do i set the visibility of my layout as GONE within the below code

   if (extras.get("NAME").equals("Blog")) {
        Intent blog = new Intent(DetailActivity.this, ReportActivity.class);
        blog.putExtra("URL", "url");
        blog.putExtra("filename", "Blog");
        startActivity(blog);

  // I want to Perform the operation here

        }

Body:
Try this code:

1.

 View view=findViewById(android.R.id.content)
 view.setVisibility(View.GONE);

2.

View view= getWindow().getDecorView().findViewById(android.R.id.content)
view.setVisibility(View.GONE);

3.

final  View view= = (ViewGroup) ((ViewGroup) this
            .findViewById(android.R.id.content)).getChildAt(0);
view.setVisibility(View.GONE);

4.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/root_view" >

   //...

</LinearLayout>

View view=findViewById(android.R.id.root_view)
view.setVisibility(View.GONE);


问:
Is it possible to recuperate data entered by user in a dynamic table
I have created a dynamic table using html+php with input like a form (this is a matrix in reality) and
  I want to know if it is possible to recuperate data entered by user in a dynamic table? This is my code: </p>

```<code><?php
$rows = 3; // define number of rows
echo ' <form action="f.php" method="post">';
echo "<table border='1'>";
for($tr=1;$tr<=$rows;$tr++){
    echo "<tr>";
    echo "<th> E".$tr." </th>";
        for($td=1;$td<=$rows;$td++){
               echo '<td><input type="number" name="etat" placeholder="nb d etat" /></td>';
        }
    echo "</tr>";
}
echo "</table>";
echo '<input type="submit" value="Create Table">';
echo '</form>'
?>
</code>```

答:
Yes it is possible but you have to create form by giving row and column number because you want to create matrix:

```<code>$rows = 3; // define number of rows
echo ' <form action="f.php" method="post">';
echo "<table border='1'>";
for($tr=1;$tr<=$rows;$tr++){
    echo "<tr>";
    echo "<th> E".$tr." </th>";
        for($td=1;$td<=$rows;$td++){
               echo '<td><input type="number" name="etat_'.$tr.'_'.$td.'" placeholder="nb d etat" /></td>';
        }
    echo "</tr>";
}
echo "</table>";
echo '<input type="submit" name="submit" value="Create Table">';
echo '</form>';
</code>```

in f.php fetch data :

```<code>if(isset($_POST['submit'])) {
    print_r($_POST);
}
</code>```

It gives you output:

```<code>Array
(
    [etat_1_1] => 1 //means 1st row 1st column
    [etat_1_2] => 2 //means 1st row 2nd column
    [etat_1_3] => 3 //means 1st row 3rd column
    [etat_2_1] => 4 //means 2nd row 1st column and so on...
    [etat_2_2] => 5
    [etat_2_3] => 6
    [etat_3_1] => 7
    [etat_3_2] => 8
    [etat_3_3] => 9
    [submit] => Create Table
)
</code>```

Body:
I have created a dynamic table using html+php with input like a form (this is a matrix in reality) and
  I want to know if it is possible to recuperate data entered by user in a dynamic table? This is my code:

<?php
$rows = 3; // define number of rows
echo ' <form action="f.php" method="post">';
echo "
";
for($tr=1;$tr<=$rows;$tr++){
    echo "
";
    echo " E".$tr." 	";
        for($td=1;$td<=$rows;$td++){
               echo '<input type="number" name="etat" placeholder="nb d etat" />	';
        }
    echo "
";
}
echo "
";
echo '<input type="submit" value="Create Table">';
echo '</form>'
?>

Body:
Yes it is possible but you have to create form by giving row and column number because you want to create matrix:

$rows = 3; // define number of rows
echo ' <form action="f.php" method="post">';
echo "<table border='1'>";
for($tr=1;$tr<=$rows;$tr++){
    echo "<tr>";
    echo "<th> E".$tr." </th>";
        for($td=1;$td<=$rows;$td++){
               echo '<td><input type="number" name="etat_'.$tr.'_'.$td.'" placeholder="nb d etat" /></td>';
        }
    echo "</tr>";
}
echo "</table>";
echo '<input type="submit" name="submit" value="Create Table">';
echo '</form>';

in f.php fetch data :

if(isset($_POST['submit'])) {
    print_r($_POST);
}

It gives you output:

Array
(
    [etat_1_1] => 1 //means 1st row 1st column
    [etat_1_2] => 2 //means 1st row 2nd column
    [etat_1_3] => 3 //means 1st row 3rd column
    [etat_2_1] => 4 //means 2nd row 1st column and so on...
    [etat_2_2] => 5
    [etat_2_3] => 6
    [etat_3_1] => 7
    [etat_3_2] => 8
    [etat_3_3] => 9
    [submit] => Create Table
)


问:
anyone got an error i get while installing teepluss/theme in laravel
I wanted to install teepluss/theme so I added it to my composer.json

but now I get this error:

[Symfony\Component\Debug\Exception\FatalThrowableError]

    Class 'SuperClosure\Serializer' not found

I was capable to solve the first error by adding         >"jeremeamia/superclosure": "^2.0"

but now when I add >Teepluss\Theme\ThemeServiceProvider::class, in app.php providers I get a new error :

> [ErrorException]                 Illegal offset type in unset

here's what i got in the script in composer.json

答:
If you already run composer update, you can try run this script
php artisan config:cache
and
php artisan cache:clear.It can help you resolve that problem


问:
Swift 3 : Add SearchBar to UIViewController
I am trying to add a search/filter option to a navigation bar in Swift 3. Currently, I am pushing to the current UICollectionView from previous views, all of which are on a NavigationViewController stack.

In the current UICollectionViewController, I have set up a UISearchBar object like so:

```<code>let searchBar: UISearchBar = {
    let sb = UISearchBar()
    sb.placeholder = "Enter search term"
    return sb
}()
</code>```

And inside collectionViewController, viewdidload() I set up the following:

```<code>// searchbar
let navBar = self.navigationController?.navigationBar
navigationController?.navigationBar.addSubview(searchBar)

searchBar.anchor(top: navBar?.topAnchor, left: navBar?.leftAnchor   , bottom: navBar?.bottomAnchor, right: navBar?.rightAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: 0, height: 0  )
</code>```

The anchoring is done through a custom extension, though I do not believe it effects anything, but is as follows:

```<code>extension UIView{
    // anchor
    func anchor(top: NSLayoutYAxisAnchor?, left: NSLayoutXAxisAnchor?, bottom: NSLayoutYAxisAnchor?, right: NSLayoutXAxisAnchor?,paddingTop: CGFloat, paddingLeft: CGFloat, paddingBottom: CGFloat, paddingRight: CGFloat, width: CGFloat, height: CGFloat){

        translatesAutoresizingMaskIntoConstraints = false

        if let top = top{
            self.topAnchor.constraint(equalTo: top, constant: paddingTop).isActive = true
        }
        if let left = left{
            self.leftAnchor.constraint(equalTo: left, constant: paddingLeft).isActive = true
        }
        if let bottom = bottom{
            bottom.constraint(equalTo: bottom, constant: paddingBottom).isActive = true
        }
        if let right = right{
            rightAnchor.constraint(equalTo: right, constant: -paddingRight).isActive = true
        }
        if width != 0{
            widthAnchor.constraint(equalToConstant: width).isActive = true
        }
        if height != 0{
            heightAnchor.constraint(equalToConstant: height).isActive = true
        }

    }
}
</code>```

However, when I load the corresponding uicollectionviewcontrollers, I am not able to see the searchbar in the navigationController navBar area. Is there something else that needs to be set in order for it to be displayed?

答:
You have to specify a frame for your UISearchBar. Try this:

```<code>let searchBar: UISearchBar = {
    let sb = UISearchBar(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 44))    //change the width & height according to your needs.
    sb.placeholder = "Enter search term"
    return sb
}
</code>```

Body:
I am trying to add a search/filter option to a navigation bar in Swift 3. Currently, I am pushing to the current UICollectionView from previous views, all of which are on a NavigationViewController stack.

In the current UICollectionViewController, I have set up a UISearchBar object like so:

let searchBar: UISearchBar = {
    let sb = UISearchBar()
    sb.placeholder = "Enter search term"
    return sb
}()

And inside collectionViewController, viewdidload() I set up the following:

// searchbar
let navBar = self.navigationController?.navigationBar
navigationController?.navigationBar.addSubview(searchBar)

searchBar.anchor(top: navBar?.topAnchor, left: navBar?.leftAnchor   , bottom: navBar?.bottomAnchor, right: navBar?.rightAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: 0, height: 0  )

The anchoring is done through a custom extension, though I do not believe it effects anything, but is as follows:

extension UIView{
    // anchor
    func anchor(top: NSLayoutYAxisAnchor?, left: NSLayoutXAxisAnchor?, bottom: NSLayoutYAxisAnchor?, right: NSLayoutXAxisAnchor?,paddingTop: CGFloat, paddingLeft: CGFloat, paddingBottom: CGFloat, paddingRight: CGFloat, width: CGFloat, height: CGFloat){

        translatesAutoresizingMaskIntoConstraints = false

        if let top = top{
            self.topAnchor.constraint(equalTo: top, constant: paddingTop).isActive = true
        }
        if let left = left{
            self.leftAnchor.constraint(equalTo: left, constant: paddingLeft).isActive = true
        }
        if let bottom = bottom{
            bottom.constraint(equalTo: bottom, constant: paddingBottom).isActive = true
        }
        if let right = right{
            rightAnchor.constraint(equalTo: right, constant: -paddingRight).isActive = true
        }
        if width != 0{
            widthAnchor.constraint(equalToConstant: width).isActive = true
        }
        if height != 0{
            heightAnchor.constraint(equalToConstant: height).isActive = true
        }

    }
}

However, when I load the corresponding uicollectionviewcontrollers, I am not able to see the searchbar in the navigationController navBar area. Is there something else that needs to be set in order for it to be displayed?

Body:
You have to specify a frame for your UISearchBar. Try this:

let searchBar: UISearchBar = {
    let sb = UISearchBar(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 44))    //change the width & height according to your needs.
    sb.placeholder = "Enter search term"
    return sb
}


问:
WPF iDataErrorInfo (validating textboxes) not working as intended
UPDATE: I fixed this by improving my switch statement. Made use of nameof!

I'm trying to validate a set of user inputs from textboxes.

I have my class with interface setup. Snippet of it below:

```<code>public class PatientValidation : INotifyPropertyChanged, IDataErrorInfo
    {
        private string _id;
        private string _fname;

        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged(string p)
        {
            PropertyChangedEventHandler ph = PropertyChanged;
            if (ph != null)
            {
                ph(this, new PropertyChangedEventArgs(p));
            }

        }

        public string Id
        {
            get
            {
                return _id;
            }
            set
            {
                _id = value;
            }
        }
        public string Fname
        {
            get
            {
                return _fname;
            }
            set
            {
                _fname = value;
            }
        }
</code>```

And a switch statement to return error message based on user input:

```<code>public string this[string PropertyName]
        {
            get
            {
                string result = null;

                switch (PropertyName)
                {
                    case "Id":
                        if (string.IsNullOrEmpty(Id))
                            result = "ID number is required.";
                        break;

                    case "fname":
                        if (string.IsNullOrEmpty(Fname))
                            result = "First name is required.";
                        break;
                  }
                    return result;
             }
          }
</code>```

My relevant code in XAML:

```<code><Style TargetType="TextBox">
            <Style.Triggers>
                <Trigger Property="Validation.HasError" Value="true">
                    <Setter Property="ToolTip" Value="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=(Validation.Errors).CurrentItem.ErrorContent}"/>
                </Trigger>
            </Style.Triggers>
        </Style>

<TextBox x:Name="textBox_IDNumber" Text="{Binding Id, Mode=TwoWay, ValidatesOnDataErrors=True}"/>
<TextBox x:Name="textBox_FirstName" Text="{Binding Fname, Mode=TwoWay, ValidatesOnDataErrors=True"}/>
</code>```

Here's the problem I've run into: ONLY the first textbox (ID) is validated correctly and the error tooltip is shown. None of the other textboxes.
Different bindings and triggers hasn't solved the issue. Any help would be much appreciated.

答: It doesn't seem that you are calling OnPropertyChanged(nameof(FName)); or OnPropertyChanged(nameof(ID)); within the setters of your properties - thus there will be no notification that the binding has updated, and the IDataErrorInfo.<propertyName> will not be called.

Body:
UPDATE: I fixed this by improving my switch statement. Made use of nameof!

I'm trying to validate a set of user inputs from textboxes.

I have my class with interface setup. Snippet of it below:

public class PatientValidation : INotifyPropertyChanged, IDataErrorInfo
    {
        private string _id;
        private string _fname;

        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged(string p)
        {
            PropertyChangedEventHandler ph = PropertyChanged;
            if (ph != null)
            {
                ph(this, new PropertyChangedEventArgs(p));
            }

        }

        public string Id
        {
            get
            {
                return _id;
            }
            set
            {
                _id = value;
            }
        }
        public string Fname
        {
            get
            {
                return _fname;
            }
            set
            {
                _fname = value;
            }
        }

And a switch statement to return error message based on user input:

public string this[string PropertyName]
        {
            get
            {
                string result = null;

                switch (PropertyName)
                {
                    case "Id":
                        if (string.IsNullOrEmpty(Id))
                            result = "ID number is required.";
                        break;

                    case "fname":
                        if (string.IsNullOrEmpty(Fname))
                            result = "First name is required.";
                        break;
                  }
                    return result;
             }
          }

My relevant code in XAML:

        </Style>

<TextBox x:Name="textBox_IDNumber" Text="{Binding Id, Mode=TwoWay, ValidatesOnDataErrors=True}"/>
<TextBox x:Name="textBox_FirstName" Text="{Binding Fname, Mode=TwoWay, ValidatesOnDataErrors=True"}/>

Here's the problem I've run into: ONLY the first textbox (ID) is validated correctly and the error tooltip is shown. None of the other textboxes.
Different bindings and triggers hasn't solved the issue. Any help would be much appreciated.


问:
Web data scraping using Scrapy
I am using scrapy to scrape justdial.com but the code doesn't seem to work. Please help me fix this. I run it with the command being "scrapy crawl justdial -o items.csv -t csv" from the terminal.

```<code>from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import HtmlXPathSelector
from justdial_sample.items import JustdialSampleItem

class MySpider(CrawlSpider):
    name = "justdial"
    allowed_domains = ["www.justdial.com"]
    start_urls = ["https://www.justdial.com/"]

    rules = (Rule (SgmlLinkExtractor(allow=("index\d00\.html",
    ),restrict_xpaths=('//p[@id="nextpage"]',))
    , callback="parse_items", follow=True),
    )

    def parse(self, response):
        hxs = HtmlXPathSelector(response)
        titles = hxs.select("//p")
        items = []
        for titles in titles:
            item = JdItem()
            item ["title"] = titles.select("a/text()").extract()
            item ["link"] = titles.select("@/href").extract()
            item.append(item)
        return items
</code>```

this is the code that I used.

答:
If you can show output log it will be easier to help you.

Usually you should add correct headers as in browser, etc User-Agent. You can check all headers in firebug and you can check headers in your spider.

```<code>print response.request.headers
</code>```

UPDATE:
You should add this row to settings.py

```<code>USER_AGENT = 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:45.0) Gecko/20100101 Firefox/53.0'
</code>```

Title: Web data scraping using Scrapy

Body:
I am using scrapy to scrape justdial.com but the code doesn't seem to work. Please help me fix this. I run it with the command being "scrapy crawl justdial -o items.csv -t csv" from the terminal.

from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import HtmlXPathSelector
from justdial_sample.items import JustdialSampleItem

class MySpider(CrawlSpider):
    name = "justdial"
    allowed_domains = ["www.justdial.com"]
    start_urls = ["https://www.justdial.com/"]

    rules = (Rule (SgmlLinkExtractor(allow=("index\d00\.html",
    ),restrict_xpaths=('//p[@id="nextpage"]',))
    , callback="parse_items", follow=True),
    )

    def parse(self, response):
        hxs = HtmlXPathSelector(response)
        titles = hxs.select("//p")
        items = []
        for titles in titles:
            item = JdItem()
            item ["title"] = titles.select("a/text()").extract()
            item ["link"] = titles.select("@/href").extract()
            item.append(item)
        return items

this is the code that I used.

Body:
If you can show output log it will be easier to help you.

Usually you should add correct headers as in browser, etc User-Agent. You can check all headers in firebug and you can check headers in your spider.

print response.request.headers

UPDATE:
You should add this row to settings.py

USER_AGENT = 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:45.0) Gecko/20100101 Firefox/53.0'


问:
Event bubbling and capture on a root element with nested elements
I am trying to capture the id on each card from the root element. However, every time I click on a nested element I get empty string. However, I want the id from the wrapping card while listening on the root element cards. I want to handle both bubbling and capturing cases as this is part of a larger structure. I only want answers in vanilla js, and Javascript,  no css please.

cards.addEventListener('click', evt => {
  if (evt.target !== evt.currentTarget) {
    var clickedItem = evt.target.id
    console.log(clickedItem);
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.card {
  /* Add shadows to create the "card" effect */
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
  transition: 0.3s;
}

/* On mouse-over, add a deeper shadow */

.card:hover {
  box-shadow: 0 8px 16px 0 rgba(0, 0, 0, 0.2);
}

/* Add some padding inside the card container */

.container {
  padding: 2px 16px;
}</code>```

1st Note

Note Body

2nd Note

Note Body2

3Note Body

Note Body3

```

答:
Yes, one listener is a good requirement.  As it happens you only need to change the line where you get your target:

```<code>cards.addEventListener('click', evt => {
  console.log( evt.target.closest( '.card' ).id );
});
</code>```

Complete example:

cards.addEventListener('click', evt => {
  alert( evt.target.closest( '.card' ).id );
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.card {
  /* Add shadows to create the "card" effect */
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
  transition: 0.3s;
}

/* On mouse-over, add a deeper shadow */

.card:hover {
  box-shadow: 0 8px 16px 0 rgba(0, 0, 0, 0.2);
}

/* Add some padding inside the card container */

.container {
  padding: 2px 16px;
}</code>```

1st Note

Note Body

2nd Note

Note Body2

3Note Body

Note Body3

```

Body:
I am trying to capture the id on each card from the root element. However, every time I click on a nested element I get empty string. However, I want the id from the wrapping card while listening on the root element cards. I want to handle both bubbling and capturing cases as this is part of a larger structure. I only want answers in vanilla js, and Javascript,  no css please.

cards.addEventListener('click', evt => {
  if (evt.target !== evt.currentTarget) {
    var clickedItem = evt.target.id
    console.log(clickedItem);
  }
});

.card {
  /* Add shadows to create the "card" effect */
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
  transition: 0.3s;
}

/* On mouse-over, add a deeper shadow */

.card:hover {
  box-shadow: 0 8px 16px 0 rgba(0, 0, 0, 0.2);
}

/* Add some padding inside the card container */

.container {
  padding: 2px 16px;
}

1st Note

Note Body

2nd Note

Note Body2

3Note Body

Note Body3

Body:
Yes, one listener is a good requirement.  As it happens you only need to change the line where you get your target:

cards.addEventListener('click', evt => {
  console.log( evt.target.closest( '.card' ).id );
});

Complete example:

cards.addEventListener('click', evt => {
  alert( evt.target.closest( '.card' ).id );
});

.card {
  /* Add shadows to create the "card" effect */
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
  transition: 0.3s;
}

/* On mouse-over, add a deeper shadow */

.card:hover {
  box-shadow: 0 8px 16px 0 rgba(0, 0, 0, 0.2);
}

/* Add some padding inside the card container */

.container {
  padding: 2px 16px;
}

<div id="cards" style="margin: auto; width: 50%;">
  <div class="card" id="1234567"><img src="img_avatar.png">
    <div class="container">
      <h4>1st Note</h4>
      <p>Note Body</p>
    </div>
  </div>
  <div class="card" id="1234547"><img src="img_avatar.png">
    <div class="container">
      <h4>2nd Note</h4>
      <p>Note Body2</p>
    </div>
  </div>
  <div class="card" id="721680"><img src="img_avatar.png">
    <div class="container">
      <h4>3Note Body</h4>
      <p>Note Body3</p>
    </div>
  </div>
</div>


问:
Electron register protocol not working
I am trying this:

https://electron.atom.io/docs/api/protocol/

And I get this error:

```<code>https://google.com/#q=standard%2Fno-callback-literal  Unexpected literal in error position of callback
</code>```

Why is it not working?

答:
Solution is to install this so the callback can work:

https://github.com/xjamundx/eslint-plugin-standard

Title: Electron register protocol not working

Body:
I am trying this:

https://electron.atom.io/docs/api/protocol/

And I get this error:

https://google.com/#q=standard%2Fno-callback-literal  Unexpected literal in error position of callback

Why is it not working?


问:
How to parse rss-feeds / xml in a shell script
I'd like to parse rss feeds and download podcasts on my ReadyNas which is running 24/7 anyway.

So I'm thinking about having a shell script checking periodically the feeds and spawning wget to download the files.

What is the best way to do the parsing?

Thanks!

答: Do you have access to awk?  Maybe you could use XMLGawk</p>

OwnerDisplayName: Oli

OwnerDisplayName: cddr


问:
Magento - Populate a dropdown from 'X' Store categories
I am in the process of customising our search filters on our Multi-Domain Magento install and was wondering how I can populate a dropdown with the category titles from a store depending on what store/domain you are on.

Probably a simple query but have so much going on at the moment I can't think where to start!

Thanks

答: Once you have specified your store (probably using a switch based upon the domain) you should be able to get a collection of the categories associated with that store id. </p>


问:
Filling list nan values
How to fill nan values with 0's in a list. I can do it for dataframes but don't know how to do it for lists?

```<code>listname=listname.fillna(0)
</code>```

This isn't working.

答:
You can use list comprehension and check with math.isnan:

```<code>import math
listname = [0 if math.isnan(x) else x for x in listname]
</code>```

But that would not work with non float types, if you have strings, other numeric types etc.. in your list then you can use str(x) != 'nan'

```<code>listname = [0 if str(x)=='nan' else x for x in listname]
</code>```

Title: Filling list nan values

Body:
How to fill nan values with 0's in a list. I can do it for dataframes but don't know how to do it for lists?

listname=listname.fillna(0)

This isn't working.

Body:
You can use list comprehension and check with math.isnan:

import math
listname = [0 if math.isnan(x) else x for x in listname]

But that would not work with non float types, if you have strings, other numeric types etc.. in your list then you can use str(x) != 'nan'

listname = [0 if str(x)=='nan' else x for x in listname]


问:
getting value of array from certain index in php
I want to get the value of an array type given a certain index. The array's values are

$status = [1,2];

And I used these code to get the value:

$task_state = $status[1];

But it actually thought $status is a string and returns

'['

I know that this is actually quite simple, but I just can't seem to find the answer to my problem. Thank you

答:
Maybe you are saying that the values of your array:

```<code>$status  = array(1,2);
</code>```

So to get a value from the array:

```<code>echo $tatus[0] . "and " . $tatus[1];
</code>```

output:

1 and 2

Body:
Maybe you are saying that the values of your array:

$status  = array(1,2);

So to get a value from the array:

echo $tatus[0] . "and " . $tatus[1];

output:

1 and 2


问:
chart.js adjust height in mobile view
I need to get chart.js to adjust the height of the chart when I switch my site to mobile view, I'm using bootstrap as my framework which is working fine.

The issue with mobile view of the site is that the graphs are too small to interact with.

I've tried adding attributes in var options = {} but no luck I've even tried using height attributed in css but no luck!

Please help!

Here's the site:

http://preview.qaxawkzy7e6d2t9vhswkar3v1n8w7b9p705un9k2ojkbj4i.box.codeanywhere.com/

And code:

```<code><html>
  <head>
    <meta name="viewport" content="width=device-width, minimal-scale=1.0, maximum-scale=1.0,">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
    <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.2.1/Chart.bundle.js"></script>
  </head>
  <body style="padding: 20px;">
    <div class="row">
      <div class="col-md-6">
        <div class="well">
          <canvas id="myChart"></canvas>
        </div>
      </div>
      <div class="col-md-6">
        <div class="well">
          <h1>Hi there!</h1>
        </div>
      </div>
    </div>
    <script>
      var ctx = document.getElementById("myChart");

      var myChart = new Chart(ctx, {
          type: 'bar',
          options: {
              responsive: true,
          },
          data: {
              labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
              datasets: [{
                  label: '# of Votes',
                  data: [12, 19, 3, 5, 2, 3],
                  backgroundColor: [
                      'rgba(255, 99, 132, 0.2)',
                      'rgba(54, 162, 235, 0.2)',
                      'rgba(255, 206, 86, 0.2)',
                      'rgba(75, 192, 192, 0.2)',
                      'rgba(153, 102, 255, 0.2)',
                      'rgba(255, 159, 64, 0.2)'
                  ],
                  borderColor: [
                      'rgba(255,99,132,1)',
                      'rgba(54, 162, 235, 1)',
                      'rgba(255, 206, 86, 1)',
                      'rgba(75, 192, 192, 1)',
                      'rgba(153, 102, 255, 1)',
                      'rgba(255, 159, 64, 1)'
                  ],
                  borderWidth: 1
              }]
          },
          options: {
              scales: {
                  yAxes: [{
                      ticks: {
                          beginAtZero:true
                      }
                  }]
              }
          }
      });
    </script>
  </body>
</html>
</code>```

答: I believe the answer is to set the maintainAspectRatio: false option for the chart and then set the minimum height of the chart responsively if the screen width reaches a certain size.

Title: chart.js adjust height in mobile view

Body:
I need to get chart.js to adjust the height of the chart when I switch my site to mobile view, I'm using bootstrap as my framework which is working fine.

The issue with mobile view of the site is that the graphs are too small to interact with.

I've tried adding attributes in var options = {} but no luck I've even tried using height attributed in css but no luck!

Please help!

Here's the site:

http://preview.qaxawkzy7e6d2t9vhswkar3v1n8w7b9p705un9k2ojkbj4i.box.codeanywhere.com/

And code:

    <meta name="viewport" content="width=device-width, minimal-scale=1.0, maximum-scale=1.0,">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

          <canvas id="myChart"></canvas>

Hi there!


问:
Nested include with offset and limit Sequelize
Is anyone successful using nested include along with Limit and Offset in Sequelize. I'm trying to implement server side paging using the Sequelize, can anyone show me any reference. I'm using Sql Server database. I see that the query is being converted as sub query along with joins when I try to do this. Has anyone got</p>

```<code>{where: query.activity,
        attributes: [...activityAttributes, 'LastModifiedUserID', 'LastModifiedDateUTC', 'SPIStatus'],
        include: [
            {
                model: Issue,
                where: query.issue,
                attributes: issueAttributes,
                include: [{
                    model: Product,
                    where: query.product,
                    attributes: productAttributes
                },
                    {
                        model: IssueExtendedAttribute,
                        where: {$and: query.issueExtendedAttributes},
                        required: !!query.issueExtendedAttributes
                    }]
            }],
           offset: 10,
           limit: 10}
</code>```

答:
You need to add

subQuery: false;

ex:

```<code>{
    subQuery: false,
    where: queryObj,
    include: [{
      model: db.A,
      where: AQueryObj,
      include:[{
        model: db.B,
        where: BQueryObj
      },{
        model: db.C,
        where: CQueryObj
      }]
    }],
    offset: offset,
    limit: limit
}
</code>```

Check this link to get more information

Body:
Is anyone successful using nested include along with Limit and Offset in Sequelize. I'm trying to implement server side paging using the Sequelize, can anyone show me any reference. I'm using Sql Server database. I see that the query is being converted as sub query along with joins when I try to do this. Has anyone got

{where: query.activity,
        attributes: [...activityAttributes, 'LastModifiedUserID', 'LastModifiedDateUTC', 'SPIStatus'],
        include: [
            {
                model: Issue,
                where: query.issue,
                attributes: issueAttributes,
                include: [{
                    model: Product,
                    where: query.product,
                    attributes: productAttributes
                },
                    {
                        model: IssueExtendedAttribute,
                        where: {$and: query.issueExtendedAttributes},
                        required: !!query.issueExtendedAttributes
                    }]
            }],
           offset: 10,
           limit: 10}

Body:
You need to add

subQuery: false;

ex:

{
    subQuery: false,
    where: queryObj,
    include: [{
      model: db.A,
      where: AQueryObj,
      include:[{
        model: db.B,
        where: BQueryObj
      },{
        model: db.C,
        where: CQueryObj
      }]
    }],
    offset: offset,
    limit: limit
}

Check this link to get more information


问:
Query Timeout Settings in Excel
new to the site I'd like to give it a shot and see if I can get any answers regarding SQL Querys in Excel.

Is there a way to handle if a Timeout occurs in Microsoft Excel (mostly 2007/2010 on Win XP/Vista/7)? As you know you can connect Excel to a Microsoft SQL Server and run your query via Excel. The only thing is that I don't seem to find any Timeout options for this. And for an example, if there is a bad query, this might lock other tables in the SQL Server (2005) database.

I'm not looking for a script. It's more like settings I need and if possible I would like to add these Timeout settings to a specific Windows user account. Settings in either SQL Server 2005 or in Microsoft Excel 2007/2010.

Best regards
/Henrik

答:
Use the CommandTimeout property

```<code>Dim objCommand As ADODB.Command
Set objCommand = New ADODB.Command

objCommand.CommandTimeout = 99 '
objCommand.ActiveConnection = cnConn
objCommand.CommandText = "DELETE Users WHERE IdLevel < 98"
objCommand.Execute
</code>```

Title: Query Timeout Settings in Excel

Body:
Use the CommandTimeout property

Dim objCommand As ADODB.Command
Set objCommand = New ADODB.Command

objCommand.CommandTimeout = 99 '
objCommand.ActiveConnection = cnConn
objCommand.CommandText = "DELETE Users WHERE IdLevel < 98"
objCommand.Execute


问:
How to solve: Use of unresolved identifier 'indexPath' in Swift
```<code>func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 1
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
    return interests.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt cellForItemAtindexPath: IndexPath) -> UICollectionViewCell
{
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier(Storyboard.CellIdentifier, forIndexPath:indexPath) as! InterestCollectionViewCell

    cell.interest = self.interest[indexPath.item]

    return cell
}
</code>```

答:
```<code>extension ViewController: UICollectionViewDataSource {

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        return interests.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: Storyboard.cellIdentifier, for: indexPath) as! InterestCollectionViewCell

        cell.interest = interests[(indexPath as NSIndexPath).item]

        return cell
    }
}
</code>```


问:
compare the information between two matrices R
I have two matrices, one is generated out of the other by deleting some rows. For example:

```<code>m = matrix(1:18, 6, 3)
m1 = m[c(-1, -3, -6),]
</code>```

Suppose I do not know which rows in m were eliminated to create m1, how should I find it out by comparing the two matrices? The result I want looks like this:

```<code>1, 3, 6
</code>```

The actual matrix I am dealing with is very big. I was wondering if there is any efficient way of conducting it.

答:
We can also use do.call

```<code>which(!do.call(paste, as.data.frame(m)) %in% do.call(paste, as.data.frame(m1)))
#[1] 1 3 6
</code>```

Body:
I have two matrices, one is generated out of the other by deleting some rows. For example:

m = matrix(1:18, 6, 3)
m1 = m[c(-1, -3, -6),]

Suppose I do not know which rows in m were eliminated to create m1, how should I find it out by comparing the two matrices? The result I want looks like this:

1, 3, 6

The actual matrix I am dealing with is very big. I was wondering if there is any efficient way of conducting it.

Body:
We can also use do.call

which(!do.call(paste, as.data.frame(m)) %in% do.call(paste, as.data.frame(m1)))
#[1] 1 3 6


问:
Background position, margin-top?
I currently have my background set to top right as:

```<code>#thedivstatus {
    background-image: url("imagestatus.gif");
    background-position: right top;
    background-repeat: no-repeat;
}
</code>```

BUT! I need to add a margin-top:50px; from where its rendering via above. Could anyone give me a suggestion?

Thanks

答:
```<code> background-image: url(/images/poster.png);
 background-position: center;
 background-position-y: 50px;
 background-repeat: no-repeat;
</code>```

Title: Background position, margin-top?

Body:
I currently have my background set to top right as:

#thedivstatus {
    background-image: url("imagestatus.gif");
    background-position: right top;
    background-repeat: no-repeat;
}

BUT! I need to add a margin-top:50px; from where its rendering via above. Could anyone give me a suggestion?

Thanks


问:
codename-one.appspot.com 500 error when attempting to migrate old device id
When I execute
    curl -i "https://codename-one.appspot.com/token?m=id&i=d116845c6825ac151489ab33725285e5f48b3e0225285e5f48b3e02"

The result is:

```<code>HTTP/1.1 500 Internal Server Error
X-Cloud-Trace-Context: 3f022af7dc49c7650be2fa82421a8511
Date: Tue, 06 Jun 2017 18:25:36 GMT
Content-Type: text/html; charset=UTF-8
Server: Google Frontend
Content-Length: 323
Alt-Svc: quic=":443"; ma=2592000; v="38,37,36,35"

<html><head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>500 Server Error</title>
</head>
<body text=#000000 bgcolor=#ffffff>
<h1>Error: Server Error</h1>
<h2>The server encountered an error and could not complete your request.<p>Please try again in 30 seconds.</h2>
<h2></h2>
</body></html>
</code>```

This seems to happen when running the example (with six 9s) from https://www.codenameone.com/blog/new-push-servers.html

How can I tell if an old device id exists or if this is a temporary error with the servers?

答: That id is incorrect as the old device ids were purely numeric and your number contains both a d and an e character

Body:
When I execute
    curl -i "https://codename-one.appspot.com/token?m=id&i=d116845c6825ac151489ab33725285e5f48b3e0225285e5f48b3e02"

The result is:

HTTP/1.1 500 Internal Server Error
X-Cloud-Trace-Context: 3f022af7dc49c7650be2fa82421a8511
Date: Tue, 06 Jun 2017 18:25:36 GMT
Content-Type: text/html; charset=UTF-8
Server: Google Frontend
Content-Length: 323
Alt-Svc: quic=":443"; ma=2592000; v="38,37,36,35"

<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>500 Server Error</title>

Error: Server Error

The server encountered an error and could not complete your request.
Please try again in 30 seconds.

This seems to happen when running the example (with six 9s) from https://www.codenameone.com/blog/new-push-servers.html

How can I tell if an old device id exists or if this is a temporary error with the servers?


问:
jQuery show/hide issue on data grid
I am facing a problem with the data gird. I have three to four datagrid one below the other and for each grid i have action buttons[select/del/copy/add] which i showing and hiding using jquery.

Each data grid has different id and show and hide controlled through jquery. But when i am clicking the first grid the next grid is also showing the control eventhough it has a different id.

I understand there is something advanced jquery scripting involved here, would be of great help if someone looks into this.

http://jsfiddle.net/pixelfx/3fwyf/16/

thanks,
ravi.

答: you should use the .next() jquery function to only select the next set of buttons to display</p>

Title: jQuery show/hide issue on data grid