问:
Regex in Python?
I have a string:

```<code>line = "https://dbwebb.se/kunskap/uml#sequence, ftp://bth.com:32/files/im.jpeg, file://localhost:8585/zipit, http://v2-dbwebb.se/do%hack"
</code>```

I want to get this result:

```<code>[('https', 'dbwebb.se', ''), ('ftp', 'bth.com', '32'), ('file', 'localhost', '8585'), ('http', 'v2-dbwebb.se', '')]
</code>```

I tried this:

```<code>match = re.findall("(^[a-z]+[^://](^[a-z]+\d))", line)
</code>```

I'm a beginner in Python.  If there is somebody who can explain, it would be very nice :D

答:
To provide yet another druidic and hacky regular expression approach:

```<code>import re

rx = re.compile(r"""
            (?P<protocol>[^:]+)://  # protocol
            (?P<domain>[^/:]+)      # domain part
            (?::(?P<port>\d+))?     # port, optional
            """, re.VERBOSE)

line = "https://dbwebb.se/kunskap/uml#sequence, ftp://bth.com:32/files/im.jpeg, file://localhost:8585/zipit, http://v2-dbwebb.se/do%hack"

matches = [match.groups()
           for part in line.split(" ")
           for match in [rx.match(part)]]
print(matches)
# [('https', 'dbwebb.se', None), ('ftp', 'bth.com', '32'), ('file', 'localhost', '8585'), ('http', 'v2-dbwebb.se', None)]
</code>```

See a demo on ideone.com. Otherwise, have a look at @DRC's answer for a very good non-regex way to tackle the problem.

Title: Regex in Python?

Body:
I have a string:

line = "https://dbwebb.se/kunskap/uml#sequence, ftp://bth.com:32/files/im.jpeg, file://localhost:8585/zipit, http://v2-dbwebb.se/do%hack"

I want to get this result:

[('https', 'dbwebb.se', ''), ('ftp', 'bth.com', '32'), ('file', 'localhost', '8585'), ('http', 'v2-dbwebb.se', '')]

I tried this:

match = re.findall("(^[a-z]+[^://](^[a-z]+\d))", line)

I'm a beginner in Python.  If there is somebody who can explain, it would be very nice :D

Body:
To provide yet another druidic and hacky regular expression approach:

import re

rx = re.compile(r"""
            (?P<protocol>[^:]+)://  # protocol
            (?P<domain>[^/:]+)      # domain part
            (?::(?P<port>\d+))?     # port, optional
            """, re.VERBOSE)

line = "https://dbwebb.se/kunskap/uml#sequence, ftp://bth.com:32/files/im.jpeg, file://localhost:8585/zipit, http://v2-dbwebb.se/do%hack"

matches = [match.groups()
           for part in line.split(" ")
           for match in [rx.match(part)]]
print(matches)
# [('https', 'dbwebb.se', None), ('ftp', 'bth.com', '32'), ('file', 'localhost', '8585'), ('http', 'v2-dbwebb.se', None)]

See a demo on ideone.com. Otherwise, have a look at @DRC's answer for a very good non-regex way to tackle the problem.


来源: stackexchange

问:
Automatically create One-To-One relation when using reverse field
When creating two instances of a model and connecting them using a OneToOneField, the connection gets created and saved automatically at object creation:

```<code>from django.db import models

class MyModel(models.Model):
    name = models.CharField(primary_key=True, max_length=255)
    next = models.OneToOneField('self', on_delete=models.SET_NULL, related_name='prev', null=True, blank=True)

>>> m2 = MyModel.objects.create(name="2")
>>> m1 = MyModel.objects.create(name="1", next=m2)
>>> m2.prev
<MyModel: 1>
>>> m2.refresh_from_db()
>>> m2.prev
<MyModel: 2>
</code>```

However, when creating the same connection but using the reverse field, the creation is also done automatically but not the save.

```<code>>>> m1 = MyModel.objects.create(name="1")
>>> m2 = MyModel.objects.create(name="2", prev=m1)
>>> m1.next
<MyModel: 2>
>>> m1.refresh_from_db()
>>> m1.next
</code>```

Note that the last statement doesn't print anything since it returns None

How can I have it always save the relation when created using the reverse field without having to manually use .save() each time?

答:
Probably simple way to achieve this could be using pre_save/post_save signal which you see as a viable solution. But not sure how viable this answer would be, try to make some mods and see if this works!</p>

```<code>from django.db.models.signals import post_save
from django.dispatch import receiver

class MyModel(models.Model):
    name = models.CharField(primary_key=True, max_length=255)
    next = models.OneToOneField('self', on_delete=models.SET_NULL, related_name='prev', null=True, blank=True)

@receiver(post_save, sender=MyModel)
def mymodel_post_save(sender, instance, **kwargs):
     if hasattr(instance, 'prev'): # if prev exists
          # now check if prev is added next
          if not instance.prev.next: # if next is not present
                 instance.prev.next = instance
                 MyModel.objects.filter(
                     pk=instance.prev.pk
                 ).update(next=instance)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
When creating two instances of a model and connecting them using a OneToOneField, the connection gets created and saved automatically at object creation:

from django.db import models

class MyModel(models.Model):
    name = models.CharField(primary_key=True, max_length=255)
    next = models.OneToOneField('self', on_delete=models.SET_NULL, related_name='prev', null=True, blank=True)

>>> m2 = MyModel.objects.create(name="2")
>>> m1 = MyModel.objects.create(name="1", next=m2)
>>> m2.prev
<MyModel: 1>
>>> m2.refresh_from_db()
>>> m2.prev
<MyModel: 2>

However, when creating the same connection but using the reverse field, the creation is also done automatically but not the save.

>>> m1 = MyModel.objects.create(name="1")
>>> m2 = MyModel.objects.create(name="2", prev=m1)
>>> m1.next
<MyModel: 2>
>>> m1.refresh_from_db()
>>> m1.next

Note that the last statement doesn't print anything since it returns None

How can I have it always save the relation when created using the reverse field without having to manually use .save() each time?

Body:
Probably simple way to achieve this could be using pre_save/post_save signal which you see as a viable solution. But not sure how viable this answer would be, try to make some mods and see if this works!

from django.db.models.signals import post_save
from django.dispatch import receiver

class MyModel(models.Model):
    name = models.CharField(primary_key=True, max_length=255)
    next = models.OneToOneField('self', on_delete=models.SET_NULL, related_name='prev', null=True, blank=True)

@receiver(post_save, sender=MyModel)
def mymodel_post_save(sender, instance, **kwargs):
     if hasattr(instance, 'prev'): # if prev exists
          # now check if prev is added next
          if not instance.prev.next: # if next is not present
                 instance.prev.next = instance
                 MyModel.objects.filter(
                     pk=instance.prev.pk
                 ).update(next=instance)


问:
Python pandas groupby aggregate on multiple columns, then pivot
In Python, I have a pandas DataFrame similar to the following:

```<code>Item | shop1 | shop2 | shop3 | Category
------------------------------------
Shoes| 45    | 50    | 53    | Clothes
TV   | 200   | 300   | 250   | Technology
Book | 20    | 17    | 21    | Books
phone| 300   | 350   | 400   | Technology
</code>```

Where shop1, shop2 and shop3 are the costs of every item in different shops.
Now, I need to  return a DataFrame, after some data cleaning, like this one:

```<code>Category (index)| size| sum| mean | std
----------------------------------------
</code>```

where size is the number of items in each Category and sum, mean and std are related to the same functions applied to the 3 shops. How can I do these operations with the split-apply-combine pattern (groupby, aggregate, apply,...) ?

Can someone help me out? I'm going crazy with this one...thank you!

答:
```<code>df.groupby('Category').agg({'Item':'size','shop1':['sum','mean','std'],'shop2':['sum','mean','std'],'shop3':['sum','mean','std']})
</code>```

Or if you want it across all shops then:

```<code>df1 = df.set_index(['Item','Category']).stack().reset_index().rename(columns={'level_2':'Shops',0:'costs'})
df1.groupby('Category').agg({'Item':'size','costs':['sum','mean','std']})
</code>```

Body:
In Python, I have a pandas DataFrame similar to the following:

Item | shop1 | shop2 | shop3 | Category
------------------------------------
Shoes| 45    | 50    | 53    | Clothes
TV   | 200   | 300   | 250   | Technology
Book | 20    | 17    | 21    | Books
phone| 300   | 350   | 400   | Technology

Where shop1, shop2 and shop3 are the costs of every item in different shops.
Now, I need to  return a DataFrame, after some data cleaning, like this one:

Category (index)| size| sum| mean | std
----------------------------------------

where size is the number of items in each Category and sum, mean and std are related to the same functions applied to the 3 shops. How can I do these operations with the split-apply-combine pattern (groupby, aggregate, apply,...) ?

Can someone help me out? I'm going crazy with this one...thank you!

Body:
df.groupby('Category').agg({'Item':'size','shop1':['sum','mean','std'],'shop2':['sum','mean','std'],'shop3':['sum','mean','std']})

Or if you want it across all shops then:

df1 = df.set_index(['Item','Category']).stack().reset_index().rename(columns={'level_2':'Shops',0:'costs'})
df1.groupby('Category').agg({'Item':'size','costs':['sum','mean','std']})


问:
Use QtConcurrent::map as a parallel for loop
I want to have a for loop that executes in parallel with Qt and I came across QtConcurrent::map. My current code looks like this:

```<code>QList<int> list;
for(int i=0;i<100;i++) list.append(i);
auto future=QtConcurrent::map(list,[=](const int &i) {
    // do stuff in parallel
});
</code>```

The QList looks like a waste of space (in code lines, and memory). Is there a (pseudo) iterator that just counts between 2 numbers? Is there a smarter solution within Qt?

答:
You can try QtConcurrent::run instead:</p>

```<code>for (int i = 0; i < 100; i++) {
  QtConcurrent::run([=] {
    // do stuff in parallel
  });
}
</code>```

Body:
I want to have a for loop that executes in parallel with Qt and I came across QtConcurrent::map. My current code looks like this:

QList<int> list;
for(int i=0;i<100;i++) list.append(i);
auto future=QtConcurrent::map(list,[=](const int &i) {
    // do stuff in parallel
});

The QList looks like a waste of space (in code lines, and memory). Is there a (pseudo) iterator that just counts between 2 numbers? Is there a smarter solution within Qt?

Body:
You can try QtConcurrent::run instead:

for (int i = 0; i < 100; i++) {
  QtConcurrent::run([=] {
    // do stuff in parallel
  });
}


问:
How to install an older version of Angular?
I need to install Angular 2 but when I'm run $ ng new myApp the version is 4. I searched a lot, but I could not find a way to install only version 2.

Does anyone know how to do it?

Edit
the command:
ng new MYAPP --ng4=false It does not work.

答:
I'd also recommend using Angular 4 - the differences aren't really significant enough to worry about the differences in versions. In fact, one of the goals of Angular 4 is to allow it to be backwards compatible with Angular 2.

But, I can definitely understand the risk of using a different version from the course as a new learner - you want to minimize differences as much as you possibly can so you can be (relatively) sure that an error is because you did something wrong.

So, with all that, I'd recommend two approaches:

The first (and preferable) approach is to identify the angular CLI version that the teacher is using and install that specific version of the CLI (hopefully, at some point in the course, the teacher shows the package.json so you can see the angular CLI version in use. Then I would install that specific CLI version both globally and then in my project).

The second option would be to update the package.json in your application to match the package.json of the teacher (but without changing the global Angular CLI version). This is slightly more risky, but should still be relatively safe if you ensure that the angular cli version in your project matches that of the teacher.

Note that both options require you to be able to get/view the package.json that your course is using so that you can match version numbers. Without that option, it's just a blind guess if you're actually using the same versions as your course.


问:
Virtual inheritance - why this output
Take a look at the code below. Why the output from static_cast<D2&>(m).f() and cout << static_cast(m).f() is 33, not 21?

```<code>struct B {
    virtual int f() {return 1;}
};
struct D1 : virtual public B {
    virtual int f(){return 2;}
};
struct D2 :  virtual public B{};
struct M : public D1, public D2 {
    virtual int f() {return 3;}
};

int main(){
    M m;
    cout << static_cast<D2&>(m).f();
    cout << static_cast<B&>(m).f();
    return 0;
}
</code>```

答:
Because that's the entire point of virtual dispatch: The target of the dispatch is determined by the dynamic type of the most-derived object that contains the statically nominated object of the call expression.

If you don't want virtual dispatch, you can bypass it by qualifying the function call:

```<code>m.B::f();
m.D1::f();
m.D2::f();
</code>```

Title: Virtual inheritance - why this output

Body:
Take a look at the code below. Why the output from static_cast<D2&>(m).f() and cout << static_cast(m).f() is 33, not 21?

struct B {
    virtual int f() {return 1;}
};
struct D1 : virtual public B {
    virtual int f(){return 2;}
};
struct D2 :  virtual public B{};
struct M : public D1, public D2 {
    virtual int f() {return 3;}
};

int main(){
    M m;
    cout << static_cast<D2&>(m).f();
    cout << static_cast(m).f();
    return 0;
}

Body:
Because that's the entire point of virtual dispatch: The target of the dispatch is determined by the dynamic type of the most-derived object that contains the statically nominated object of the call expression.

If you don't want virtual dispatch, you can bypass it by qualifying the function call:

m.B::f();
m.D1::f();
m.D2::f();


问:
Build custom query with gorm Golang lib
I'm using http://jinzhu.me/gorm/crud.html#query

I want to build selectQuery base on some custom conditions

```<code>selectQuery := db.Select("username").Where("status = 'active'")
selectQuery.Limit(10)
if err := selectQuery.Find(&users).Error; err != nil {
//
} else {
//
}
</code>```

Why limit is not applied?

It’s working if implemented with below code:

```<code>if err := db.Select("username").Where("status = 'active").Limit(10).Find(&users).Error; err != nil {
//
} else {
//
}
</code>```

答:
Why limit is not applied?

Because you're ignoring the return value of Limit. In effect, you're creating a query with a limit, then throwing it away without ever executing it.

You need to use:

```<code>selectQuery = selectQuery.Limit(10)
</code>```

Title: Build custom query with gorm Golang lib

Body:
I'm using http://jinzhu.me/gorm/crud.html#query

I want to build selectQuery base on some custom conditions

selectQuery := db.Select("username").Where("status = 'active'")
selectQuery.Limit(10)
if err := selectQuery.Find(&users).Error; err != nil {
//
} else {
//
}

Why limit is not applied?

It’s working if implemented with below code:

if err := db.Select("username").Where("status = 'active").Limit(10).Find(&users).Error; err != nil {
//
} else {
//
}

Body:
Why limit is not applied?

Because you're ignoring the return value of Limit. In effect, you're creating a query with a limit, then throwing it away without ever executing it.

You need to use:

selectQuery = selectQuery.Limit(10)


答: Your object is an instance of M, and casting to base reference types doesn't change that.  The whole point of virtual functions is that when you call a function on a base pointer or reference, it goes to the derived implementation.

Title: Virtual inheritance - why this output


问:
SVN: Merging two branches together
We have multiple developers working on a project. We're employing a feature-branch method of branching in which we do the following:

All maintenance work and bug fixes are done on the trunk

All new functionality is done on a new branch

Branch is updated regularly (via merging changes from trunk to branch)

However, we've run into a situation that 2 branches [we'll call them feature-branch-1 and feature-branch-2] need to be merged together. What is the best way to accomplish this? Part of me thinks we should create a new branch. Then, merge that branch with the first feature branch [feature-branch-1]. And then merge with the second feature branch [feature-branch-2] and take care of the conflicts (which will most likely be the project files).

Is there a better way?

Thanks guys!

答:
Oooh the merging. Love it.

If you mean you want to combine feature-branch-1, feature-branch-2 and trunk into some new branch then yes - your way is good. Otherwise I wouldn't waste precious time and just copy feature-branch-1 and merge feature-branch-2 into it. You've probably would've done it already instead of asking this question :D

ContentLicense: CC BY-SA 2.5

Title: SVN: Merging two branches together


问:
System.DllNotFoundException on Mono SQLite
I've been trying to figure this out lately. It is working on my Windows machine, where I got SQLite from NuGet, but...

When I put System.Data.SQLite.dll and SQLite.Interop.dll straight from my Windows machine into Linux server it says that SQLite.Interop.dll is not found, but I am sure I see it next right to executable.

Then I tried to compile System.Data.SQLite.dll with /p:UseInteropDll=false, but with no luck. This time it says that System.Data.SQLite.dll is not found.

What is this "not found" mystery?

答:
No code changes necessary. You can build it yourself.

apt-get install build-essentials unzip

Download the SQLITE source code - you want the full source code. Currently called sqlite-netFx-full-source-1.0.104.0.zip.

unzip and cd Source,

chmod +x the compile-interop-assembly-release.sh build shell script, then run it ./compile-interop-assembly-release.sh. - It'll build an .so file in the ../bin directory.

Copy this .so file to the directory that has your application in

Run your application as normal.

Note: Ensure that your SQLite database and the directory it's inside of are writable by the user you're trying to run as.


问:
Chrome extension: sendMessage from content to background getting response from popup
I am trying to send a message from a content script to my background script. When the background receives the message it sends data back to the content script in the callback.

My popup also has a listener for messages from the content script, but does not respond to a message meant for the background script.

Then content is receiving an undefined back from the callback, which I think is caused by the popup receiving the message but not responding.

The reference says:

Note: If multiple pages are listening for onMessage events, only the
  first to call sendResponse() for a particular event will succeed in
  sending the response. All other responses to that event will be
  ignored.

So surely I should only get the response from my background script.

My content script does this:

```<code>function notifyReady() {

    chrome.runtime.sendMessage({
        type: 'ACTIVITY_HISTORY_READY'
    },
        function (response) {
            console.log(">>>>Response: ", response);
            if (response.type == 'HISTORY_DATA') {
                processLog(response);
            }
        });
}
</code>```

My background script listens like this:

```<code>chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
    console.log("received " + msg.type);
    if (msg.type = 'ACTIVITY_HISTORY_READY' && historyData) {
        if (historyData) {
            sendResponse({
                type: "HISTORY_DATA",
                position: historyData.position,
                company: historyData.company
            });
            historyData = '';
        } else {
            sendResponse({
                type: "NO_DATA"
            });
        }
    }
});
</code>```

And the listener in my popup is:

```<code>chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {

    if (msg.type == 'JOB_DETAILS') {

        sendResponse("OK!");

        document.getElementById('position').value = msg.position;
        document.getElementById('company').value = msg.company;
        document.getElementById('url').value = sender.tab.url;
    }
});
</code>```

答:
```<code>if (msg.type = 'ACTIVITY_HISTORY_READY' && historyData) {
</code>```

note that if historyData is falsey you are not sending any response. The else branch of the second if can never be taken.

You should remove historyData from the first if. The popup code has nothing to do with this.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to send a message from a content script to my background script. When the background receives the message it sends data back to the content script in the callback.

My popup also has a listener for messages from the content script, but does not respond to a message meant for the background script.

Then content is receiving an undefined back from the callback, which I think is caused by the popup receiving the message but not responding.

The reference says:

Note: If multiple pages are listening for onMessage events, only the
  first to call sendResponse() for a particular event will succeed in
  sending the response. All other responses to that event will be
  ignored.

So surely I should only get the response from my background script.

My content script does this:

function notifyReady() {

    chrome.runtime.sendMessage({
        type: 'ACTIVITY_HISTORY_READY'
    },
        function (response) {
            console.log(">>>>Response: ", response);
            if (response.type == 'HISTORY_DATA') {
                processLog(response);
            }
        });
}

My background script listens like this:

chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
    console.log("received " + msg.type);
    if (msg.type = 'ACTIVITY_HISTORY_READY' && historyData) {
        if (historyData) {
            sendResponse({
                type: "HISTORY_DATA",
                position: historyData.position,
                company: historyData.company
            });
            historyData = '';
        } else {
            sendResponse({
                type: "NO_DATA"
            });
        }
    }
});

And the listener in my popup is:

chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {

    if (msg.type == 'JOB_DETAILS') {

        sendResponse("OK!");

        document.getElementById('position').value = msg.position;
        document.getElementById('company').value = msg.company;
        document.getElementById('url').value = sender.tab.url;
    }
});

Body:
if (msg.type = 'ACTIVITY_HISTORY_READY' && historyData) {

note that if historyData is falsey you are not sending any response. The else branch of the second if can never be taken.

You should remove historyData from the first if. The popup code has nothing to do with this.


问:
Determine which if statement was triggered? (python 2.7)
how would I determine which if statement was triggered?

Example:

```<code>string = "hello"
if len(string) > 10:
    print("over 10")

elif string == "hello":
    print("String is equal to hello")

else:
    pass
</code>```

I want to rewrite it so its more "pythonic", I have gotten this far

```<code>string = "hello"
if len(string) > 10 or string == "hello":
    print("one of the if statements was triggered") # I want to determine which was triggered
else:
    pass
</code>```

Is what I am hoping to accomplish even possible?

Thanks

答:
IMO, there is nothing wrong with the if statement you use.

But if you want to be clever you could use a list of lambda's:

```<code>In [1]: string  = 'Hello'

In [2]: conditions = [lambda s: 'Length is > 10' if len(s) > 10 else None,
   ...:               lambda s: 'String is "Hello"' if s == 'Hello' else None]
</code>```

The conditions are anonymous functions. They return a string describing the condition or None using the ternary operator.

This is slightly different from your if-statement in that it tests all the conditions.

We apply the functions to the string, filtering out the None values:

```<code>In [3]: results = [r for r in [c(string) for c in conditions] if r is not None]
</code>```

The results is a list of strings describing conditions that apply to the string.

We print the results.

```<code>In [4]: for r in results:
   ...:         print(r)
   ...:
String is "Hello"
</code>```

This certainly makes good use of the possibilities that Python offers.

If you would consider this Pythonic is a matter of taste. :-) The original if-statement is shorter, and probably easier to read! Especially for someone new to Python.

However, if you want to test a lot of conditions this could be a good approach instead of a huge list of if-statements.

Body:
how would I determine which if statement was triggered?

Example:

string = "hello"
if len(string) > 10:
    print("over 10")

elif string == "hello":
    print("String is equal to hello")

else:
    pass

I want to rewrite it so its more "pythonic", I have gotten this far

string = "hello"
if len(string) > 10 or string == "hello":
    print("one of the if statements was triggered") # I want to determine which was triggered
else:
    pass

Is what I am hoping to accomplish even possible?

Thanks

Body:
IMO, there is nothing wrong with the if statement you use.

But if you want to be clever you could use a list of lambda's:

In [1]: string  = 'Hello'

In [2]: conditions = [lambda s: 'Length is > 10' if len(s) > 10 else None,
   ...:               lambda s: 'String is "Hello"' if s == 'Hello' else None]

The conditions are anonymous functions. They return a string describing the condition or None using the ternary operator.

This is slightly different from your if-statement in that it tests all the conditions.

We apply the functions to the string, filtering out the None values:

In [3]: results = [r for r in [c(string) for c in conditions] if r is not None]

The results is a list of strings describing conditions that apply to the string.

We print the results.

In [4]: for r in results:
   ...:         print(r)
   ...:
String is "Hello"

This certainly makes good use of the possibilities that Python offers.

If you would consider this Pythonic is a matter of taste. :-) The original if-statement is shorter, and probably easier to read! Especially for someone new to Python.

However, if you want to test a lot of conditions this could be a good approach instead of a huge list of if-statements.


问:
Can CNNs be faster than classic descriptors?
Disclamer: I don't know almost nothing on CNNs and I have no idea where I could ask this.

My research is focused on high performance on computer vision applications. We generate codes representing an image in less than 20 ms on images with the largest size of 500pxs.

This is done by combining SURF descriptors and VLAD codes, obtaining a vector representing an image that will be used in our object recognition application.

Can CNNs be faster? According to this benchmark (which is based on much smaller images) the times needed is longer, almost double considering that the size of the image is half of ours.

答:
Yes, they can be faster. The numbers you got are for networks trained for ImageNet classification, 1 Million images, 1000 classes. Unless your classification problem is similar, then using a ImageNet network is overkill.

You should also remember that these networks have weights in the order of 10-100 million, so they are quite expensive to evaluate. But you probably don't need a really big network, and you can design your own network, with less layers and parameters that is much cheaper to evaluate.

In my experience, I designed a network to classify 96x96 sonar image patches, and with around 4000 weights in total, it can get over 95% classification accuracy and run at 40 ms per frame on a RPi2.

A bigger network with 900K weights, same input size, takes 7 ms to evaluate on a Core i7. So this is surely possible, you just need to play with smaller network architectures. A good start is SqueezeNet, which is a network that can achieve good performance in Imagenet, but has 50 times less weights, and it is of course much faster than other networks.


问:
Can you use the free AnjLab Profiler for SQL Server Express to view the actually SQL command used to access the dababase?
It seems the trace can only tell you something accessed the database, but not the SQL command.</p>

答:
Yes.  It will show up in the TextData column.

As an experiment, run a trace selecting all events and all event columns.


问:
c# Richtext box how to set text margin in winform
I am using Richtext box in winform to load an rtf file.

the text align in rtf file is justify, however after loaded in richtext box it just left aligned. I wonder is there any method to set the justify align in richtext box.

And i can't find  a property to set text margin  inside the  richtextbox.is there anyone know how to solve this problem?

Body:
See this
http://geekswithblogs.net/pvidler/archive/2003/10/14/182.aspx


问:
Error inside inject method
I am trying to learn the inject method. I thought I will just print elements as it calculates. But in the following code when I comment print b statement it works fine. But when I uncomment it, error occurs. What does that mean? The error occurs for a+b statement which is at line number 4 mentioned in the error.

```<code>list = *(1..10)

list.inject(0) do |a, b|
  a + b
  print b
end
</code>```

Error:

```<code>undefined method `+' for nil:NilClass (NoMethodError)
</code>```

答:
Solution:

```<code>list.inject(0) do |a, b|
  print b
  a + b
end
#=> 12345678910=> 55
</code>```

Explanation:

inject returns the cumulated value from previous iteration (a).

When you are printing b it is the return value of the iteration, thus a is nil. To solve it move the printing above, so that a is still the return value of the iteration.

Title: Error inside inject method

Body:
I am trying to learn the inject method. I thought I will just print elements as it calculates. But in the following code when I comment print b statement it works fine. But when I uncomment it, error occurs. What does that mean? The error occurs for a+b statement which is at line number 4 mentioned in the error.

list = *(1..10)

list.inject(0) do |a, b|
  a + b
  print b
end

Error:

undefined method `+' for nil:NilClass (NoMethodError)

Body:
Solution:

list.inject(0) do |a, b|
  print b
  a + b
end
#=> 12345678910=> 55

Explanation:

inject returns the cumulated value from previous iteration (a).

When you are printing b it is the return value of the iteration, thus a is nil. To solve it move the printing above, so that a is still the return value of the iteration.


问:
Can not ping docker container from another host which is in the same LAN
I have two hosts, in the same LAN, both running docker:

Host A: 172.16.0.113

Host B: 172.16.0.114

I can ping host A from host B. But, I can not ping a docker container on host A from host B.

I created a docker container running ubuntu, in the docker default network (bridge). The default docker0's IP address is 172.17.0.1. And the IP address of the container (ubuntu) in the host (172.16.0.113) is 172.17.0.2. The command I used is here:

```<code>sudo docker run --name container01 -it -p 8080:80 ubuntu /bin/bash
</code>```

I can ping container01 from its host, host A; but I can not ping container01 from the other host, host B. Note that I have exposed the port of container01.

I think when I ping container01 from the host B, packets are sent to a container in that host. But I want to know how to connect to host A's container01 from host B.

答:
Maybe try doing

sudo docker run --name container01 -it --network=host -p 8080:80 ubuntu /bin/bash

Body:
I have two hosts, in the same LAN, both running docker:

Host A: 172.16.0.113

Host B: 172.16.0.114

I can ping host A from host B. But, I can not ping a docker container on host A from host B.

I created a docker container running ubuntu, in the docker default network (bridge). The default docker0's IP address is 172.17.0.1. And the IP address of the container (ubuntu) in the host (172.16.0.113) is 172.17.0.2. The command I used is here:

sudo docker run --name container01 -it -p 8080:80 ubuntu /bin/bash

I can ping container01 from its host, host A; but I can not ping container01 from the other host, host B. Note that I have exposed the port of container01.

I think when I ping container01 from the host B, packets are sent to a container in that host. But I want to know how to connect to host A's container01 from host B.


问:
Laravel 5.4 HTTP Testing
I am writing a test for a json route in laravel 5.4, I am supposed to be redirected if the GET request is not ajax, the code works correctly on the browser chrome but when I test it does not work as expected. I tried different variation to add headers to the request none worked.

When I changed the request to POST it worked as excepted, I am not sure what I am missing. here is the code

routes.php

```<code>// Redirect all none-ajax routes to the main edit test route
if (!Request::ajax()) {
  Route::get('{vue?}', ['as'=>'vue_redirect', 'uses' => 'TestController@vueHandler'])->where('vue', '[\/\w\.-]*');
}
    /*
     * General route to the test instructions
     */
    Route::get('getInstructions', ['as' => 'getInstructions', 'uses' => 'TestController@getInstructions']);
</code>```

This is the test code

```<code>public function testgetTest()
{

  $x = $this->actingAs($this->customer)->json('GET', '/test/edit/' . $this->test->id . '/getInstructions');
  var_dump($x->getContent());

}
</code>```

I tried variation like

$this->actingAs($this->customer)->call('GET', '/test/edit/' . $this->test->id . '/getInstructions', [], [], ['X-Requested-With' => 'XMLHttpRequest']

Put also did not work.

When I change to POST and print out the headers this is what I get

```<code>    if (!Request::ajax()) {
      var_dump(Request::header());
      Route::get('{vue?}', ['as'=>'vue_redirect', 'uses' => 'TestController@vueHandler'])->where('vue', '[\/\w\.-]*');
    }

    /*
     * General route to the test instructions
     */
    Route::post('getInstructions', ['as' => 'getInstructions', 'uses' => 'TestController@getInstructions']);
</code>```

Output for the POST working

```<code>array(5) {
  ["host"]=>
  array(1) {
    [0]=>
    string(7) "app.dev"
  }
  ["user-agent"]=>
  array(1) {
    [0]=>
    string(11) "Symfony/3.X"
  }
  ["accept"]=>
  array(1) {
    [0]=>
    string(63) "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
  }
  ["accept-language"]=>
  array(1) {
    [0]=>
    string(14) "en-us,en;q=0.5"
  }
  ["accept-charset"]=>
  array(1) {
    [0]=>
    string(30) "ISO-8859-1,utf-8;q=0.7,*;q=0.7"
  }
}
string(373) "{"success":true,"message":{"id":1,"type_id":"2","user_id":"3","test_name":"Test-MEAjT","test_url":"http:\/\/www.kuphal.com\/eveniet-distinctio-voluptas-sint","test_instructions":"Accusamus laboriosam alias magni ea. Et libero totam sunt ut.","status":"draft","completion_date":null,"is_onboarding":"0","created_at":"2017-04-02 19:50:00","updated_at":"2017-04-02 19:50:00"}}"
</code>```

I can see the correct output, but the headers are not correct which is confusing for me.

答:
I managed to solve this issue based on guidance of @sisve @lagbox I made the following updates to the code.

I removed the condition of checking ajax to a middleware, then I moved the location of the route vue_redirect to the bottom of the match so it does not conflict with other routes. (which was a bug that redirect all the traffic to the wrong route).

Routes.php

```<code>Route::group(['middleware' => ['VerifyAjaxRequest']], function(){
          /*
           * General route to the test instructions
           */
          Route::get('getInstructions', ['as' => 'getInstructions', 'uses' => 'TestController@getInstructions']);

});
</code>```

VerifyAjaxRequest.php middleware

```<code>public function handle($request, Closure $next)
{

  // Redirect all none-ajax routes to the main edit test route
  if (!$request->ajax()) {
    return redirect(route('vue_redirect'));
  }

  return $next($request);
}
</code>```

Test.php

```<code>public function testgetTest()
{
  $response = $this->actingAs($this->customer)->json('get', '/test/edit/' . $this->test->id . '/getInstructions', [], ['X-Requested-With'=>'XMLHttpRequest']);
  var_dump($response->getContent());
}
</code>```

Now it works as excepted including headers and correct response

Title: Laravel 5.4 HTTP Testing

Body:
I am writing a test for a json route in laravel 5.4, I am supposed to be redirected if the GET request is not ajax, the code works correctly on the browser chrome but when I test it does not work as expected. I tried different variation to add headers to the request none worked.

When I changed the request to POST it worked as excepted, I am not sure what I am missing. here is the code

routes.php

// Redirect all none-ajax routes to the main edit test route
if (!Request::ajax()) {
  Route::get('{vue?}', ['as'=>'vue_redirect', 'uses' => 'TestController@vueHandler'])->where('vue', '[\/\w\.-]*');
}
    /*
     * General route to the test instructions
     */
    Route::get('getInstructions', ['as' => 'getInstructions', 'uses' => 'TestController@getInstructions']);

This is the test code

public function testgetTest()
{

  $x = $this->actingAs($this->customer)->json('GET', '/test/edit/' . $this->test->id . '/getInstructions');
  var_dump($x->getContent());

}

I tried variation like

$this->actingAs($this->customer)->call('GET', '/test/edit/' . $this->test->id . '/getInstructions', [], [], ['X-Requested-With' => 'XMLHttpRequest']

Put also did not work.

When I change to POST and print out the headers this is what I get

    if (!Request::ajax()) {
      var_dump(Request::header());
      Route::get('{vue?}', ['as'=>'vue_redirect', 'uses' => 'TestController@vueHandler'])->where('vue', '[\/\w\.-]*');
    }

    /*
     * General route to the test instructions
     */
    Route::post('getInstructions', ['as' => 'getInstructions', 'uses' => 'TestController@getInstructions']);

Output for the POST working

array(5) {
  ["host"]=>
  array(1) {
    [0]=>
    string(7) "app.dev"
  }
  ["user-agent"]=>
  array(1) {
    [0]=>
    string(11) "Symfony/3.X"
  }
  ["accept"]=>
  array(1) {
    [0]=>
    string(63) "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
  }
  ["accept-language"]=>
  array(1) {
    [0]=>
    string(14) "en-us,en;q=0.5"
  }
  ["accept-charset"]=>
  array(1) {
    [0]=>
    string(30) "ISO-8859-1,utf-8;q=0.7,*;q=0.7"
  }
}
string(373) "{"success":true,"message":{"id":1,"type_id":"2","user_id":"3","test_name":"Test-MEAjT","test_url":"http:\/\/www.kuphal.com\/eveniet-distinctio-voluptas-sint","test_instructions":"Accusamus laboriosam alias magni ea. Et libero totam sunt ut.","status":"draft","completion_date":null,"is_onboarding":"0","created_at":"2017-04-02 19:50:00","updated_at":"2017-04-02 19:50:00"}}"

I can see the correct output, but the headers are not correct which is confusing for me.

Body:
I managed to solve this issue based on guidance of @sisve @lagbox I made the following updates to the code.

I removed the condition of checking ajax to a middleware, then I moved the location of the route vue_redirect to the bottom of the match so it does not conflict with other routes. (which was a bug that redirect all the traffic to the wrong route).

Routes.php

Route::group(['middleware' => ['VerifyAjaxRequest']], function(){
          /*
           * General route to the test instructions
           */
          Route::get('getInstructions', ['as' => 'getInstructions', 'uses' => 'TestController@getInstructions']);

});

VerifyAjaxRequest.php middleware

public function handle($request, Closure $next)
{

  // Redirect all none-ajax routes to the main edit test route
  if (!$request->ajax()) {
    return redirect(route('vue_redirect'));
  }

  return $next($request);
}

Test.php

public function testgetTest()
{
  $response = $this->actingAs($this->customer)->json('get', '/test/edit/' . $this->test->id . '/getInstructions', [], ['X-Requested-With'=>'XMLHttpRequest']);
  var_dump($response->getContent());
}

Now it works as excepted including headers and correct response


问:
Check record exists db - error show
How do I check if username or email exists and then put a error message in my error array. Right now i have:

```<code>$sql = "SELECT username, email FROM users WHERE username = '" . $username . "' OR email = '" . $email . "'";

$query = mysql_query($sql);

if (mysql_num_rows($query) > 0)
{
 echo "That username or email already exists";
}
</code>```

But I want to check if it is the username OR the email that is existing and then put:

error[] = "username is existing"; //if the username is existing

error[] = "email is existing"; //if the email is existing

How to do?

答:
It would be easier if you just did a quick true/false check in the SQL and checked the flag that came back.

```<code>$sql = "SELECT "
  . "(SELECT 1 FROM `users` WHERE `username` = '" . mysql_real_escape_string($username) . "'), "
  . "(SELECT 1 FROM `users` WHERE `email` = '" . mysql_real_escape_string($email) . "')";

$query = mysql_query($sql);

if (mysql_num_rows($query) > 0) {
  $foundFlags = mysql_fetch_assoc($query);
  if ($foundFlags['username']) {
    $error[] = "username is existing";
  }

  if ($foundFlags['email']) {
    $error[] = "email is existing";
  }
} else {
  // General error as the query should always return
}
</code>```

When it does not find an entry, it will return NULL in the flag, which evaluates to false, so the if condition is fine.

Note that you could generalise it for a field list like this:

```<code>$fieldMatch = array('username' => $username, 'email' => $email);

$sqlParts = array();
foreach ($fieldMatch as $cFieldName => $cFieldValue) {
  $sqlParts[] = "(SELECT 1 FROM `users` WHERE `" . $cFieldName . "` = '" . mysql_real_escape_string($cFieldValue) . "')";
}

$sql = "SELECT " . implode(", ", $sqlParts);

$query = mysql_query($sql);

if (mysql_num_rows($query) > 0) {
  $foundFlags = mysql_fetch_assoc($query);
  foreach ($foundFlags as $cFieldName => $cFlag) {
    if ($foundFlags[$cFieldName]) {
      $error[] = $cFieldName . " is existing";
    }
  }
} else {
  // General error as the query should always return
}
</code>```

NB. Note that assumes all fields are strings, or other string-escaped types (eg. date/time).

Title: Check record exists db - error show

Body:
How do I check if username or email exists and then put a error message in my error array. Right now i have:

$sql = "SELECT username, email FROM users WHERE username = '" . $username . "' OR email = '" . $email . "'";

$query = mysql_query($sql);

if (mysql_num_rows($query) > 0)
{
 echo "That username or email already exists";
}

But I want to check if it is the username OR the email that is existing and then put:

error[] = "username is existing"; //if the username is existing

error[] = "email is existing"; //if the email is existing

How to do?

Body:
It would be easier if you just did a quick true/false check in the SQL and checked the flag that came back.

$sql = "SELECT "
  . "(SELECT 1 FROM `users` WHERE `username` = '" . mysql_real_escape_string($username) . "'), "
  . "(SELECT 1 FROM `users` WHERE `email` = '" . mysql_real_escape_string($email) . "')";

$query = mysql_query($sql);

if (mysql_num_rows($query) > 0) {
  $foundFlags = mysql_fetch_assoc($query);
  if ($foundFlags['username']) {
    $error[] = "username is existing";
  }

  if ($foundFlags['email']) {
    $error[] = "email is existing";
  }
} else {
  // General error as the query should always return
}

When it does not find an entry, it will return NULL in the flag, which evaluates to false, so the if condition is fine.

Note that you could generalise it for a field list like this:

$fieldMatch = array('username' => $username, 'email' => $email);

$sqlParts = array();
foreach ($fieldMatch as $cFieldName => $cFieldValue) {
  $sqlParts[] = "(SELECT 1 FROM `users` WHERE `" . $cFieldName . "` = '" . mysql_real_escape_string($cFieldValue) . "')";
}

$sql = "SELECT " . implode(", ", $sqlParts);

$query = mysql_query($sql);

if (mysql_num_rows($query) > 0) {
  $foundFlags = mysql_fetch_assoc($query);
  foreach ($foundFlags as $cFieldName => $cFlag) {
    if ($foundFlags[$cFieldName]) {
      $error[] = $cFieldName . " is existing";
    }
  }
} else {
  // General error as the query should always return
}

NB. Note that assumes all fields are strings, or other string-escaped types (eg. date/time).


问:
Adding Attribute Labels to DynamicModel Yii
I have dynamic number of questions and answers. I use DynamicModel() for collecting these data.

```<code>$attributes = [
      "answer_1" => "Some Value 1",
      "answer_2" => "Some Value 2",
      "answer_3" => "Some Value 3",
      .....
]

$customFormModel = new DynamicModel($attributes);
</code>```

I also have

```<code>$labels = [
      "answer_1" => "Label 1",
      "answer_2" => "Label 2",
      "answer_3" => "Label 3",
      .....
]
</code>```

I just can't get the $label array to be set as Label Attributes for my Dynamic Model.
My $customFormModel->attributeLabels() is always empty.

These results with the following issue.
I get error messages like these

```<code>Answer 1 can not be blank
Answer 2 can not be blank
Answer 3 can not be blank
</code>```

What I want instead

```<code>Label 1 can not be blank
Label 2 can not be blank
Label 3 can not be blank
</code>```

答:
you can simply extend DynamicModel like this :

```<code>class MyDynamicModel extends DynamicModel
{
    public $attributeLabels = [];

    public function attributeLabels(){
        return $this->attributeLabels;
    }
}
</code>```

now you can set $attributeLabels as array

Body:
I have dynamic number of questions and answers. I use DynamicModel() for collecting these data.

$attributes = [
      "answer_1" => "Some Value 1",
      "answer_2" => "Some Value 2",
      "answer_3" => "Some Value 3",
      .....
]

$customFormModel = new DynamicModel($attributes);

I also have

$labels = [
      "answer_1" => "Label 1",
      "answer_2" => "Label 2",
      "answer_3" => "Label 3",
      .....
]

I just can't get the $label array to be set as Label Attributes for my Dynamic Model.
My $customFormModel->attributeLabels() is always empty.

These results with the following issue.
I get error messages like these

Answer 1 can not be blank
Answer 2 can not be blank
Answer 3 can not be blank

What I want instead

Label 1 can not be blank
Label 2 can not be blank
Label 3 can not be blank

Body:
you can simply extend DynamicModel like this :

class MyDynamicModel extends DynamicModel
{
    public $attributeLabels = [];

    public function attributeLabels(){
        return $this->attributeLabels;
    }
}

now you can set $attributeLabels as array


问:
Python: check if "two" .doc files are the same file?
IMAP filtering and searching dictates that my script works as follows: Each night I receive an email with a relevant .doc file attached to it. My Python script always selects the last (most recent) email, and does certain operations on that .doc file.

All .doc files sent daily are named exactly the same.

Issue is: Sometimes the sender neglects to send a new file. The result is that my script does the operation on the wrong file (the one from the day before). If I can somehow check that two files are actually (copies) of the same file, then I can avoid doing the operation.

How is this most easily/effectively achievable in Python?

答:
To compare files binary-wise, the best/quickest way is to use the filecmp module:

```<code>>>> import filecmp
>>> filecmp.cmp("first.doc","second.doc",shallow=False)
</code>```

returns True if both files share the exact file contents. shallow is set to False so the file contents are analysed regardless of a difference of date (which you'll have when you extract both files)

Body:
To compare files binary-wise, the best/quickest way is to use the filecmp module:

>>> import filecmp
>>> filecmp.cmp("first.doc","second.doc",shallow=False)

returns True if both files share the exact file contents. shallow is set to False so the file contents are analysed regardless of a difference of date (which you'll have when you extract both files)


问:
Convert date-time string to class Date
I have a data frame with a character column of date-times.

When I use as.Date, most of my strings are parsed correctly, except for a few instances.  The example below will hopefully show you what is going on.

```<code># my attempt to parse the string to Date -- uses the stringr package
prods.all$Date2 <- as.Date(str_sub(prods.all$Date, 1,
                str_locate(prods.all$Date, " ")[1]-1),
                "%m/%d/%Y")

# grab two rows to highlight my issue
temp <- prods.all[c(1925:1926), c(1,8)]
temp
#                    Date      Date2
# 1925  10/9/2009 0:00:00 2009-10-09
# 1926 10/15/2009 0:00:00 0200-10-15
</code>```

As you can see, the year of some of the dates is inaccurate.  The pattern seems to occur when the day is double digit.

Any help you can provide will be greatly appreciated.

答:
The easiest way is to use lubridate:

```<code>library(lubridate)
prods.all$Date2 <- mdy(prods.all$Date2)
</code>```

This function automatically returns objects of class POSIXct and will work with either factors or characters.

Title: Convert date-time string to class Date

Body:
I have a data frame with a character column of date-times.

When I use as.Date, most of my strings are parsed correctly, except for a few instances.  The example below will hopefully show you what is going on.

# my attempt to parse the string to Date -- uses the stringr package
prods.all$Date2 <- as.Date(str_sub(prods.all$Date, 1,
                str_locate(prods.all$Date, " ")[1]-1),
                "%m/%d/%Y")

# grab two rows to highlight my issue
temp <- prods.all[c(1925:1926), c(1,8)]
temp
#                    Date      Date2
# 1925  10/9/2009 0:00:00 2009-10-09
# 1926 10/15/2009 0:00:00 0200-10-15

As you can see, the year of some of the dates is inaccurate.  The pattern seems to occur when the day is double digit.

Any help you can provide will be greatly appreciated.

Body:
The easiest way is to use lubridate:

library(lubridate)
prods.all$Date2 <- mdy(prods.all$Date2)

This function automatically returns objects of class POSIXct and will work with either factors or characters.


问:
Getting wrong characters in pt-br from xml in python
I'm trying to send data from a XML feed to MySQL database, but I'm getting wrong pt-br characters in python and mysql.

```<code>import MySQLdb
import urllib2
import sys
import codecs

## default enconding
reload(sys)
sys.setdefaultencoding('utf-8')
UTF8Writer = codecs.getwriter('utf8')
sys.stdout = UTF8Writer(sys.stdout)
file = urllib2.urlopen('feed.xml')
data = file.read()
file.close()
data = xmltodict.parse(data)

db = MySQLdb.connect(host=MYSQL_HOST,    # your host, usually localhost
                     user=MYSQL_USER,         # your username
                     passwd=MYSQL_PASSWD,  # your password
                     db=MYSQL_DB)        # name of the data base
cur = db.cursor()

    product_name = str(data.items()[0][1].items()[2][1].items()[3][1][i].items()[1][1])
</code>```

But when I print product_name in Python or insert it into mysql, I get this:

```<code>'Probi\xc3\xb3tica (120caps)'
</code>```

this should be:

```<code>'Probiótica'
</code>```

How can I fix this?

答:
'Probi\xc3\xb3tica' is the utf-8 encoded version of 'Probiótica'.

Is your terminal (or whatever you are using to run this) set up to handle utf-8 output?

Try print 'Probi\xc3\xb3tica'.decode('utf-8') to see what happens.

I get Probiótica.

Body:
I'm trying to send data from a XML feed to MySQL database, but I'm getting wrong pt-br characters in python and mysql.

import MySQLdb
import urllib2
import sys
import codecs

## default enconding
reload(sys)
sys.setdefaultencoding('utf-8')
UTF8Writer = codecs.getwriter('utf8')
sys.stdout = UTF8Writer(sys.stdout)
file = urllib2.urlopen('feed.xml')
data = file.read()
file.close()
data = xmltodict.parse(data)

db = MySQLdb.connect(host=MYSQL_HOST,    # your host, usually localhost
                     user=MYSQL_USER,         # your username
                     passwd=MYSQL_PASSWD,  # your password
                     db=MYSQL_DB)        # name of the data base
cur = db.cursor()

    product_name = str(data.items()[0][1].items()[2][1].items()[3][1][i].items()[1][1])

But when I print product_name in Python or insert it into mysql, I get this:

'Probi\xc3\xb3tica (120caps)'

this should be:

'Probiótica'

How can I fix this?


问:
How to place div in second row directly under div in first row with same column size but blocked by the height of another column in first row
Sorry if the title is confusing. I have included a screenshot of my issue to make it more clear.

Essentially, I want the green-bordered div to be directly underneath the red-bordered div without the blue-bordered div interfering.

Here is my HTML code (I am using Bootstrap v3.3.7)

```<code><div class="container appParent">
    <div class="row">
        <div class="col-md-6" id="song-view">
            <app-selected-song-view></app-selected-song-view>
        </div>
        <div class="col-md-6" id="songs-added">
            <app-songs-added></app-songs-added>
        </div>

    </div>
    <div class="row">
        <div class="col-md-6" id="playlist-form">
            <app-playlist-form></app-playlist-form>
        </div>
    </div>
</div>
</code>```

My CSS is only putting the borders around the div. Everything else is bootstrap.

```<code>#song-view{
    border: 2px solid red;
}
#songs-added{
    border: 2px solid blue;
}
#playlist-form{
    border: 2px solid green;
}
</code>```

答:
In this case, use pull-right, and keep all of the col- in a single row.

```<code><div class="container appParent">
    <div class="row">
        <div class="col-md-6" id="song-view">
            <app-selected-song-view></app-selected-song-view>
        </div>
        <div class="col-md-6 pull-right col-xs-12" id="songs-added">
            <app-songs-added></app-songs-added>
        </div>
        <div class="col-md-6" id="playlist-form">
            <app-playlist-form></app-playlist-form>
        </div>
    </div>
</div>
</code>```

http://www.codeply.com/go/189ofQG5Sj

Body:
Sorry if the title is confusing. I have included a screenshot of my issue to make it more clear.

Essentially, I want the green-bordered div to be directly underneath the red-bordered div without the blue-bordered div interfering.

Here is my HTML code (I am using Bootstrap v3.3.7)

            <app-selected-song-view></app-selected-song-view>

            <app-songs-added></app-songs-added>

            <app-playlist-form></app-playlist-form>

My CSS is only putting the borders around the div. Everything else is bootstrap.

#song-view{
    border: 2px solid red;
}
#songs-added{
    border: 2px solid blue;
}
#playlist-form{
    border: 2px solid green;
}

Body:
In this case, use pull-right, and keep all of the col- in a single row.

<div class="container appParent">
    <div class="row">
        <div class="col-md-6" id="song-view">
            <app-selected-song-view></app-selected-song-view>
        </div>
        <div class="col-md-6 pull-right col-xs-12" id="songs-added">
            <app-songs-added></app-songs-added>
        </div>
        <div class="col-md-6" id="playlist-form">
            <app-playlist-form></app-playlist-form>
        </div>
    </div>
</div>

http://www.codeply.com/go/189ofQG5Sj


问:
Handling acks in Akka Streams
I have seen the examples of using Akka Streams to avoid backpressure but wondering how this works if I need to get custom acks downstream?

In my specific case I have several flows in the chain which process a message and when it reaches a certain flow I would like to pass an ack back to the source in order to signal that I have now "taken ownership" of the resource being processes.

How does this work in Akka Streams?

答:
I suppose there is more than one solution to this problem. A simple approach is to augment your data with a Promise[Unit] to be successfully completed to signal an ack.
This has its cons (namely the lack of backpressure support), but it has simplicity by its side.

For more information on the topic, check out this blogpost.

Acked-stream is an excellent library based on this approach.

Title: Handling acks in Akka Streams


问:
SVN: Merging two branches together
We have multiple developers working on a project. We're employing a feature-branch method of branching in which we do the following:

All maintenance work and bug fixes are done on the trunk

All new functionality is done on a new branch

Branch is updated regularly (via merging changes from trunk to branch)

However, we've run into a situation that 2 branches [we'll call them feature-branch-1 and feature-branch-2] need to be merged together. What is the best way to accomplish this? Part of me thinks we should create a new branch. Then, merge that branch with the first feature branch [feature-branch-1]. And then merge with the second feature branch [feature-branch-2] and take care of the conflicts (which will most likely be the project files).

Is there a better way?

Thanks guys!

答:
It depends somewhat on what you are trying to accomplish.  Why do you want to merge two feature branches?  If it's because the two features have logically "combined," just pick one to merge into the other, then do all your development on the merged branch.  If it's because there are dependencies on items in the other branches, there is probably enough commonality still to merge into one branch, then only if truly needed, branch off the merged branch to develop a feature independently.

Keeping two non-trunk branches synchronized when they are for different features is likely to cause much pain; I wouldn't recommend it if you can help it.

Title: SVN: Merging two branches together


问:
What are all the possibilities to pass the data one component to another component without navigation or route in angular 2 type script?
I am a beginner for learning  Angular 2 type script. I want to pass the data between one component to another component?

Serives.ts

```<code>    import {Component, Injectable} from '@angular/core';

    // Name Service
    export interface myData {
       myDataname:any;
    }

    @Injectable()
    export class GetService {
        sharingData:any={myDataname:"My data string"};

        saveData(str:any){
            alert("Save Data");
        // console.log('save data function called' + JSON.stringify(str));
        this.sharingData.myDataname=str;
        console.log(JSON.stringify(this.sharingData.myDataname));
      }
      getData():any{
     console.log('get data function called');
     console.log(JSON.stringify(this.sharingData.myDataname)+ "Get dats service s");
        return this.sharingData.myDataname;
}
    }
</code>```

First Component.ts

```<code>import { GetService } from '../service/get-service';

    @Component({
      selector: 'firstcomponent,
      templateUrl: 'firstcomponent.html',
      providers:[GetService]
    })

    export class firstcomponentDetails {
    firstname:string;
    lastname:string;

      constructor(public getservice: GetService ) {
         this.getservice= getservice;

    submitForm(value: any):void{
            console.log(' Personal Details Form submited!');
        console.log(value);
        this.getservice.saveData(value);
    }
}
    }
</code>```

Second Component.ts

```<code> import { GetService } from '../service/get-service';
    @Component({
      selector: 'secondpage',
      templateUrl: 'secondpage.html',
       providers: [GetService],
    })
    export class SecondPage {
     getDatavaluesServices:any;
     constructor( public getservice:GetService){
    this.getservice = getservice;
     this.getDatavaluesServices=getservice.getData();
      console.log(this.getDatavaluesServices );
    }
    }
</code>```

This is my code. I tried this code passing data first component to second component. I am getting to string value my data string. How to get first component value?

答:
You can create a service and import it into your main module and export it from there, then inject it into the components where you want to use it.

```<code>import { StateService } from '../../../core/state.service';

  constructor(
    @Inject(StateService) private stateSrvc: StateService
  ) {}
</code>```

Your service will be something like this:

```<code>@Injectable()
export class StateService {
    someStateValue: string;;
}
</code>```

This way you're creating a singleton service, meaning that there will be one instance of the service throughout the application, so any values you set from one component can be retrieved from another, allowing you to pass data back and forth between components without having rely on passing data via the URL and Router Params.

How you maintain the state storage in that service is up to you, you could simply declare variables as above and get and set values directly:

```<code>stateSrvc.someStateValue = 1234
</code>```

or

```<code>someLocalVariable = stateSrvc.someStateValue
</code>```

Or you can setup getVariable and setVariable functions in the service to have more control.

You can also make use of Observables and Subjects or BehaviorSubjects to store state using RxJS.

Body:
I am a beginner for learning  Angular 2 type script. I want to pass the data between one component to another component?

Serives.ts

    import {Component, Injectable} from '@angular/core';

    // Name Service
    export interface myData {
       myDataname:any;
    }

    @Injectable()
    export class GetService {
        sharingData:any={myDataname:"My data string"};

        saveData(str:any){
            alert("Save Data");
        // console.log('save data function called' + JSON.stringify(str));
        this.sharingData.myDataname=str;
        console.log(JSON.stringify(this.sharingData.myDataname));
      }
      getData():any{
     console.log('get data function called');
     console.log(JSON.stringify(this.sharingData.myDataname)+ "Get dats service s");
        return this.sharingData.myDataname;
}
    }

First Component.ts

import { GetService } from '../service/get-service';

    @Component({
      selector: 'firstcomponent,
      templateUrl: 'firstcomponent.html',
      providers:[GetService]
    })

    export class firstcomponentDetails {
    firstname:string;
    lastname:string;

      constructor(public getservice: GetService ) {
         this.getservice= getservice;

    submitForm(value: any):void{
            console.log(' Personal Details Form submited!');
        console.log(value);
        this.getservice.saveData(value);
    }
}
    }

Second Component.ts

 import { GetService } from '../service/get-service';
    @Component({
      selector: 'secondpage',
      templateUrl: 'secondpage.html',
       providers: [GetService],
    })
    export class SecondPage {
     getDatavaluesServices:any;
     constructor( public getservice:GetService){
    this.getservice = getservice;
     this.getDatavaluesServices=getservice.getData();
      console.log(this.getDatavaluesServices );
    }
    }

This is my code. I tried this code passing data first component to second component. I am getting to string value my data string. How to get first component value?

Body:
You can create a service and import it into your main module and export it from there, then inject it into the components where you want to use it.

import { StateService } from '../../../core/state.service';

  constructor(
    @Inject(StateService) private stateSrvc: StateService
  ) {}

Your service will be something like this:

@Injectable()
export class StateService {
    someStateValue: string;;
}

This way you're creating a singleton service, meaning that there will be one instance of the service throughout the application, so any values you set from one component can be retrieved from another, allowing you to pass data back and forth between components without having rely on passing data via the URL and Router Params.

How you maintain the state storage in that service is up to you, you could simply declare variables as above and get and set values directly:

stateSrvc.someStateValue = 1234

or

someLocalVariable = stateSrvc.someStateValue

Or you can setup getVariable and setVariable functions in the service to have more control.

You can also make use of Observables and Subjects or BehaviorSubjects to store state using RxJS.


问:
In Pycharm How to load code to interactive debugger?
I want to be able to load and run several line of code into interactive debugger, to make sure the code works fine. By doing so I don't need to rerun from the beginning of the code, which takes much longer time. I tried two methods but neither work.  Coming from R and Matlab, I do prefer this feature.
Anyone can suggest?

Method 1:
According to interactive shell debugging with pycharm, one can load the code typed in pycharm editor to interactive debugger by

```<code>1> set a debugging point
2> highlight the code you want to load to Python console
3> alt+shift+E
</code>```

When I follow these steps: I set the debug point, debug the code to trigger the debug point, and select the code press alt+shift+e.Instead of loading the code to the debug console, it loaded to the python console by default. I don't have access to variables and packages that I want to debug under the python console context.

I have to minimize the python console, then run it again. Sometimes it runs in debugger console. Below answer suggests to "select the console you want to target". What is the step? you click the debugger? then select the code and press atl+shift+e? I tried, it does not work.

EDIT: found  the official doc but not very helpful:
https://www.jetbrains.com/help/pycharm/2017.1/loading-code-from-editor-into-console.html

Method2:
Type and experiment the code directly in the interactive debugger console. However, there is no easy way to bring the code (multiple lines) back to the editor. The console history is sorted automatically from the newest to oldest. When copied from console history, you have your last line of desired code as the first line in the editor.
See below threads, I have the same issue.
How to invert console history order in pycharm for copy pasting?

答:
Alhough it is not a pycharm's feature, I would strongly suggest trying jupyter notebook. It is very useful for prototyping.

If, you want to do it the pycharm way, as Dag Høidahl pointed out, one option is to execute block of code in console with Alt+Shift+E.

However, to fully leverage the awesome Pycharm's debugger, you should write an unit test calling particular piece of code which you want to test (or debug). This way you can add breakpoints properly debug, or automatically ensure expected behavior in the future.
Nevertheless, writing unit tests has many other advantages you will appreciate.

Body:
I want to be able to load and run several line of code into interactive debugger, to make sure the code works fine. By doing so I don't need to rerun from the beginning of the code, which takes much longer time. I tried two methods but neither work.  Coming from R and Matlab, I do prefer this feature.
Anyone can suggest?

Method 1:
According to interactive shell debugging with pycharm, one can load the code typed in pycharm editor to interactive debugger by

1> set a debugging point
2> highlight the code you want to load to Python console
3> alt+shift+E

When I follow these steps: I set the debug point, debug the code to trigger the debug point, and select the code press alt+shift+e.Instead of loading the code to the debug console, it loaded to the python console by default. I don't have access to variables and packages that I want to debug under the python console context.

I have to minimize the python console, then run it again. Sometimes it runs in debugger console. Below answer suggests to "select the console you want to target". What is the step? you click the debugger? then select the code and press atl+shift+e? I tried, it does not work.

EDIT: found  the official doc but not very helpful:
https://www.jetbrains.com/help/pycharm/2017.1/loading-code-from-editor-into-console.html

Method2:
Type and experiment the code directly in the interactive debugger console. However, there is no easy way to bring the code (multiple lines) back to the editor. The console history is sorted automatically from the newest to oldest. When copied from console history, you have your last line of desired code as the first line in the editor.
See below threads, I have the same issue.
How to invert console history order in pycharm for copy pasting?


问:
Delete files contained in repeated directory locations
I'm looking for a way to script a repeating deletion task. We have a standard directory template which is used repeatedly with the top level renamed. I want to target a named folder in all these directories to delete the files e.g.

```<code>wxyz\TemporaryFiles
acbd\TemporaryFiles
</code>```

etc. I have tried the following:

```<code>for /d %%i in (X:\Company\Projects\*) do cd TemporaryFiles && del /f /s /q %%i\*.*
</code>```

I must have my syntax wrong and would appreciate some help - thanks.

答:
Simpler:

```<code>for /d %%i in ("X:\Company\Projects\*") do del /f /s /q "%%i\TemporaryFiles\*.*"
</code>```

If some directories have not the TemporaryFiles folder, then an error message is shown. You may supress such a message including 2>nul part at end.

Body:
I'm looking for a way to script a repeating deletion task. We have a standard directory template which is used repeatedly with the top level renamed. I want to target a named folder in all these directories to delete the files e.g.

wxyz\TemporaryFiles
acbd\TemporaryFiles

etc. I have tried the following:

for /d %%i in (X:\Company\Projects\*) do cd TemporaryFiles && del /f /s /q %%i\*.*

I must have my syntax wrong and would appreciate some help - thanks.

Body:
Simpler:

for /d %%i in ("X:\Company\Projects\*") do del /f /s /q "%%i\TemporaryFiles\*.*"

If some directories have not the TemporaryFiles folder, then an error message is shown. You may supress such a message including 2>nul part at end.


问:
C# method is not returning object - method chaining
I came across the post on stackoverflow that provided solution to question by chaining two methods. The answer looked something like this:

```<code>public x DoThis()
 {
    //do something
    return this;

 }

public x DoThat ()
{
   //do something else
   return this;

}

var x = new x ().DoThis().DoThat;
</code>```

I read about chaining methods. But something does not seem to be right in this case. I created a class called Library with two different methods that return the same type, and I can access first of the methods, but not the second one. Unless, I'm doing something wrong, that solution is incorrect.

I watched tutorial on creating collection extention methods and I wanted to try use this approach. I have to admit that I do not understand everything about it yet. So I thought, I should be able to use IEnumerable<> because I'm only passing collection to this class

Here is a class:

```<code>class Library
{
    private IEnumerable<Movie> MoviesLibrary;

    public Library(IEnumerable<Movie> library)
    {
        this.MoviesLibrary = library.ToList();

    }

    public IEnumerable<Movie> FindMovie(int _movieId)
    {

        return this.MoviesLibrary.Where(movie => movie.MovieId == _movieId);

    }

    public IEnumerable<Movie> GetByYear(int _year)
    {

        return this.MoviesLibrary.Where(movie => movie.Year == _year);

    }

}
</code>```

As I understand "return this" statement should return currently instantiated object. In chained method, next method should use that returned object and perform its own action.

答:
Can you provide more context for the first code example you gave?
(the one that doesn't work - for example what is X in your case? what class has the first method?).

The last example you gave

```<code>public IEnumerable<Movie> GetByYear(int _year)
{
   this.MoviesLibrary.Where(movie => movie.MovieId == _movieId);
    return this;
}
</code>```

is incorrect because you return an IEnumerable,
and IEnumerable doesn't have the additional method which aren't extension methods.

Extension methods indeed may help you achieve what you want.
In fact, Linq is implemented as a set of extension methods to IEnumerable

See
https://referencesource.microsoft.com/#System.Core/System/Linq/Enumerable.cs,577032c8811e20d3

for more info (and examples how to write extension methods).

Also you may want to read more about extension method in their formal msdn page
https://msdn.microsoft.com/en-us/library/bb383977.aspx

Body:
I came across the post on stackoverflow that provided solution to question by chaining two methods. The answer looked something like this:

public x DoThis()
 {
    //do something
    return this;

 }

public x DoThat ()
{
   //do something else
   return this;

}

var x = new x ().DoThis().DoThat;

I read about chaining methods. But something does not seem to be right in this case. I created a class called Library with two different methods that return the same type, and I can access first of the methods, but not the second one. Unless, I'm doing something wrong, that solution is incorrect.

I watched tutorial on creating collection extention methods and I wanted to try use this approach. I have to admit that I do not understand everything about it yet. So I thought, I should be able to use IEnumerable<> because I'm only passing collection to this class

Here is a class:

class Library
{
    private IEnumerable<Movie> MoviesLibrary;

    public Library(IEnumerable<Movie> library)
    {
        this.MoviesLibrary = library.ToList();

    }

    public IEnumerable<Movie> FindMovie(int _movieId)
    {

        return this.MoviesLibrary.Where(movie => movie.MovieId == _movieId);

    }

    public IEnumerable<Movie> GetByYear(int _year)
    {

        return this.MoviesLibrary.Where(movie => movie.Year == _year);

    }

}

As I understand "return this" statement should return currently instantiated object. In chained method, next method should use that returned object and perform its own action.

Body:
Can you provide more context for the first code example you gave?
(the one that doesn't work - for example what is X in your case? what class has the first method?).

The last example you gave

public IEnumerable<Movie> GetByYear(int _year)
{
   this.MoviesLibrary.Where(movie => movie.MovieId == _movieId);
    return this;
}

is incorrect because you return an IEnumerable,
and IEnumerable doesn't have the additional method which aren't extension methods.

Extension methods indeed may help you achieve what you want.
In fact, Linq is implemented as a set of extension methods to IEnumerable

See
https://referencesource.microsoft.com/#System.Core/System/Linq/Enumerable.cs,577032c8811e20d3

for more info (and examples how to write extension methods).

Also you may want to read more about extension method in their formal msdn page
https://msdn.microsoft.com/en-us/library/bb383977.aspx


问:
Object with longer field is returned against an object with a short field
Let's say that we have an index with two objects:

```<code>{
"name": "iPhone 6s Plus big screen, super fast, ultra responsive, blah blah"
}
</code>```

and:

```<code>{
"name" : "iPhone 6s Plus"
}
</code>```

Now, when i search for iPhone 6s Plus, it returns the first object which does not make sense, since the first object contains more words (or noise) than the second object for the given query. In other words, a term appearing in a short name field should carry more ranking points than the same term appearing in a long name field

Algolia uses a TF/IDF algorithm, which takes account of the Field-length norm, so the second object should have higher score than the first one.

So why does the first object has higher score than the second one? Is there any settings option that I am missing?

答: One option is to break up the value into two different attributes, one for just the product name and another for the description. Doing that also lets you prioritize the product name in your searchable attributes, which would lead to better relevance in most cases.</p>

Body:
Let's say that we have an index with two objects:

{
"name": "iPhone 6s Plus big screen, super fast, ultra responsive, blah blah"
}

and:

{
"name" : "iPhone 6s Plus"
}

Now, when i search for iPhone 6s Plus, it returns the first object which does not make sense, since the first object contains more words (or noise) than the second object for the given query. In other words, a term appearing in a short name field should carry more ranking points than the same term appearing in a long name field

Algolia uses a TF/IDF algorithm, which takes account of the Field-length norm, so the second object should have higher score than the first one.

So why does the first object has higher score than the second one? Is there any settings option that I am missing?


问:
How do you filter WHERE using a count?
Starting with this working query:

```<code>  MATCH (post:Post)<-[:AUTHOR]-(author:User)
  WHERE post.createdAt > { hotAfter } AND post.text =~ { keyword }
  MATCH (post)-[:HAS_COMMENT]->(comment:Comment)<-[:AUTHOR]-(commentAuthor:User)
  WITH post, author, count(DISTINCT commentAuthor) as participantsCount, count(comment) as commentsCount
  ORDER BY (participantsCount * commentsCount) DESC
  RETURN collect(post {.*, author, participantsCount, commentsCount})[0..{ LIMIT }] as posts
</code>```

I'd additionally like to filter the posts with number of comments that fit the criteria:

```<code>WHERE (count(DISTINCT commentAuthor) * count(comment)) <= { someNumber }
</code>```

But I am not sure where/how to apply this logic e.g. this is incorrect:

```<code>  MATCH (post:Post)<-[:AUTHOR]-(author:User)
  WHERE post.createdAt > { hotAfter } AND post.text =~ { keyword }
  MATCH (post)-[:HAS_COMMENT]->(comment:Comment)<-[:AUTHOR]-(commentAuthor:User)
  WHERE count(DISTINCT commentAuthor) * count(comment) <= 10
  WITH post, author, count(DISTINCT commentAuthor) as participantsCount, count(comment) as commentsCount
  ORDER BY (participantsCount * commentsCount) DESC
  RETURN collect(post {.*, author, participantsCount, commentsCount})[0..{ LIMIT }] as posts
</code>```

答:
You can add this as a WHERE clause before you do your ORDER BY:</p>

```<code>MATCH (post:Post)<-[:AUTHOR]-(author:User)
WHERE post.createdAt > { hotAfter } AND post.text =~ { keyword }
MATCH (post)-[:HAS_COMMENT]->(comment:Comment)<-[:AUTHOR]-(commentAuthor:User)
WITH post, author, count(DISTINCT commentAuthor) as participantsCount, count(comment) as commentsCount
WITH post, author, participantsCount, commentsCount, participantsCount * commentsCount as countProduct
ORDER BY countProduct DESC
WHERE countProduct <= { someNumber }
RETURN collect(post {.*, author, participantsCount, commentsCount})[0..{ LIMIT }]
</code>```

Title: How do you filter WHERE using a count?

Body:
Starting with this working query:

  MATCH (post:Post)<-[:AUTHOR]-(author:User)
  WHERE post.createdAt > { hotAfter } AND post.text =~ { keyword }
  MATCH (post)-[:HAS_COMMENT]->(comment:Comment)<-[:AUTHOR]-(commentAuthor:User)
  WITH post, author, count(DISTINCT commentAuthor) as participantsCount, count(comment) as commentsCount
  ORDER BY (participantsCount * commentsCount) DESC
  RETURN collect(post {.*, author, participantsCount, commentsCount})[0..{ LIMIT }] as posts

I'd additionally like to filter the posts with number of comments that fit the criteria:

WHERE (count(DISTINCT commentAuthor) * count(comment)) <= { someNumber }

But I am not sure where/how to apply this logic e.g. this is incorrect:

  MATCH (post:Post)<-[:AUTHOR]-(author:User)
  WHERE post.createdAt > { hotAfter } AND post.text =~ { keyword }
  MATCH (post)-[:HAS_COMMENT]->(comment:Comment)<-[:AUTHOR]-(commentAuthor:User)
  WHERE count(DISTINCT commentAuthor) * count(comment) <= 10
  WITH post, author, count(DISTINCT commentAuthor) as participantsCount, count(comment) as commentsCount
  ORDER BY (participantsCount * commentsCount) DESC
  RETURN collect(post {.*, author, participantsCount, commentsCount})[0..{ LIMIT }] as posts

Body:
You can add this as a WHERE clause before you do your ORDER BY:

MATCH (post:Post)<-[:AUTHOR]-(author:User)
WHERE post.createdAt > { hotAfter } AND post.text =~ { keyword }
MATCH (post)-[:HAS_COMMENT]->(comment:Comment)<-[:AUTHOR]-(commentAuthor:User)
WITH post, author, count(DISTINCT commentAuthor) as participantsCount, count(comment) as commentsCount
WITH post, author, participantsCount, commentsCount, participantsCount * commentsCount as countProduct
ORDER BY countProduct DESC
WHERE countProduct <= { someNumber }
RETURN collect(post {.*, author, participantsCount, commentsCount})[0..{ LIMIT }]


问:
Create a folder and sub folder in Excel VBA
I have a pull down menu of companies that is populated by a list on another sheet. Three columns, Company, Job #, and Part Number.

When a job is created I need a folder for said company and a sub-folder for said Part Number.

If you go down the path it would look like:

C:\Images\Company Name\Part Number\

If either company name or Part number exists don't create, or overwrite the old one. Just go to next step. So if both folders exist nothing happens, if one or both don't exist create as required.

Another question is there a way to make it so it works on Macs and PCs the same?

答:
```<code>Sub MakeAllPath(ByVal PS$)
    Dim PP$
    If PS <> "" Then
        ' chop any end  name
        PP = Left(PS, InStrRev(PS, "\") - 1)
        ' if not there so build it
        If Dir(PP, vbDirectory) = "" Then
            MakeAllPath Left(PP, InStrRev(PS, "\") - 1)
            ' if not back to drive then  build on what is there
            If Right(PP, 1) <> ":" Then MkDir PP
        End If
    End If
End Sub

'Martins loop version above is better than MY recursive version
'so improve to below

Sub MakeAllDir(PathS$)

  ' format "K:\firstfold\secf\fold3"

  If Dir(PathS) = vbNullString Then

 ' else do not bother

   Dim LI&, MYPath$, BuildPath$, PathStrArray$()

   PathStrArray = Split(PathS, "\")

      BuildPath = PathStrArray(0) & "\"    '

      If Dir(BuildPath) = vbNullString Then

' trap problem of no drive :\  path given

         If vbYes = MsgBox(PathStrArray(0) & "< not there for >" & PathS & " try to append to " & CurDir, vbYesNo) Then
            BuildPath = CurDir & "\"
         Else
            Exit Sub
         End If
      End If
      '
      ' loop through required folders
      '
      For LI = 1 To UBound(PathStrArray)
         BuildPath = BuildPath & PathStrArray(LI) & "\"
         If Dir(BuildPath, vbDirectory) = vbNullString Then MkDir BuildPath
      Next LI
   End If

 ' was already there

End Sub

' use like
'MakeAllDir "K:\bil\joan\Johno"

'MakeAllDir "K:\bil\joan\Fredso"

'MakeAllDir "K:\bil\tom\wattom"

'MakeAllDir "K:\bil\herb\watherb"

'MakeAllDir "K:\bil\herb\Jim"

'MakeAllDir "bil\joan\wat" ' default drive
</code>```


问:
EF Core 1.1 to WebApi Core - Add-Migration fails
I think I’ve got all my dependencies running 1.1 properly but when I try to follow the steps here https://learn.microsoft.com/en-us/ef/core/get-started/aspnetcore/new-db I get an error running the Add-Migration command.

PM> Add-Migration InitialState

An error occurred while calling method ‘ConfigureServices’ on startup class ‘Startup’.

Consider using IDbContextFactory to override the initialization of the
DbContext at design-time. Error: This method could not find a user
secret ID because the application’s entry assembly is not set. Try
using the “.AddUserSecrets(Assembly assembly)” method instead.  No
parameterless constructor was found on ‘ApplicationDbContext’. Either
add a parameterless constructor to ‘ApplicationDbContext’ or add an
implementation of ‘IDbContextFactory’ in the same assembly as
‘ApplicationDbContext’.

relevant sections of my project.json:
…

```<code> “Microsoft.EntityFrameworkCore”: “1.1.0”,
“Microsoft.EntityFrameworkCore.SqlServer”: “1.1.0”,
“Microsoft.EntityFrameworkCore.Design”: {
“type “: “build”,
“version”: “1.1.0”
},
“Microsoft.EntityFrameworkCore.Tools”: “1.1.0-preview4-final”
},

“tools”: {
“Microsoft.EntityFrameworkCore.Tools.DotNet”: “1.1.0-preview4-final”
},
</code>```

My ApplicationDbContext does have the constructor:

```<code>public ApplicationDbContext(DbContextOptions options) : base(options)
 { }
</code>```

and my Startup.cs does have the:

```<code>services.AddDbContext(options => options.UseSqlServer(Configuration.GetConnectionString(“DefaultConnection”)));
</code>```

What else can it be?

答:
An alternate solution:

I ran into the same problem and landed here. But I am writing an app from scratch comparing it at every step with the DotNetCore WebApp with Individual auth. that gets generated via wizard in VS 2017 hoping to follow latest practices. So it was strange when everything was identical in my code and the generated code and I was getting this exception. The generated code did not have Michael Dennis's suggested code in startup.cs, which does not mean he is wrong, it just means there was now a different way. Upon diving down further I found out that UserSecretsId was declared in myprojetname.csproj like follows:

```<code><PropertyGroup>
    <UserSecretsId>aspnet-mywebproect-006a401f-2fdc-4aad-abb1-12c00000004a</UserSecretsId>
</PropertyGroup>
</code>```

After adding the entry in my project.csproj file, the issue was resolved.

Body:
I think I’ve got all my dependencies running 1.1 properly but when I try to follow the steps here https://learn.microsoft.com/en-us/ef/core/get-started/aspnetcore/new-db I get an error running the Add-Migration command.

PM> Add-Migration InitialState

An error occurred while calling method ‘ConfigureServices’ on startup class ‘Startup’.

Consider using IDbContextFactory to override the initialization of the
DbContext at design-time. Error: This method could not find a user
secret ID because the application’s entry assembly is not set. Try
using the “.AddUserSecrets(Assembly assembly)” method instead.  No
parameterless constructor was found on ‘ApplicationDbContext’. Either
add a parameterless constructor to ‘ApplicationDbContext’ or add an
implementation of ‘IDbContextFactory’ in the same assembly as
‘ApplicationDbContext’.

relevant sections of my project.json:
…

 “Microsoft.EntityFrameworkCore”: “1.1.0”,
“Microsoft.EntityFrameworkCore.SqlServer”: “1.1.0”,
“Microsoft.EntityFrameworkCore.Design”: {
“type “: “build”,
“version”: “1.1.0”
},
“Microsoft.EntityFrameworkCore.Tools”: “1.1.0-preview4-final”
},

“tools”: {
“Microsoft.EntityFrameworkCore.Tools.DotNet”: “1.1.0-preview4-final”
},

My ApplicationDbContext does have the constructor:

public ApplicationDbContext(DbContextOptions options) : base(options)
 { }

and my Startup.cs does have the:

services.AddDbContext(options => options.UseSqlServer(Configuration.GetConnectionString(“DefaultConnection”)));

What else can it be?

Body:
An alternate solution:

I ran into the same problem and landed here. But I am writing an app from scratch comparing it at every step with the DotNetCore WebApp with Individual auth. that gets generated via wizard in VS 2017 hoping to follow latest practices. So it was strange when everything was identical in my code and the generated code and I was getting this exception. The generated code did not have Michael Dennis's suggested code in startup.cs, which does not mean he is wrong, it just means there was now a different way. Upon diving down further I found out that UserSecretsId was declared in myprojetname.csproj like follows:

<PropertyGroup>
    <UserSecretsId>aspnet-mywebproect-006a401f-2fdc-4aad-abb1-12c00000004a</UserSecretsId>
</PropertyGroup>

After adding the entry in my project.csproj file, the issue was resolved.


问:
Fold/unfold div in table?
A few days ago, I asked a question regarding folding div ([link text][fold-unfold div]). The answers I got allowed me to make good progress in my coding effort. However, my requirements have changed.

Being a newbie with all this web stuff, I though that wrapping the divs with a table and table headers would be easy. Boy, was I wrong.

```<code><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title>Animate my Div</title>
<style type="text/css" media="screen">
a            {text-decoration: none; color: black; }
#expand      {background-color: #fff;}
.description {display: none;         }
.entry       {margin: 0; padding: 0px;}
</style>
<script src="jquery-1.3.2.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".entry a").click(function() {
    $(this).parents('.entry').find('.description').slideToggle(1000);
});
});
</script>
</head>
<body>
<?php
$con = mysql_connect("korg", "joe", "bob");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("wfr11", $con);
$result = mysql_query("
select title,description from webcases");
?>
<table border="1">
<thead>
<tr>
<th>title</th>
</tr>
</thead>
<?php
while ($row = mysql_fetch_array($result)) {
?><div class="entry"><tr>
<td>
<a href="#expand"><?php echo htmlentities($row['title']); ?></a>
<div class="description"><?php echo htmlentities($row['description']); ?></div>
</td>
</tr></div>
<?php
}
mysql_close($con);
?>
</table>
</body>
</html>
</code>```

Now, a click on a ticket title does not work. I remove all the code for the table, it works fine: click on a title and the description unfolds

I should be able to fold my div (expand & description) into my table, right? What am I missing?

答:
Chris, have a look here: http://jsfiddle.net/neopreneur/kdFHP/

Your HTML needs to look like this:

```<code><table border="1">
    <thead>
        <tr>
            <th>title</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td class="entry">
                <a href="#expand">Title Text (click here)</a>
                <div class="description">Description Text</div>
            </td>
        </tr>
    </tbody>
</table>
</code>```

Title: Fold/unfold div in table?

Body:
A few days ago, I asked a question regarding folding div ([link text][fold-unfold div]). The answers I got allowed me to make good progress in my coding effort. However, my requirements have changed.

Being a newbie with all this web stuff, I though that wrapping the divs with a table and table headers would be easy. Boy, was I wrong.

<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title>Animate my Div</title>

<?php
$con = mysql_connect("korg", "joe", "bob");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("wfr11", $con);
$result = mysql_query("
select title,description from webcases");
?>

title

<?php
while ($row = mysql_fetch_array($result)) {
?>

<?php echo htmlentities($row['title']); ?>

<?php echo htmlentities($row['description']); ?>

<?php
}
mysql_close($con);
?>

Now, a click on a ticket title does not work. I remove all the code for the table, it works fine: click on a title and the description unfolds

I should be able to fold my div (expand & description) into my table, right? What am I missing?

Body:
Chris, have a look here: http://jsfiddle.net/neopreneur/kdFHP/

Your HTML needs to look like this:

<table border="1">
    <thead>
        <tr>
            <th>title</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td class="entry">
                <a href="#expand">Title Text (click here)</a>
                <div class="description">Description Text</div>
            </td>
        </tr>
    </tbody>
</table>


问:
Protocol not firing
My protocol is not firing at all, and I am conforming it to the method that I want it to trigger. Any help would be well appreciated!</p>

```<code>public class NoteCardView:UIView {
@IBInspectable var delegate: NoteCardViewDelegate?

 func handleTitleLabelTap(_ recognizer:UITapGestureRecognizer) {
    // Verified this function is being called and has the right value!
self.delegate?.noteCardViewTitleLabelDidRecieveTap(MainViewController.NoteCardArray[Int(recognizer.view!.tag)])
 }
}

public protocol NoteCardViewDelegate {
// This should be being fired..
func noteCardViewTitleLabelDidRecieveTap(_ view: NoteCardView!)
}

extension MainViewController: NoteCardViewDelegate {
// this is what the handleTitleLabelTap function should do!
func noteCardViewTitleLabelDidRecieveTap(_ view: NoteCardView!) {
    print("6")
    let card:NoteCardView = (view)
    UIView.animate(withDuration: 0.5, delay: 0.0, options: UIViewAnimationOptions.curveEaseInOut, animations: {

        card.contentView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: (self.elementPlacement / 4) + 20)

        card.contentView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 100)

    }, completion: { (finished: Bool) in

        self.elementPlacement = (self.elementPlacement + 1)
        card.titleLabelTapGestureRecognizer!.isEnabled = !(self.elementPlacement == 5)
    })
}
}
</code>```

答:
This line:

self.delegate?.noteCardViewTitleLabelDidRecieveTap(MainViewController.NoteCardArray[Int(recognizer.view!.tag)])

...won't do anything if self.delegate is nil. The "?" tells the compiler to check for nil and stop if is nil.

I suggest adding a print statement:

   print("About to call delegate. delegate = \(delegate)")
delegate?.noteCardViewTitleLabelDidRecieveTap(MainViewController.NoteCardArray[Int(recognizer.view!.tag)])

BTW, self is unneeded and you should omit it. The only time you usually need to specify self is in a closure, where the compiler insists that you include it in order to "make the capture semantics explicit." My advice is to leave it out unless the compiler complains.

Also note that it doesn't really make sense to say "my protocol isn't firing." A protocol is an agreed-upon set of methods/properties. It's like a lingo used to communicate between objects that understand the protocol. It would be better to say "my delegate method isn't getting invoked."

Title: Protocol not firing

Body:
My protocol is not firing at all, and I am conforming it to the method that I want it to trigger. Any help would be well appreciated!

public class NoteCardView:UIView {
@IBInspectable var delegate: NoteCardViewDelegate?

 func handleTitleLabelTap(_ recognizer:UITapGestureRecognizer) {
    // Verified this function is being called and has the right value!
self.delegate?.noteCardViewTitleLabelDidRecieveTap(MainViewController.NoteCardArray[Int(recognizer.view!.tag)])
 }
}

public protocol NoteCardViewDelegate {
// This should be being fired..
func noteCardViewTitleLabelDidRecieveTap(_ view: NoteCardView!)
}

extension MainViewController: NoteCardViewDelegate {
// this is what the handleTitleLabelTap function should do!
func noteCardViewTitleLabelDidRecieveTap(_ view: NoteCardView!) {
    print("6")
    let card:NoteCardView = (view)
    UIView.animate(withDuration: 0.5, delay: 0.0, options: UIViewAnimationOptions.curveEaseInOut, animations: {

        card.contentView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: (self.elementPlacement / 4) + 20)

        card.contentView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 100)

    }, completion: { (finished: Bool) in

        self.elementPlacement = (self.elementPlacement + 1)
        card.titleLabelTapGestureRecognizer!.isEnabled = !(self.elementPlacement == 5)
    })
}
}