问:
How to genericly construct objects from data fetched from database
I have a database with multiple tables and corresponding objects for the table's data. For (almost) all tables I have a Model class, which handle the interaction with it's corresponding table (adding records, fetching data and instantiate an object holding the data.

All Model classes have a getById(int id) method, so I thought it would be nice to put it in a superclass (CoreModel).

But here the thing:
Since the Model classes are just a sort of interaction layers, I see no use in creating an instance of it. So I thought I make the class final and it's methods static, but then the problem arises that super() methods cannot be called from static methods.

My question: How is this usually done? I'm sorta new to OOP and am pretty baffled by the whole polymorphism thing. Are there any design patterns or standard solutions to solve this problem in a generic way?

Example code:

```<code>public final class CoreModel {

public static ResultSet getById(int id, String table){
    Statement stat = null;
    ResultSet res = null;

    try {
        stat = DatabaseModel.getStatement();
        res = stat.executeQuery("SELECT * FROM `"+table+"` WHERE `id` = " +id);

        res.next();

        stat.close();
        res.close();

    } catch (SQLException ex) {
        // handle any errors
        System.out.println("SQLException: " + ex.getMessage());
        System.out.println("SQLState: " + ex.getSQLState());
        System.out.println("VendorError: " + ex.getErrorCode());
        }
    return res;
    }
}

public final class PersonModel extends CoreModel {

public static Person getById(int id) {
    ResultSet personResult = super.getById(id, "person");
    // instatiate Person object
    return personObj;
    }
}
</code>```

答:
What you are asking is called ORM. There are couple of design pattern for creating an ORM you can read about DataMapper or ActiveRecord to understand the concept better.

According to your code get only an Id and generating an object is not enough. you need to have a distinguishable Id so the super class can differ from different object.

One way to create a super class for create different object is Factory design pattern.

Something similar to following code :

```<code>//Character Class
public class Character implements Model {
    public String age;
    }
//Person Class
public class Person implements Model {
    public String name;
}
//Model
public interface Model {
}
//CoreModel
public class CoreModel {

    public static <T extends Model> T getById( int id) throws Exception {
        int idType = id % 10; // the id has to be distinguishable
        // get data from DB
        switch (idType) {
            case 0:

                Person person = new Person();
                person.name = "test";
                return (T) Person.class.cast(person);
            case 1:
                Character character = new Character();
                character.age = "100";
                return (T) Character.class.cast(character);
            default:
                throw new Exception("Type Not Found");
        }
    }
}
//Main Class
public class Main {
    public static void main(String[] args) {

        try {
            Person p = CoreModel.getById(100);
            Character c = CoreModel.getById(101);
            System.out.println(p.name);
            System.out.println(c.age);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
</code>```

Body:
I have a database with multiple tables and corresponding objects for the table's data. For (almost) all tables I have a Model class, which handle the interaction with it's corresponding table (adding records, fetching data and instantiate an object holding the data.

All Model classes have a getById(int id) method, so I thought it would be nice to put it in a superclass (CoreModel).

But here the thing:
Since the Model classes are just a sort of interaction layers, I see no use in creating an instance of it. So I thought I make the class final and it's methods static, but then the problem arises that super() methods cannot be called from static methods.

My question: How is this usually done? I'm sorta new to OOP and am pretty baffled by the whole polymorphism thing. Are there any design patterns or standard solutions to solve this problem in a generic way?

Example code:

public final class CoreModel {

public static ResultSet getById(int id, String table){
    Statement stat = null;
    ResultSet res = null;

    try {
        stat = DatabaseModel.getStatement();
        res = stat.executeQuery("SELECT * FROM `"+table+"` WHERE `id` = " +id);

        res.next();

        stat.close();
        res.close();

    } catch (SQLException ex) {
        // handle any errors
        System.out.println("SQLException: " + ex.getMessage());
        System.out.println("SQLState: " + ex.getSQLState());
        System.out.println("VendorError: " + ex.getErrorCode());
        }
    return res;
    }
}

public final class PersonModel extends CoreModel {

public static Person getById(int id) {
    ResultSet personResult = super.getById(id, "person");
    // instatiate Person object
    return personObj;
    }
}

Body:
What you are asking is called ORM. There are couple of design pattern for creating an ORM you can read about DataMapper or ActiveRecord to understand the concept better.

According to your code get only an Id and generating an object is not enough. you need to have a distinguishable Id so the super class can differ from different object.

One way to create a super class for create different object is Factory design pattern.

Something similar to following code :

//Character Class
public class Character implements Model {
    public String age;
    }
//Person Class
public class Person implements Model {
    public String name;
}
//Model
public interface Model {
}
//CoreModel
public class CoreModel {

    public static <T extends Model> T getById( int id) throws Exception {
        int idType = id % 10; // the id has to be distinguishable
        // get data from DB
        switch (idType) {
            case 0:

                Person person = new Person();
                person.name = "test";
                return (T) Person.class.cast(person);
            case 1:
                Character character = new Character();
                character.age = "100";
                return (T) Character.class.cast(character);
            default:
                throw new Exception("Type Not Found");
        }
    }
}
//Main Class
public class Main {
    public static void main(String[] args) {

        try {
            Person p = CoreModel.getById(100);
            Character c = CoreModel.getById(101);
            System.out.println(p.name);
            System.out.println(c.age);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


来源: stackexchange

问:
Is there a way to specify default values for null in Lodash or Underscore?
I know the _.defaults function works to put default values for an object with keys that are undefined. However it doesn't work with keys that are null. Is there way to achieve this?

答:
The reason behind this behavior for the _.defaults helper is that undefined means a property hasn't been set and null conveys the meaning of being explicitly set to refer to nothing.

If you still think your variables should hold null and be set with a function, then you can use _.defaultTo, a function that returns its first argument normally and its second if the first one was NaN, null or undefined. You'll need to make it loop over all the object's keys yourself though.

```<code>_.forOwn(myObject, function (value, key) {
  myObject[key] = _.defaultTo(value, defaultValues[key]);
});
</code>```

However, this won't set values for variables that are not even defined on the original element, since we're looping through its own properties. Plus it's not very efficient. If that's what you wanted, might as well loop on the defaults instead:

```<code>_.forOwn(defaultValues, function (value, key) {
  if (myObject[key] === undefined || myObject[key] === null)
    myObject[key] = value;
});
</code>```

function getSampleObject() {
  return {
    a: null,
    b: NaN,
    // c: undefined,
    d: undefined,
    e: 'original'
}};

var defaultValues = {
  a: 1,
  b: 2,
  c: 3,
  d: 4,
  e: 5
};

var myObject = getSampleObject();
_.forOwn(myObject, function (value, key) {
  myObject[key] = _.defaultTo(value, defaultValues[key]);
});

console.log('defaultTo', myObject);

var myObject = getSampleObject();
_.defaults(myObject, defaultValues);

console.log('defaults', myObject);

var myObject = getSampleObject();
_.forOwn(defaultValues, function (value, key) {
  if (myObject[key] === undefined || myObject[key] === null)
    myObject[key] = value;
});

console.log('handmade', myObject);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script></code>```

ContentLicense: CC BY-SA 3.0

Body:
The reason behind this behavior for the _.defaults helper is that undefined means a property hasn't been set and null conveys the meaning of being explicitly set to refer to nothing.

If you still think your variables should hold null and be set with a function, then you can use _.defaultTo, a function that returns its first argument normally and its second if the first one was NaN, null or undefined. You'll need to make it loop over all the object's keys yourself though.

_.forOwn(myObject, function (value, key) {
  myObject[key] = _.defaultTo(value, defaultValues[key]);
});

However, this won't set values for variables that are not even defined on the original element, since we're looping through its own properties. Plus it's not very efficient. If that's what you wanted, might as well loop on the defaults instead:

_.forOwn(defaultValues, function (value, key) {
  if (myObject[key] === undefined || myObject[key] === null)
    myObject[key] = value;
});

function getSampleObject() {
  return {
    a: null,
    b: NaN,
    // c: undefined,
    d: undefined,
    e: 'original'
}};

var defaultValues = {
  a: 1,
  b: 2,
  c: 3,
  d: 4,
  e: 5
};

var myObject = getSampleObject();
_.forOwn(myObject, function (value, key) {
  myObject[key] = _.defaultTo(value, defaultValues[key]);
});

console.log('defaultTo', myObject);

var myObject = getSampleObject();
_.defaults(myObject, defaultValues);

console.log('defaults', myObject);

var myObject = getSampleObject();
_.forOwn(defaultValues, function (value, key) {
  if (myObject[key] === undefined || myObject[key] === null)
    myObject[key] = value;
});

console.log('handmade', myObject);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>


问:
Logged in users still see login page (django auth)
I'm using django.contrib.auth to handle user authentication in my django project. In order to log in, I have

```<code>from django.contrib.auth.views import login, logout

# ...

url(r'^login/', login, name='login'),
url(r'^logout/', logout, {'next_page': '/'}, name='logout'),
</code>```

in my main project's urls.py.

So far, so good. However, I notice that after logging in, if I access /login/, I still see the login page, and am able to log in as another user. This seems like counter-intuitive behavior -- most websites will either show an error or redirect you to the homepage if you attempt to access the login page while logged in.

I'm using the builtin models / views, and so as far as I know I have no easy way of altering the views. Is there a simple way of gaining this functionality (i.e. preventing access to the login form if logged in), or is the best way simply to modify the template to only show the form if not logged in?

答:
Possible solution:
I create 'my_login':

```<code>def my_login(request):
    if request.user.is_authenticated():
        return redirect(#...home)
    else:
        return login(request, 'template/login.html') # here i used login built-in function
                                                     # instead of using directly in urls.py
</code>```

And i used my_login view in urls.py instead of 'django.contrib.auth.views.login'

EDIT

```<code>New in Django 1.10:
The redirect_authenticated_user parameter was added.
</code>```

Check https://docs.djangoproject.com/en/1.10/topics/auth/default/#django.contrib.auth.views.login

Body:
I'm using django.contrib.auth to handle user authentication in my django project. In order to log in, I have

from django.contrib.auth.views import login, logout

# ...

url(r'^login/', login, name='login'),
url(r'^logout/', logout, {'next_page': '/'}, name='logout'),

in my main project's urls.py.

So far, so good. However, I notice that after logging in, if I access /login/, I still see the login page, and am able to log in as another user. This seems like counter-intuitive behavior -- most websites will either show an error or redirect you to the homepage if you attempt to access the login page while logged in.

I'm using the builtin models / views, and so as far as I know I have no easy way of altering the views. Is there a simple way of gaining this functionality (i.e. preventing access to the login form if logged in), or is the best way simply to modify the template to only show the form if not logged in?

Body:
Possible solution:
I create 'my_login':

def my_login(request):
    if request.user.is_authenticated():
        return redirect(#...home)
    else:
        return login(request, 'template/login.html') # here i used login built-in function
                                                     # instead of using directly in urls.py

And i used my_login view in urls.py instead of 'django.contrib.auth.views.login'

EDIT

New in Django 1.10:
The redirect_authenticated_user parameter was added.

Check https://docs.djangoproject.com/en/1.10/topics/auth/default/#django.contrib.auth.views.login


问:
Knockout fallback view
Durandal, RequireJS, KnockoutJS

I have a generic and a client specific view in my project.

```<code>│   faq.html
│   welcome.html
│   shell.html
│
├───Client1
│     faq.html
│
├───Client2
│     faq.html
│     welcome.html
</code>```

I want to show the client specific view if it exists or else show the default view.

Something like this.

```<code><div>
   <div data-bind="compose: { view:'views/Client1/faq.html', fallbackView: 'view/faq.html' }"></div>
</div>
</code>```

答:
I think you're better off handling this in your view-model than in your view. Durandal lets you use an observable property for its compose binding so you can do something like this:

```<code><div>
   <div data-bind="compose: { view: currentView }"></div>
</div>
</code>```

...

```<code>viewModel = function(){
    var self = this;
    self.currentView = ko.observable();

    self.loadView = require(['text!views/Client1/faq.html', 'text!view/faq.html'], function(clientView, defaultView) {
        if(clientView) {
            self.currentView('views/Client1/faq.html');
        } else {
            self.currentView('view/faq.html');
        }
    });

}
</code>```

Trying to load the view path twice seems a bit redundant of course but if you don't have any other way to know if the view exists or not then it might be your best bet.

Title: Knockout fallback view

Body:
Durandal, RequireJS, KnockoutJS

I have a generic and a client specific view in my project.

│   faq.html
│   welcome.html
│   shell.html
│
├───Client1
│     faq.html
│
├───Client2
│     faq.html
│     welcome.html

I want to show the client specific view if it exists or else show the default view.

Something like this.

Body:
I think you're better off handling this in your view-model than in your view. Durandal lets you use an observable property for its compose binding so you can do something like this:

<div>
   <div data-bind="compose: { view: currentView }"></div>
</div>

...

viewModel = function(){
    var self = this;
    self.currentView = ko.observable();

    self.loadView = require(['text!views/Client1/faq.html', 'text!view/faq.html'], function(clientView, defaultView) {
        if(clientView) {
            self.currentView('views/Client1/faq.html');
        } else {
            self.currentView('view/faq.html');
        }
    });

}

Trying to load the view path twice seems a bit redundant of course but if you don't have any other way to know if the view exists or not then it might be your best bet.


问:
How to detect duplicate words in a list and count them in a specific way
I've been learning python 3 for about 1 week now and I just can't find a way to do this, so here is my question.

I have this list:

```<code>['apple', 'banana', 'apple', 'tomato', 'carrot', 'apple', 'banana']
</code>```

Now I want to detect the duplicated words, count them, put the result in front of the word and print in a single string like this example:

Apple 3, Banana 2, tomato, carrot

Order doesn't matter.

答:
```<code>arr = ['apple', 'banana', 'apple', 'tomato', 'carrot', 'apple', 'banana']

', '.join(x + ' ' + str(arr.count(x)) for x in set(arr))
</code>```

Returns this:

```<code>'banana 2, carrot 1, apple 3, tomato 1'
</code>```

If you want to exclude 1s:

```<code>', '.join(x + (' ' + str(arr.count(x)) if arr.count(x) > 1 else '') for x in set(arr))
</code>```

Which produces:

```<code>'banana 2, carrot, apple 3, tomato'
</code>```

An explanation:

This is what you would call a "comprehension." All I'm doing is iterating through each distinct element in arr (i.e. iterating through the set of unique elements in arr) and counting the number of times each one occurs in arr using arr.count(x) for each x in set(arr). Everything else is just a way of getting your final string result in one line.

You also might be interested in collections.Counter, which effectively returns a dictionary of element: count pairs and makes it easy to quickly find the number of times a given element x occurs in your list. :

```<code>>>> collections.Counter(arr)
Counter({'apple': 3, 'banana': 2, 'carrot': 1, 'tomato': 1})
</code>```

Body:
I've been learning python 3 for about 1 week now and I just can't find a way to do this, so here is my question.

I have this list:

['apple', 'banana', 'apple', 'tomato', 'carrot', 'apple', 'banana']

Now I want to detect the duplicated words, count them, put the result in front of the word and print in a single string like this example:

Apple 3, Banana 2, tomato, carrot

Order doesn't matter.

Body:
arr = ['apple', 'banana', 'apple', 'tomato', 'carrot', 'apple', 'banana']

', '.join(x + ' ' + str(arr.count(x)) for x in set(arr))

Returns this:

'banana 2, carrot 1, apple 3, tomato 1'

If you want to exclude 1s:

', '.join(x + (' ' + str(arr.count(x)) if arr.count(x) > 1 else '') for x in set(arr))

Which produces:

'banana 2, carrot, apple 3, tomato'

An explanation:

This is what you would call a "comprehension." All I'm doing is iterating through each distinct element in arr (i.e. iterating through the set of unique elements in arr) and counting the number of times each one occurs in arr using arr.count(x) for each x in set(arr). Everything else is just a way of getting your final string result in one line.

You also might be interested in collections.Counter, which effectively returns a dictionary of element: count pairs and makes it easy to quickly find the number of times a given element x occurs in your list. :

>>> collections.Counter(arr)
Counter({'apple': 3, 'banana': 2, 'carrot': 1, 'tomato': 1})


问:
How to get coordinates of a button in a browser?
I am looking for a way to get the coordinates of e.g. a button in a browser.
Thanks in advance. </p>

答:
To get the coordinates of a button in a browser, you need to first write a selector to get the particular button you're interested in finding the coordinates for.

```<code>var button = document.querySelector('button')
</code>```

To get the coordinate, it depends on if you want the coordinates in reference to some other element. If the coordinates were in reference to itself, then it would be as simple as

```<code>{left: 0, top: 0, bottom:  button.offsetHeight, right: button.offsetWidth}
</code>```

If you want to have it in reference to a different element like the window for instance, you can recursively traverse the button's parents until the window is reached

```<code>var top = button.offsetTop;
var left = button.offsetLeft;
var height = button.offsetHeight;
var width = button.offsetWidth;
while(button.offsetParent && button.offsetParent != window){
    button = button.offsetParent;
    top += button.offsetTop;
    left += button.offsetLeft;
}
var bottom = top + height;
var right = left + width;
return {left: left, top: top, bottom: bottom, right: right}
</code>```

Body:
To get the coordinates of a button in a browser, you need to first write a selector to get the particular button you're interested in finding the coordinates for.

var button = document.querySelector('button')

To get the coordinate, it depends on if you want the coordinates in reference to some other element. If the coordinates were in reference to itself, then it would be as simple as

{left: 0, top: 0, bottom:  button.offsetHeight, right: button.offsetWidth}

If you want to have it in reference to a different element like the window for instance, you can recursively traverse the button's parents until the window is reached

var top = button.offsetTop;
var left = button.offsetLeft;
var height = button.offsetHeight;
var width = button.offsetWidth;
while(button.offsetParent && button.offsetParent != window){
    button = button.offsetParent;
    top += button.offsetTop;
    left += button.offsetLeft;
}
var bottom = top + height;
var right = left + width;
return {left: left, top: top, bottom: bottom, right: right}


问:
Visual Studio messes up project settings
I've created an empty C++ project, added main.cpp, and set up build configurations. Particularly, I changed Output Directory and Intermediate Directory. Pushed everything to GitHub, and cloned it to the other computer. Opened solution, checked properties of the project to find out that it is now set back to default. Tried compiling, wrong directories are used. git status on both computers shows nothing. I also checked .vcxproj to find out that changed strings are present in the file.

What could be the cause of this behavior?

Repository: https://github.com/kirdaybov/experiments

My environment:

1st computer: VS Express 2015 update 1.

2nd computer: VS Community 2015 update 3.

答:
Some updates MIGHT change libraries directory. I had this moment when I changed from VS2015 to VS2017 and nothing worked anymore.

Also try to see the directories in the settings. A project could be on CPU1's desktop, but on CPU's 2 document folder. In other words, check project propreties.


问:
c# sql How to get row selected value?
I used datagrid to show sql table datagrid.

And I showed one column on datagrid from sql.

Now I want to determine that which rows is now open & what is that values.

Like this.

See what I want to do.

And I used this code to show datatable on my datagrid.

```<code>string ConString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(ConString))
{

    SqlCommand cmd = new SqlCommand("SELECT roll FROM cmt_7th WHERE name IS Null And department IS Null And phone IS Null", con);
    SqlDataAdapter sda = new SqlDataAdapter(cmd);
    DataTable dt = new DataTable("cmt_7th");
    sda.Fill(dt);
    MydataGrid_roll.ItemsSource = dt.DefaultView;

}
</code>```

And its show only row column. But I want to declare like my previous image.

答:
You can get the selected row value with this code:
string em = dataGridView1.CurrentRow.Cells[2].FormattedValue.ToString();
You store the value in a string called em like the above, you can change the name for sure, and then cell[] is like an array, it stores each intersection of a row and a column in there, so for instance if you have 3 columns and two rows, the first intersection of the row and column is of index 0 and so on and so forth.</p>

Title: c# sql How to get row selected value?

Body:
I used datagrid to show sql table datagrid.

And I showed one column on datagrid from sql.

Now I want to determine that which rows is now open & what is that values.

Like this.

See what I want to do.

And I used this code to show datatable on my datagrid.

string ConString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(ConString))
{

    SqlCommand cmd = new SqlCommand("SELECT roll FROM cmt_7th WHERE name IS Null And department IS Null And phone IS Null", con);
    SqlDataAdapter sda = new SqlDataAdapter(cmd);
    DataTable dt = new DataTable("cmt_7th");
    sda.Fill(dt);
    MydataGrid_roll.ItemsSource = dt.DefaultView;

}

And its show only row column. But I want to declare like my previous image.


问:
Activity indicator view disappears when scroll down
I make an overlay on a button with a custom node LoadingIndicatorNode this button is placed in an ASCellNode when I scroll down and up UIActivityIndicatorView from LoadingIndicatorNode disappears.

Here is the code of LoadingIndicatorNode class

```<code>@implementation LoadingIndicatorNode
- (instancetype)init
{
    self = [super init];
    if (self) {
        [self setOpaque:NO];
        self.backgroundColor = [UIColor colorWithWhite:1 alpha:0.6];
        self.activityNode = [[ASDisplayNode alloc] initWithViewBlock:^UIView * _Nonnull{
            UIActivityIndicatorView *activity = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle: IPAD ? UIActivityIndicatorViewStyleWhiteLarge : UIActivityIndicatorViewStyleWhite];
            activity.color = [UIColor blackColor];
            activity.backgroundColor = [UIColor clearColor];
            [activity startAnimating];
            return activity;
        }];

        [self addSubnode:self.activityNode];
    }
    return self;
}

- (ASLayoutSpec *)layoutSpecThatFits:(ASSizeRange)constrainedSize {
    ASCenterLayoutSpec *centerSpec = [ASCenterLayoutSpec centerLayoutSpecWithCenteringOptions:ASCenterLayoutSpecCenteringXY sizingOptions:ASCenterLayoutSpecSizingOptionDefault child:self.activityNode];

    return [ASInsetLayoutSpec insetLayoutSpecWithInsets:UIEdgeInsetsMake(10, 0, 10, 0) child:centerSpec];
}

@end
</code>```

Here is some code showing how I use it

```<code>_loadingIndicator = [[LoadingIndicatorNode alloc] init];
_loadingIndicator.hidden = YES;
[self addSubnode:_loadingIndicator];

[[[[self.viewModel.memberStatusCommand executing] not]
     distinctUntilChanged]
     subscribeNext:^(NSNumber *x) {
         [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:!x.boolValue];
         _loadingIndicator.hidden = x.boolValue;
         [self updateViewModelData];
         [self setNeedsLayout];
     }];
</code>```

Overlay from layoutSpecThatFits: method

```<code>ASOverlayLayoutSpec *overlay = [ASOverlayLayoutSpec overlayLayoutSpecWithChild:_statusButton overlay:_loadingIndicator];
    overlay.style.flexBasis = ASDimensionMake(@"50%");
    overlay.style.alignSelf = ASStackLayoutAlignSelfStretch;
    overlay.style.flexShrink = 1;
    overlay.style.flexGrow = 1;
</code>```

答:
Just made a weak reference to UIActivityIndicatorView from LoadingIndicatorNode and implemented didEnterVisibleState method and called startAnimating

```<code>- (void)didEnterVisibleState {
    [super didEnterVisibleState];
    [self.activity startAnimating];
}
</code>```

Body:
I make an overlay on a button with a custom node LoadingIndicatorNode this button is placed in an ASCellNode when I scroll down and up UIActivityIndicatorView from LoadingIndicatorNode disappears.

Here is the code of LoadingIndicatorNode class

@implementation LoadingIndicatorNode
- (instancetype)init
{
    self = [super init];
    if (self) {
        [self setOpaque:NO];
        self.backgroundColor = [UIColor colorWithWhite:1 alpha:0.6];
        self.activityNode = [[ASDisplayNode alloc] initWithViewBlock:^UIView * _Nonnull{
            UIActivityIndicatorView *activity = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle: IPAD ? UIActivityIndicatorViewStyleWhiteLarge : UIActivityIndicatorViewStyleWhite];
            activity.color = [UIColor blackColor];
            activity.backgroundColor = [UIColor clearColor];
            [activity startAnimating];
            return activity;
        }];

        [self addSubnode:self.activityNode];
    }
    return self;
}

- (ASLayoutSpec *)layoutSpecThatFits:(ASSizeRange)constrainedSize {
    ASCenterLayoutSpec *centerSpec = [ASCenterLayoutSpec centerLayoutSpecWithCenteringOptions:ASCenterLayoutSpecCenteringXY sizingOptions:ASCenterLayoutSpecSizingOptionDefault child:self.activityNode];

    return [ASInsetLayoutSpec insetLayoutSpecWithInsets:UIEdgeInsetsMake(10, 0, 10, 0) child:centerSpec];
}

@end

Here is some code showing how I use it

_loadingIndicator = [[LoadingIndicatorNode alloc] init];
_loadingIndicator.hidden = YES;
[self addSubnode:_loadingIndicator];

[[[[self.viewModel.memberStatusCommand executing] not]
     distinctUntilChanged]
     subscribeNext:^(NSNumber *x) {
         [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:!x.boolValue];
         _loadingIndicator.hidden = x.boolValue;
         [self updateViewModelData];
         [self setNeedsLayout];
     }];

Overlay from layoutSpecThatFits: method

ASOverlayLayoutSpec *overlay = [ASOverlayLayoutSpec overlayLayoutSpecWithChild:_statusButton overlay:_loadingIndicator];
    overlay.style.flexBasis = ASDimensionMake(@"50%");
    overlay.style.alignSelf = ASStackLayoutAlignSelfStretch;
    overlay.style.flexShrink = 1;
    overlay.style.flexGrow = 1;

Body:
Just made a weak reference to UIActivityIndicatorView from LoadingIndicatorNode and implemented didEnterVisibleState method and called startAnimating

- (void)didEnterVisibleState {
    [super didEnterVisibleState];
    [self.activity startAnimating];
}


问:
How to remove extra space from winform webbrowser in C#
I have a C# winForm app that use webbrowser to load websites. All thing are good but with some websites I have extra space in left or right of webbrowser. I tested the link of site on all browsers like IE and Chrome in my windows but no one has this problem and just my app have this problem. help me to find the solution and remove space to fit my website to web browser. thnx</p>

答:
The WebBrowser control in WinForms use a legacy version of IE by default. (IE7)

That is most likely the cause of your issue, to solve it you would have to force the WebBrowser emulation to a higher version, IE11 for example, in the windows registry.

This is a piece of code I use to do so by detecting currently installed IE version and updating it in the registry:

```<code>                int BrowserVer, RegVal;

            // get the installed IE version
            using (WebBrowser Wb = new WebBrowser())
                BrowserVer = Wb.Version.Major;

            // set the appropriate IE version
            if (BrowserVer >= 11)
                RegVal = 11001;
            else if (BrowserVer == 10)
                RegVal = 10001;
            else if (BrowserVer == 9)
                RegVal = 9999;
            else if (BrowserVer == 8)
                RegVal = 8888;
            else
                RegVal = 7000;

            // set the actual key
            RegistryKey Key = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION", true);
            Key.SetValue(System.Diagnostics.Process.GetCurrentProcess().ProcessName + ".exe", RegVal, RegistryValueKind.DWord);
            Key.Close();
</code>```

Simply paste the code at the beggining of your application.
Furthermore, refer to this answer for extra details.

Disclaimer: The code is not originally mine, could not find a reference to it.

Body:
The WebBrowser control in WinForms use a legacy version of IE by default. (IE7)

That is most likely the cause of your issue, to solve it you would have to force the WebBrowser emulation to a higher version, IE11 for example, in the windows registry.

This is a piece of code I use to do so by detecting currently installed IE version and updating it in the registry:

                int BrowserVer, RegVal;

            // get the installed IE version
            using (WebBrowser Wb = new WebBrowser())
                BrowserVer = Wb.Version.Major;

            // set the appropriate IE version
            if (BrowserVer >= 11)
                RegVal = 11001;
            else if (BrowserVer == 10)
                RegVal = 10001;
            else if (BrowserVer == 9)
                RegVal = 9999;
            else if (BrowserVer == 8)
                RegVal = 8888;
            else
                RegVal = 7000;

            // set the actual key
            RegistryKey Key = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION", true);
            Key.SetValue(System.Diagnostics.Process.GetCurrentProcess().ProcessName + ".exe", RegVal, RegistryValueKind.DWord);
            Key.Close();

Simply paste the code at the beggining of your application.
Furthermore, refer to this answer for extra details.

Disclaimer: The code is not originally mine, could not find a reference to it.


问:
Big C# source file with Windows API method signatures, structures, constants: will they all be included in the final .exe?
I want to put all the signatures of Windows API functions I'm using in programs in one class, such as WinAPI, and in a file WinAPI.cs I will include in my projects. The class will be internal static and the methods public static extern. (Something like the huge NativeMethods.cs from the .NET Framework source code).

Let's say WinAPI.cs has one hundred native methods signatures like:

```<code>[DllImport("user32.dll")]
internal static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
</code>```

If I'm only going to use a few of them in a project (even one or two), if I include the WinAPI.cs file in my project, will the final .exe be filled with the unnecessary method declarations I'm not using (the other 99 or so)?

What about native structure declarations, If I'm not using them in the current project, will they still be included in the final .exe?

```<code>    [StructLayout(LayoutKind.Sequential)]
    public struct POINT
    {
        public int X;
        public int Y;
    }
</code>```

What about constants declarations or readonly members like:

```<code>public const int WH_JOURNALPLAYBACK = 1;
public static readonly int WM_GETTEXT = 0x0D;
</code>```

答: All of this will be included.  However, it will be included as IL and when the program runs it's just compiled machine code.  We're talking maybe 40K of space at most.

ContentLicense: CC BY-SA 2.5

Body:
I want to put all the signatures of Windows API functions I'm using in programs in one class, such as WinAPI, and in a file WinAPI.cs I will include in my projects. The class will be internal static and the methods public static extern. (Something like the huge NativeMethods.cs from the .NET Framework source code).

Let's say WinAPI.cs has one hundred native methods signatures like:

[DllImport("user32.dll")]
internal static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

If I'm only going to use a few of them in a project (even one or two), if I include the WinAPI.cs file in my project, will the final .exe be filled with the unnecessary method declarations I'm not using (the other 99 or so)?

What about native structure declarations, If I'm not using them in the current project, will they still be included in the final .exe?

    [StructLayout(LayoutKind.Sequential)]
    public struct POINT
    {
        public int X;
        public int Y;
    }

What about constants declarations or readonly members like:

public const int WH_JOURNALPLAYBACK = 1;
public static readonly int WM_GETTEXT = 0x0D;


问:
How to use objects list as gulp source stream
I know that gulp require a vinyl source stream to work properly, but is there an easy way to use an already existant vinyl file or a json object instead of the well known gulp.src that only takes globs?</p>

答:
After several researches I did not found any good solution for that problem so I decided to share my solution with you.

That problem is solved in 2 steps

1: You need to convert what ever you want to pipe in gulp to a vinyl file.
This can be done like so

```<code>const Vinyl = require('vinyl');
var vinyl = new Vinyl();
vinyl.cwd = '/';
vinyl.base = '/';
vinyl.path = '/yourfictivefilepath';
vinyl.contents = new Buffer(JSON.stringify(yourobject));
</code>```

For more information about that step: https://github.com/gulpjs/vinyl

2: Create a stream out of your vinyl files

I found that those steps can be repetitive and can make code less readable so I decided to encapsulate those steps in an npm package that does this for you.

https://www.npmjs.com/package/gulp-to-stream

Body:
After several researches I did not found any good solution for that problem so I decided to share my solution with you.

That problem is solved in 2 steps

1: You need to convert what ever you want to pipe in gulp to a vinyl file.
This can be done like so

const Vinyl = require('vinyl');
var vinyl = new Vinyl();
vinyl.cwd = '/';
vinyl.base = '/';
vinyl.path = '/yourfictivefilepath';
vinyl.contents = new Buffer(JSON.stringify(yourobject));

For more information about that step: https://github.com/gulpjs/vinyl

2: Create a stream out of your vinyl files

I found that those steps can be repetitive and can make code less readable so I decided to encapsulate those steps in an npm package that does this for you.

https://www.npmjs.com/package/gulp-to-stream


问:
How I can running GUI application on Docker for Mac?
How I can running GUI application on Docker for Mac?

I want to running wireshark GUI on Ubuntu 16.10

I found docker forum about it, But I can't run GUI app based on content of forum.

Maybe information that in forum is outdated.

How I can run GUI app on Docker for Mac?

Note that I'm using following softwares

Host OS: macOS 10.12.4

Guest OS: Ubuntu 16.10

Docker: 17.03.1-ce-rc1-mac3

答:
How I can run GUI app on Docker for Mac?

you want a full virtual machine running Ubuntu, not a Docker container.

docker is intended to run "server" applications - things without a gui / ui; services that don't require interaction with a user.


问:
No executable found matching command dotnet-projectmodel-server
I'm getting this error when opening .NET Core projetcs in VS 2015 Community:

The following error ocurred attempting to run the project model server
  process (1.0.0-preview-003585).

Unable to start the process. No executable found matching command
  "dotnet-projectmodel-server".

It was working well until yesterday. I've already tried do reinstall the .NET Core SDK and repair the VS installation.

Some tips?

答:
I got the same error after installing .Net Core 1.0.1 (x64) on Visual Studio 2015 Enterprise following these steps:

Installed .Net Core SDK 1.0.1

Opened Visual Studio, Went to Tools, Extensions and Updates and saw there was an update for Asp.Net and Web Tools which I chose to to install

I tried to fix it by uninstalling and re-installing the latest version of .Net Core SDK but that didn't solve my problem. I kept getting the error:

In my case, I was trying to create a new project using a custom template, so I changed and tried to create a new Asp.Net Core Web Application (.Net Framework) and I got an error that told me exactly what version of the .Net Core SDK I needed:

I followed the link from the dialog (click here or go here: https://github.com/aspnet/Tooling/blob/master/known-issues-vs2015.md#missing-sdk) and downloaded the specific version. I Uninstalled the current .Net Core SDK (1.0.1 x64), then installed the suggested one (1.0.0-preview2-003131 in my case) and that fixed my problem.


问:
macrodef'd <jar> task not behaving like an implicit fileset?
Using standard Ant 1.9.7 to assemble a bunch of jar files.  We've made a macro to help cut down on the verbosity of the XML:

```<code><!-- All 'description' bits snipped for SO posting. -->
<macrodef name="buildjar">
  ... bunch of <attribute> ...
  <element name="also"/>
  <sequential>
    <jar ....>
      <manifest>  ...  </manifest>
      <fileset what="stuff in every jar file" />
      <fileset what="and this stuff too" />
      <mappedresources if:true="beauty">
        <fileset for when truth is beauty/>
        <globmapper from="ugly" to="beauty"/>
      </mappedresoruces>

      <!-- Anything else for this specific jar. -->
      <also/>

    </jar>
  </sequential>
</macrodef>
</code>```

This works:

```<code><buildjar .........>
  <also>
    <fileset file="/some/path/somewhere/a_single_file"/>
  </also>
</buildjar>
</code>```

But this does not:

```<code><buildjar .........>
  <also>
    <include name="/some/path/somewhere/a_single_file"/>
  </also>
</buildjar>
</code>```

There are no errors.  Looking at ant -d output, there's no mention of the additional entry at all, where in the first example there is a line for fileset: Setup scanner in dir /some/path/somewhere with patternSet{ includes: [a_single_file] excludes: [] }

Ditto for multiple files.  This works:

```<code><buildjar .........>
  <also>
    <fileset dir="/some/path/somewhere">
      <include name="one_file" />
      <include name="foo**" />
    </fileset>
  </also>
</buildjar>
</code>```

but this does not:

```<code><buildjar .........>
  <also>
    <include name="/some/path/somewhere/one_file"/>
    <include name="/some/path/somewhere/foo**"/>
  </also>
</buildjar>
</code>```

According to the Ant manual's page for <jar>,

This task forms an implicit FileSet and supports most attributes of <fileset> (dir becomes basedir) as well as the nested <include>, <exclude> and <patternset> elements.

So in theory, shouldn't an <include> simply be enough, and become a nested element of the macro'd <jar>?

Obviously, in practice this isn't a problem (we slap a bigass comment in the build files telling people to not leave out the explicit <fileset>).  And we can't put the <fileset> into the macro definition like this:

```<code><macrodef name="buildjar">
  <element name="also"/>
  <sequential>
    <jar ....>
      .....
      <!-- Anything else for this specific jar. -->
>>    <fileset dir="some_generic_base_path">
        <also/>
>>    </fileset>
    </jar>
  </sequential>
</macrodef>
</code>```

because then when the calling code does a buildjar without any also blocks, the unrestricted fileset will include the entire some_generic_base_path tree.

Is this simply some interaction between macrodefs and filesets that has taken us by surprise?

答:
Short answer is no - it's not a macrodef problem.  To use the implicit fileset you must specify the basedir attribute for the <jar> task.  Here's an example that illustrates this:

```<code><jar destfile="my.jar">
    <include name="a/b" />
</jar>

<zip destfile="my.zip" >
    <include name="a/b" />
</zip>
</code>```

In the example the <jar> task will succeed and create a manifest-only jar file.  But the <zip> task will fail saying:

```<code>BUILD FAILED
build.xml:8: basedir attribute must be set, or at least one resource collection must be given!
</code>```

The jar task is based on the zip task and inherits its check for resources.  Because the jar task has some - the manifest - the error is not thrown.

If you want to use the implicit fileset, specify a basedir.

Body:
Using standard Ant 1.9.7 to assemble a bunch of jar files.  We've made a macro to help cut down on the verbosity of the XML:

<macrodef name="buildjar">
  ... bunch of <attribute> ...
  <element name="also"/>
  <sequential>
    <jar ....>
      <manifest>  ...  </manifest>
      <fileset what="stuff in every jar file" />
      <fileset what="and this stuff too" />
      <mappedresources if:true="beauty">
        <fileset for when truth is beauty/>
        <globmapper from="ugly" to="beauty"/>
      </mappedresoruces>

      <also/>

    </jar>
  </sequential>
</macrodef>

This works:

<buildjar .........>
  <also>
    <fileset file="/some/path/somewhere/a_single_file"/>
  </also>
</buildjar>

But this does not:

<buildjar .........>
  <also>
    <include name="/some/path/somewhere/a_single_file"/>
  </also>
</buildjar>

There are no errors.  Looking at ant -d output, there's no mention of the additional entry at all, where in the first example there is a line for fileset: Setup scanner in dir /some/path/somewhere with patternSet{ includes: [a_single_file] excludes: [] }

Ditto for multiple files.  This works:

<buildjar .........>
  <also>
    <fileset dir="/some/path/somewhere">
      <include name="one_file" />
      <include name="foo**" />
    </fileset>
  </also>
</buildjar>

but this does not:

<buildjar .........>
  <also>
    <include name="/some/path/somewhere/one_file"/>
    <include name="/some/path/somewhere/foo**"/>
  </also>
</buildjar>

According to the Ant manual's page for <jar>,

This task forms an implicit FileSet and supports most attributes of <fileset> (dir becomes basedir) as well as the nested <include>, <exclude> and <patternset> elements.

So in theory, shouldn't an <include> simply be enough, and become a nested element of the macro'd <jar>?

Obviously, in practice this isn't a problem (we slap a bigass comment in the build files telling people to not leave out the explicit <fileset>).  And we can't put the <fileset> into the macro definition like this:

<macrodef name="buildjar">
  <element name="also"/>
  <sequential>
    <jar ....>
      .....

>>    <fileset dir="some_generic_base_path">
        <also/>
>>    </fileset>
    </jar>
  </sequential>
</macrodef>

because then when the calling code does a buildjar without any also blocks, the unrestricted fileset will include the entire some_generic_base_path tree.

Is this simply some interaction between macrodefs and filesets that has taken us by surprise?

Body:
Short answer is no - it's not a macrodef problem.  To use the implicit fileset you must specify the basedir attribute for the <jar> task.  Here's an example that illustrates this:

<jar destfile="my.jar">
    <include name="a/b" />
</jar>

<zip destfile="my.zip" >
    <include name="a/b" />
</zip>

In the example the <jar> task will succeed and create a manifest-only jar file.  But the <zip> task will fail saying:

BUILD FAILED
build.xml:8: basedir attribute must be set, or at least one resource collection must be given!

The jar task is based on the zip task and inherits its check for resources.  Because the jar task has some - the manifest - the error is not thrown.

If you want to use the implicit fileset, specify a basedir.


问:
Invalid Debug Option Build Error Visual Studio for MAC
I am getting following error while building .NET Core MVC App.

```<code>Projects/MVCCoreTest/MVCCoreTest/CSC: Error CS1902: Invalid debug option `portable'. Valid options are `full' or `pdbonly' (CS1902) (MVCCoreTest)
</code>```

What does this mean and where do i set those valid options ?

答:
Goto Project Options by right clicking on project ....

Goto "Compiler"

Change "Debug Information" to "Full" or "Portable". It shall solve this problem.

Please let me know if this has helped.

ContentLicense: CC BY-SA 4.0

Body:
I am getting following error while building .NET Core MVC App.

Projects/MVCCoreTest/MVCCoreTest/CSC: Error CS1902: Invalid debug option `portable'. Valid options are `full' or `pdbonly' (CS1902) (MVCCoreTest)

What does this mean and where do i set those valid options ?


问:
How to encrypt and decrypt sound files in Java?
Is there a way to encrypt and decrypt sound files such as *.wav , *.au or *.snd files in Java ?

Edit :
I knew how to encrypt and decrypt text files, just curious if a sound file could be encrypted and decrypted, now it seems I can use the same methods.

答:
Like any other data file you can encrypt media files using standard encryption techniques.

For starters check these links....

http://en.wikipedia.org/wiki/Tiny_Encryption_Algorithm

The Tiny Encryption Algorithm (TEA) is
  a fast, simple and robust block cipher
  designed by David Wheeler and Roger
  Needham. This code is released under
  the LGPL. The algorithm is implemented
  in a single class:

http://www.winterwell.com/software/TEA.php

http://143.53.36.235:8080/tea.htm

http://143.53.36.235:8080/TEA_java_sc.txt


问:
Can't create migrations with same name even after deleting the file
```
php artisan make:migration create_batles_table
Created Migration: 2017_04_01_123218_create_batles_table

php artisan make:migration create_batles_table
  [InvalidArgumentException]
  A CreateBatlesTable migration already exists.

---------------------File deleted by me-----------------------------

php artisan make:migration create_batles_table
 [ErrorException]
 include(/home/lubuntu/Desktop/work/git/lara/database/migrations/2017_04_01_123218_create_batles_table.php): fail
  ed to open stream: No such file or directory
```

Now using another name "newbatles" instead of "batles"

```
php artisan make:migration create_newbatles_table
Created Migration: 2017_04_01_123343_create_newbatles_table

php artisan make:migration create_newbatles_table
[InvalidArgumentException]
A CreateNewbatlesTable migration already exists.

-----------File deleted by me--------------

php artisan make:migration create_newbatles_table
[ErrorException]
include(/home/lubuntu/Desktop/work/git/lara/database/migrations/2017_04_01_123343_create_newbatles_table.php): f
  ailed to open stream: No such file or directory
```

Why I can't recreate migrations with same name in Laravel 5.4?

答:
When changing something in migrations always run these commands:

```<code>php artisan cache:clear
php artisan view:clear
php artisan route:clear
composer dump-autoload
</code>```

It will clear all old stuff and run smoothly!

Update:

But remember: the table name must be unique inside that database...it's like a name for folder on a hard drive. You can't have more than one table with that specific name!

Body:
php artisan make:migration create_batles_table
Created Migration: 2017_04_01_123218_create_batles_table

php artisan make:migration create_batles_table
  [InvalidArgumentException]
  A CreateBatlesTable migration already exists.

---------------------File deleted by me-----------------------------

php artisan make:migration create_batles_table
 [ErrorException]
 include(/home/lubuntu/Desktop/work/git/lara/database/migrations/2017_04_01_123218_create_batles_table.php): fail
  ed to open stream: No such file or directory

Now using another name "newbatles" instead of "batles"

php artisan make:migration create_newbatles_table
Created Migration: 2017_04_01_123343_create_newbatles_table

php artisan make:migration create_newbatles_table
[InvalidArgumentException]
A CreateNewbatlesTable migration already exists.

-----------File deleted by me--------------

php artisan make:migration create_newbatles_table
[ErrorException]
include(/home/lubuntu/Desktop/work/git/lara/database/migrations/2017_04_01_123343_create_newbatles_table.php): f
  ailed to open stream: No such file or directory

Why I can't recreate migrations with same name in Laravel 5.4?

Body:
When changing something in migrations always run these commands:

php artisan cache:clear
php artisan view:clear
php artisan route:clear
composer dump-autoload

It will clear all old stuff and run smoothly!

Update:

But remember: the table name must be unique inside that database...it's like a name for folder on a hard drive. You can't have more than one table with that specific name!


问:
Laravel 5.4 Error when create user
Hi i got problem when i create user. I got this error:
FatalThrowableError in SessionGuard.php line 407: Type error: Argument 1 passed to Illuminate\Auth\SessionGuard::login() must implement interface Illuminate\Contracts\Auth\Authenticatable, null given, called in /home/mariusz/Pulpit/www/szpital/vendor/laravel/framework/src/Illuminate/Foundation/Auth/RegistersUsers.php on line 35

User is created anyway but this error is so anoying and i dont know how fix it.
I use laravel auth and i little edit register controller becouse i need add role for user and now my controller looks like that.

<?php

namespace App\Http\Controllers\Auth;

use App\User;
use App\Role;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Auth;

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    /**
     * Where to redirect users after registration.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => 'required|max:255',
            'lastname' => 'required|max:255',
            'phonenumber' => 'required|max:255',
            'email' => 'required|email|max:255|unique:users',
            'password' => 'required|min:6|confirmed',
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     *
     */

     public function create(array $data)
    {
        $user = new User();
        $user->name = $data['name'];
        $user->lastname = $data['lastname'];
        $user->phonenumber = $data['phonenumber'];
        $user->email = $data['email'];
        $user->password = bcrypt($data['password']);
        $user->save();
        $user->roles()->attach(Role::where('name', 'User')->first());
        Auth::login($user);

    }
}```

I dont know mybe i shouldnt edit it. I want explain when i got this error:
1.I go to page create acc.
2.I write name etc.
3.When i click create i got error
4. Next when i refresh page user is created,login and redirect to home page.

答:
You shouldn't need to add the line Auth::login($user); in Laravel 5.4 for auto-login following registration.  Replace:

```<code>public function create(array $data)
{
        $user = new User();
        $user->name = $data['name'];
        $user->lastname = $data['lastname'];
        $user->phonenumber = $data['phonenumber'];
        $user->email = $data['email'];
        $user->password = bcrypt($data['password']);
        $user->save();
        $user->roles()->attach(Role::where('name', 'User')->first());
        Auth::login($user);
}
</code>```

with:

```<code>public function create(array $data)
{
        $user = new User();
        $user->name = $data['name'];
        $user->lastname = $data['lastname'];
        $user->phonenumber = $data['phonenumber'];
        $user->email = $data['email'];
        $user->password = bcrypt($data['password']);
        $user->save();
        $user->roles()->attach(Role::where('name', 'User')->first());

        return $user;
}
</code>```

If your Laravel framework and auth controllers code is up-to-date, the RegisterUsers trait should address it for you.  This should also fix the issue you're having.

Title: Laravel 5.4 Error when create user

Body:
Hi i got problem when i create user. I got this error:
FatalThrowableError in SessionGuard.php line 407: Type error: Argument 1 passed to Illuminate\Auth\SessionGuard::login() must implement interface Illuminate\Contracts\Auth\Authenticatable, null given, called in /home/mariusz/Pulpit/www/szpital/vendor/laravel/framework/src/Illuminate/Foundation/Auth/RegistersUsers.php on line 35

User is created anyway but this error is so anoying and i dont know how fix it.
I use laravel auth and i little edit register controller becouse i need add role for user and now my controller looks like that.

<?php

namespace App\Http\Controllers\Auth;

use App\User;
use App\Role;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Auth;

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    /**
     * Where to redirect users after registration.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => 'required|max:255',
            'lastname' => 'required|max:255',
            'phonenumber' => 'required|max:255',
            'email' => 'required|email|max:255|unique:users',
            'password' => 'required|min:6|confirmed',
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     *
     */

     public function create(array $data)
    {
        $user = new User();
        $user->name = $data['name'];
        $user->lastname = $data['lastname'];
        $user->phonenumber = $data['phonenumber'];
        $user->email = $data['email'];
        $user->password = bcrypt($data['password']);
        $user->save();
        $user->roles()->attach(Role::where('name', 'User')->first());
        Auth::login($user);

    }
}

I dont know mybe i shouldnt edit it. I want explain when i got this error:
1.I go to page create acc.
2.I write name etc.
3.When i click create i got error
4. Next when i refresh page user is created,login and redirect to home page.

Body:
You shouldn't need to add the line Auth::login($user); in Laravel 5.4 for auto-login following registration.  Replace:

public function create(array $data)
{
        $user = new User();
        $user->name = $data['name'];
        $user->lastname = $data['lastname'];
        $user->phonenumber = $data['phonenumber'];
        $user->email = $data['email'];
        $user->password = bcrypt($data['password']);
        $user->save();
        $user->roles()->attach(Role::where('name', 'User')->first());
        Auth::login($user);
}

with:

public function create(array $data)
{
        $user = new User();
        $user->name = $data['name'];
        $user->lastname = $data['lastname'];
        $user->phonenumber = $data['phonenumber'];
        $user->email = $data['email'];
        $user->password = bcrypt($data['password']);
        $user->save();
        $user->roles()->attach(Role::where('name', 'User')->first());

        return $user;
}

If your Laravel framework and auth controllers code is up-to-date, the RegisterUsers trait should address it for you.  This should also fix the issue you're having.


问:
Android OS killing service, notification is staying
My Android App plays audio. The app starts a service, the service starts a notification with media buttons.

When the OS is low on resources, the OS kills my service. Yet the notification, with the media buttons, is staying. Because the service is gone, the media buttons  don't function anymore. A negative user experience.

I've been looking for solutions for a week. The OS is not informing me that the service is being killed. Please help.

答:
You should use foreground service for that and add this code before service will be destroyed:</p>

```<code>@Override
public void onDestroy() {
    stopForeground(true);
    super.onDestroy();
}
</code>```

Body:
You should use foreground service for that and add this code before service will be destroyed:

@Override
public void onDestroy() {
    stopForeground(true);
    super.onDestroy();
}


问:
Is it possible to view html and php on same page and also access/modify html content of html dom in php?
```<code><?php

$htmlDoc = <<< HTML

<html>
<body>

    <p id="hello">hello</p>

</body>
</html>

HTML;

echo "world";

?>
</code>```

how to get output as : hello world
hello from html
and world from php

and is it possible to access and modify html content in above php code like we can do in javascript like document.getElementById("hello").innerHTML

----follwing code sent by Niklesh---

```<code><?php
echo $htmlDoc = <<< HTML

<html>
<body>
    <p id="hello">hello</p>
</body>
</html>
HTML;

echo "world";

?>
</code>```

----- code that i tried -------

```<code><html>
<body>
    <p id="hello">hello</p>
</body>
</html>
HTML;

echo "world";

?>
</code>```

答:
Yes both are possible change your code as </p>

```<code><?php
echo $htmlDoc = <<< HTML
<html>
<body>
    <p id="hello">hello</p>
</body>
</html>
HTML;
echo "world";
echo '<br><input type="button" onClick="changeText()" value="Change Text">';
?>
<script type="text/javascript">
    function changeText(){
        document.getElementById("hello").innerHTML =  "Niklesh here";
    }
</script>
</code>```

Body:
<?php

$htmlDoc = <<< HTML

hello

HTML;

echo "world";

?>

how to get output as : hello world
hello from html
and world from php

and is it possible to access and modify html content in above php code like we can do in javascript like document.getElementById("hello").innerHTML

----follwing code sent by Niklesh---

<?php
echo $htmlDoc = <<< HTML

hello

HTML;

echo "world";

?>

----- code that i tried -------

hello

HTML;

echo "world";

?>

Body:
Yes both are possible change your code as

<?php
echo $htmlDoc = <<< HTML
<html>
<body>
    <p id="hello">hello</p>
</body>
</html>
HTML;
echo "world";
echo '<br><input type="button" onClick="changeText()" value="Change Text">';
?>
<script type="text/javascript">
    function changeText(){
        document.getElementById("hello").innerHTML =  "Niklesh here";
    }
</script>


问:
How does JS variable override work?
This code works fine:

```<code>const a = 1;
{
  const b = a; // let's use "a" in a sub-scope
}
{
  const a = 2; // let's override "a" in another sub-scope
}
</code>```

... but this code fails with a is not defined at line 3:

```<code>const a = 1;
{
  const b = a; // let's use "a" in a sub-scope <<< CRASH!! >>>
  const a = 2; // let's override "a" in the same sub-scope
}
</code>```

I tested this on node 7.7.4. It may be related to V8 only, I'm curious how Firefox would handle this.

Is it related to the way variable declaration is defined in the JS spec? const/let are not hoisted, but "something" (some metadata?) still seems to be hoisted, else we would have no issues.

答:
Hoisting refers to the notion that variable declarations are hoisted  a to the top of the variable scope.

More accurately, it is a side effect of the  a fact that JavaScript builds it's execution environment  in two passes.

The first pass sets up all function and variable declarations. At this stage, variables are declared but not defined, function declarations are declared and defined (that's function declarations: function fnName(){...} not variable function expressions: var fnName = function (){...}).

The second pass then executes the code with the available declared functions and variables (which currently are unassigned and therefore have the value undefined).

var is function scoped and not block scoped.
 Although let andconst allow the declaration of block scoped variables, the code is built using the two execution passes. The difference being that block scope should be considered in the first pass within their own scope (block scope or otherwise).

To illustrate this point, consider your second snippet.

The code throws an error in your second case because after the first pass it could be re-written as:

```<code>// const 'a' declared in this outer scope
const a:
a = 1;

{
  // separate const 'a' declared in this block scope
  // Declarations still hoisted for this block scope
  const b, a
  b = a; // a undefined here
  a = 2;
}
</code>```

Title: How does JS variable override work?

Body:
This code works fine:

const a = 1;
{
  const b = a; // let's use "a" in a sub-scope
}
{
  const a = 2; // let's override "a" in another sub-scope
}

... but this code fails with a is not defined at line 3:

const a = 1;
{
  const b = a; // let's use "a" in a sub-scope <<< CRASH!! >>>
  const a = 2; // let's override "a" in the same sub-scope
}

I tested this on node 7.7.4. It may be related to V8 only, I'm curious how Firefox would handle this.

Is it related to the way variable declaration is defined in the JS spec? const/let are not hoisted, but "something" (some metadata?) still seems to be hoisted, else we would have no issues.

Body:
Hoisting refers to the notion that variable declarations are hoisted  a to the top of the variable scope.

More accurately, it is a side effect of the  a fact that JavaScript builds it's execution environment  in two passes.

The first pass sets up all function and variable declarations. At this stage, variables are declared but not defined, function declarations are declared and defined (that's function declarations: function fnName(){...} not variable function expressions: var fnName = function (){...}).

The second pass then executes the code with the available declared functions and variables (which currently are unassigned and therefore have the value undefined).

var is function scoped and not block scoped.
 Although let andconst allow the declaration of block scoped variables, the code is built using the two execution passes. The difference being that block scope should be considered in the first pass within their own scope (block scope or otherwise).

To illustrate this point, consider your second snippet.

The code throws an error in your second case because after the first pass it could be re-written as:

// const 'a' declared in this outer scope
const a:
a = 1;

{
  // separate const 'a' declared in this block scope
  // Declarations still hoisted for this block scope
  const b, a
  b = a; // a undefined here
  a = 2;
}


问:
set width between two knobs in ionic 2 dual range slider
```<code><ion-range dual-knobs="true" pin="true" min="0" max="100" step="3" snaps="true"></ion-range>
</code>```

I want the above code to be looked like shown in image

答:
According to the docs,

Setting the dualKnobs property to true on the range component will
  enable two knobs on the range. If the range has two knobs, the value
  will be an object containing two properties: lower and upper.

Use ngModel

```<code><ion-range dual-knobs="true" pin="true" min="0" max="100" step="3" [(ngModel)]="knobValues" snaps="true"></ion-range>
</code>```

In your component:

```<code>knobValues:{
  upper:100,
  lower:50
}
</code>```

Body:
<ion-range dual-knobs="true" pin="true" min="0" max="100" step="3" snaps="true"></ion-range>

I want the above code to be looked like shown in image

Body:
According to the docs,

Setting the dualKnobs property to true on the range component will
  enable two knobs on the range. If the range has two knobs, the value
  will be an object containing two properties: lower and upper.

Use ngModel

<ion-range dual-knobs="true" pin="true" min="0" max="100" step="3" [(ngModel)]="knobValues" snaps="true"></ion-range>

In your component:

knobValues:{
  upper:100,
  lower:50
}


问:
ASP.net: Display PDF in a asp.net web page
User click on a link button and it will direct them to a url that is dynmaically generated which a pdf file. The browser will prompt the user to either save or open it.

I want to know if it is possible to downlaod the pdf file to the server then show the pdf file in the asp.net web page. When i google on this question, 99% of top link are some third party component. Is it a way to do this without purchase any 3rd party component?

thank

答:
Yes there is a way to do this without a 3rd party tool, but it involves coding a PDF-to-html translator.

If this is something for a business, the RoI for the 3rd party control is that you don't have to spend hundreds of hours coding & testing this component, when you could buy one for just a few hundred dollars.

Now, an alternative is to code a page which displays the data in the same way which the PDF file generates it (this could actually be handled by RDLC). So that when the user clicks the link button, they are taken to this display page, from which they can download the PDF version if they want a local copy.

OwnerDisplayName: Jack

OwnerDisplayName: Stephen Wrighton


问:
Stack gives 'dyld: malformed mach-o'
When I attempt to run stack, for example even just stack --version, I get

```<code>dyld: malformed mach-o: load commands size (38712) > 32768
</code>```

What can I do to fix this. This started appearing after some recent updates to Homebrew.

答: I also experienced the same issue when I upgraded to macOS Sierra, I was able to run Stack commands again by installing the Haskell Platform. The Stack tools included in the package seem to work.</p>

Title: Stack gives 'dyld: malformed mach-o'

Body:
When I attempt to run stack, for example even just stack --version, I get

dyld: malformed mach-o: load commands size (38712) > 32768

What can I do to fix this. This started appearing after some recent updates to Homebrew.


问:
Making a textField inside a movie clip display specific text after mouse click in actionscript 3
first of all let me clarify that I've been working with AS3 only for a couple of days. My project consists of a google map of a street which acts as a menu where the buttons are labels floating over some of the houses. The idea is that when you click on certain house a module of specific info spreads. That info would be textual and some photos. My intention is to have that module as a movie clip template that I create just once and would fill up dynamically with the info related with each clicked house. It's a long way to get to that and I still have to figure how to do it. But I'm starting with this little thing:
I want that when I click on certain button it tells a dynamic text field inside the movie clip to display the house address which acts as a tittle for the card where the info is displayed. I'm experimenting with currentTarget but despite not getting any errors the code is just not working. Here's my code:

```<code>z5990_btn.addEventListener(MouseEvent.CLICK,setTittle);
function setTittle(event:MouseEvent)
  {
    var target = event.currentTarget;
    var tittle = houseCard_mc.tittle_txt;
    tittle.text=String(target);

     }
</code>```

Please note that my learning consists basically of reading and asking forums and lots of trail and error. Thanks for taking time to read this and help me.

答:
Trace tittle to make sure it's actual TextField:

```<code>//...
var tittle = houseCard_mc.tittle_txt;
trace("tittle is:", tittle, "currentText:", tittle.text);
tittle.text=String(target);
</code>```

you should see this in output:

tittle is: [object TextField] currentText: foo

if it's not a TextField object but MovieClip then you will see this.

tittle is: [object  MovieClip] currentText: undefined

Than means that you are creating new text field in your tittle MovieClip with string content, which of course does nothing.

All you need to do is read for instance THIS EXAMPLE

Body:
first of all let me clarify that I've been working with AS3 only for a couple of days. My project consists of a google map of a street which acts as a menu where the buttons are labels floating over some of the houses. The idea is that when you click on certain house a module of specific info spreads. That info would be textual and some photos. My intention is to have that module as a movie clip template that I create just once and would fill up dynamically with the info related with each clicked house. It's a long way to get to that and I still have to figure how to do it. But I'm starting with this little thing:
I want that when I click on certain button it tells a dynamic text field inside the movie clip to display the house address which acts as a tittle for the card where the info is displayed. I'm experimenting with currentTarget but despite not getting any errors the code is just not working. Here's my code:

z5990_btn.addEventListener(MouseEvent.CLICK,setTittle);
function setTittle(event:MouseEvent)
  {
    var target = event.currentTarget;
    var tittle = houseCard_mc.tittle_txt;
    tittle.text=String(target);

     }

Please note that my learning consists basically of reading and asking forums and lots of trail and error. Thanks for taking time to read this and help me.

Body:
Trace tittle to make sure it's actual TextField:

//...
var tittle = houseCard_mc.tittle_txt;
trace("tittle is:", tittle, "currentText:", tittle.text);
tittle.text=String(target);

you should see this in output:

tittle is: [object TextField] currentText: foo

if it's not a TextField object but MovieClip then you will see this.

tittle is: [object  MovieClip] currentText: undefined

Than means that you are creating new text field in your tittle MovieClip with string content, which of course does nothing.

All you need to do is read for instance THIS EXAMPLE


问:
How to reduce time of algorithm execution
I have to wirte an algorithm, which finding two nearest points on earth. I wrote the code below and it works for my tests, but the time of execution is too long. I tried to modify the code, but it didn't help. Maybe someone will have an idea what should I do?

```<code>struct Points
{
    std::string key;
    double latitude;
    char latSign;
    double longitude;
    char longSign;
};

typedef std::pair<std::pair<std::string, std::string>, double> myType;

double toFraction(short deegres, short minutes)
{
    return (double)deegres + (minutes / 60.0);
}

double orthodroma(const Points &a, const Points &b)
{
    double radian = M_PI / 180;
    return acos((cos((90 - a.latitude) * radian) *
                 cos((90 - b.latitude) * radian)) +
                (sin((90 - a.latitude) * radian) *
                 sin((90 - b.latitude) * radian) *
                 cos((a.longitude - b.longitude) * radian))) *
           (180 / M_PI);
}

bool sortByLatitude(const Points &a, const Points &b)
{
    return a.latitude > b.latitude;
}

myType bruteForce(const std::vector<Points> &vec, int begin, int n)
{
    myType result;
    double min = 1000000;
    int _i, _j;
    if(n > 300)
    {
    }
    for(int i = begin; i < (n + begin) - 1; i++)
    {
        for(int j = i + 1; j < n + begin; j++)
        {
            double tmp;
            tmp = orthodroma(vec[i], vec[j]);
            if(tmp < min)
            {
                min = tmp;
                _i = i;
                _j = j;
            }
        }
    }
    result.first.first = vec[_i].key;
    result.first.second = vec[_j].key;
    result.second = min;
    return result;
}

myType divideAndConquer(std::vector<Points> &vec, int begin, int n)
{
    if(n <= 3)
    {
        return bruteForce(vec, begin, n);
    }
    std::sort(vec.begin(), vec.end(), sortByLatitude);
    int middle = n / 2;
    Points point = vec[middle];
    myType left = divideAndConquer(vec, begin, middle);
    myType right = divideAndConquer(vec, middle, (n - middle));
    bool which;
    double minDist = std::min(left.second, right.second);
    if(left.second < right.second)
        which = false;
    else
        which = true;
    std::vector<Points> arr;
    for(int i = 0; i < n; i++)
    {
        if(abs(vec[i].latitude - point.latitude) < minDist)
        {
            arr.push_back(vec[i]);
        }
    }
    int size = arr.size();
    if(size < 2)
    {
        if(which)
            return right;
        else
            return left;
    }
    else
    {
        myType one = bruteForce(arr, 0, size);
        if(which)
        {
            if(one.second < right.second)
                return one;
            else
                return right;
        }
        else
        {
            if(one.second < left.second)
                return one;
            else
                return left;
        }
    }
}
</code>```

PS. I have to use divide an conquer method.

答:
To find the nearest two points you need to first check distance to the nearest point for each point.

You should use a KD tree for fast nearest neighbor lookups.  You can use comparable distance to save a sqrt() operation.

This is a great kd tree library

Body:
I have to wirte an algorithm, which finding two nearest points on earth. I wrote the code below and it works for my tests, but the time of execution is too long. I tried to modify the code, but it didn't help. Maybe someone will have an idea what should I do?

struct Points
{
    std::string key;
    double latitude;
    char latSign;
    double longitude;
    char longSign;
};

typedef std::pair<std::pair<std::string, std::string>, double> myType;

double toFraction(short deegres, short minutes)
{
    return (double)deegres + (minutes / 60.0);
}

double orthodroma(const Points &a, const Points &b)
{
    double radian = M_PI / 180;
    return acos((cos((90 - a.latitude) * radian) *
                 cos((90 - b.latitude) * radian)) +
                (sin((90 - a.latitude) * radian) *
                 sin((90 - b.latitude) * radian) *
                 cos((a.longitude - b.longitude) * radian))) *
           (180 / M_PI);
}

bool sortByLatitude(const Points &a, const Points &b)
{
    return a.latitude > b.latitude;
}

myType bruteForce(const std::vector<Points> &vec, int begin, int n)
{
    myType result;
    double min = 1000000;
    int _i, _j;
    if(n > 300)
    {
    }
    for(int i = begin; i < (n + begin) - 1; i++)
    {
        for(int j = i + 1; j < n + begin; j++)
        {
            double tmp;
            tmp = orthodroma(vec[i], vec[j]);
            if(tmp < min)
            {
                min = tmp;
                _i = i;
                _j = j;
            }
        }
    }
    result.first.first = vec[_i].key;
    result.first.second = vec[_j].key;
    result.second = min;
    return result;
}

myType divideAndConquer(std::vector<Points> &vec, int begin, int n)
{
    if(n <= 3)
    {
        return bruteForce(vec, begin, n);
    }
    std::sort(vec.begin(), vec.end(), sortByLatitude);
    int middle = n / 2;
    Points point = vec[middle];
    myType left = divideAndConquer(vec, begin, middle);
    myType right = divideAndConquer(vec, middle, (n - middle));
    bool which;
    double minDist = std::min(left.second, right.second);
    if(left.second < right.second)
        which = false;
    else
        which = true;
    std::vector<Points> arr;
    for(int i = 0; i < n; i++)
    {
        if(abs(vec[i].latitude - point.latitude) < minDist)
        {
            arr.push_back(vec[i]);
        }
    }
    int size = arr.size();
    if(size < 2)
    {
        if(which)
            return right;
        else
            return left;
    }
    else
    {
        myType one = bruteForce(arr, 0, size);
        if(which)
        {
            if(one.second < right.second)
                return one;
            else
                return right;
        }
        else
        {
            if(one.second < left.second)
                return one;
            else
                return left;
        }
    }
}

PS. I have to use divide an conquer method.


问:
How can I change [kafka-consumer-1] this thread name?
I set the concurrency to 10 and I can see 10 different thread id but the thread name is all the same. How can set the listener name? I tried container.setBeanName but no luck. Please help. By the way I am use 1.1.2 version</p>

答:
The thread names are unique; it's just that boot's logging configuration truncates the name by default; we will fix the default thread naming but, in the meantime, you can either change the logging configuration or use named executors. Use setConsumerTaskExecutor(execC()) and setListenerTaskExecutor(execL()) on the container's ContainerProperties ...

```<code>@Bean
public AsyncListenableTaskExecutor execC() {
    ThreadPoolTaskExecutor tpte = new ThreadPoolTaskExecutor();
    tpte.setCorePoolSize(15);
    return tpte;
}

@Bean
public AsyncListenableTaskExecutor execL() {
    ThreadPoolTaskExecutor tpte = new ThreadPoolTaskExecutor();
    tpte.setCorePoolSize(15);
    return tpte;
}
</code>```

Body:
The thread names are unique; it's just that boot's logging configuration truncates the name by default; we will fix the default thread naming but, in the meantime, you can either change the logging configuration or use named executors. Use setConsumerTaskExecutor(execC()) and setListenerTaskExecutor(execL()) on the container's ContainerProperties ...

@Bean
public AsyncListenableTaskExecutor execC() {
    ThreadPoolTaskExecutor tpte = new ThreadPoolTaskExecutor();
    tpte.setCorePoolSize(15);
    return tpte;
}

@Bean
public AsyncListenableTaskExecutor execL() {
    ThreadPoolTaskExecutor tpte = new ThreadPoolTaskExecutor();
    tpte.setCorePoolSize(15);
    return tpte;
}


问:
How to Delete Additional build files from the Project Solution in visual studio
How to delete additional build files from the project solution in Visual Studio?

I am forced to clear this files everytime manually when I want to give my executable program to anyone

Any solution?

I am using C# and C++.

答:
You can't.

These files are generated when the .exe is generated and you can't force VS to not make them.


问:
Which is better: Several SQL queries or one sql data with lots of data?
I am making a quiz and I am expecting a lot of players for it. The quiz has a fixed number of questions.The quiz system can either fetch individual questions one by one from the MySql database and display it to the user. Or alternatively  I can fetch all the questions when he/she logs in and display them one by one. Can the second method significantly help in reducing the load on the server due to large number of SQL queries? Here I am talking about 500-600 users simultaneously playing the game.</p>

答:
It depends on the numbers. Are you displaying all the questions or you are picking random 5 out of 1000?

If the number of questions is small, fetching them in a single query will be better.

If the number of questions is large, fetching them in a single query may use a lot of memory, so fetching them one-by-one will be better.


问:
How to enable pcntl in PHP (while using a framework like Symfony 2)
Consider:

```<code>cd c:\xampp\htdocs\login
php app/console server:start
</code>```

This command needs the pcntl extension to run.

This is the error I get when I try to start the web server in my Symfony 2 environment...

I found a fix, by using the command:

```<code>php app/console server:run
</code>```

But why doesn't server:start work on my desktop?

My goal is to:

Starting the Web server

Running a Symfony application using PHP's built-in web server is as easy as executing the server:start command:

```<code>php app/console server:start
</code>```

答:
On Windows

You can't install the pcntl extension on Windows. According to the PHP documentation:

Note: This extension is not available on Windows platforms.

Try using Vagrant or a plain virtual machine with a Linux distributions like Ubuntu, Debian or Mint.

On Unix

First, type in your command line in your home directory:

mkdir php
cd php
apt-get source php5
cd php5-(WHATEVER_RELEASE)/ext/pcntl
phpize
./configure
make
```
<p>Then do this:</p>
<pre class="lang-none prettyprint-override"><code>cp modules/pcntl.so /usr/lib/php5/WHEVER_YOUR_SO_FILES_ARE/
echo "extension=pcntl.so" > /etc/php5/conf.d/pcntl.ini
</code>```

Finished!

On Mac

Taken from an answer to How can I enable process control extension (PCNTL) in PHP MAMP?!

There is a way of compiling PCNTL as an extension and linking it in to an existing PHP build, but it's a bit in-depth.

I'm doing the following on Mac OS X v10.6 (Snow Leopard) (64bit), with MAMP and PHP version 5.3.6. Remember to change PHP version numbers in the following lines if yours is different!

Please note that make is required, which isn't installed by default on Mac OS X. You need to install this via Mac developer tools, http://developer.apple.com/unix/.

First, download a tar of the PHP source code that matches the version you are using in MAMP (e.g., mine is 5.3.6), which you can do at Unsupported Historical Releases. Untar and cd to php-[version]/ext/pcntl, e.g.:

wget http://museum.php.net/php5/php-5.3.6.tar.gz
tar xvf php-5.3.6.tar.gz
cd php-5.3.6/ext/pcntl
```
<p>You then need to run <code>phpize</code> in the pcntl directory, which is a binary file that comes with MAMP:</p>
<pre class="lang-none prettyprint-override"><code>/Applications/MAMP/bin/php/php5.3.6/bin/phpize
</code>```

This creates a bunch of files that are needed for preparing an extension for compiling.

We now need to add some flags to tell it to compile the library with dual 32-bit and 64-bit architecture, as the MAMP PHP has been built this way. If you don't do this, the compiled shared objects won't work.

MACOSX_DEPLOYMENT_TARGET=10.6
CFLAGS="-arch i386 -arch x86_64 -g -Os -pipe -no-cpp-precomp"
CCFLAGS="-arch i386 -arch x86_64 -g -Os -pipe"
CXXFLAGS="-arch i386 -arch x86_64 -g -Os -pipe"
LDFLAGS="-arch i386 -arch x86_64 -bind_at_load"
export CFLAGS CXXFLAGS LDFLAGS CCFLAGS MACOSX_DEPLOYMENT_TARGET
```
<p>We can then run <code>./configure</code> and <code>make</code> to build our shared object:</p>
<pre class="lang-none prettyprint-override"><code>./configure
make
</code>```

This puts a file called pcntl.so in the modules directory. Copy this file to your MAMP's PHP extensions directory:

cp modules/pcntl.so /Applications/MAMP/bin/php/php5.3.6/lib/php/extensions/no-debug-non-zts-20090626/
```
<p>Finally, edit the PHP INI file to include the extension:</p>
<pre class="lang-none prettyprint-override"><code>echo "extension=pcntl.so" >> /Applications/MAMP/bin/php/php5.3.6/conf/php.ini
</code>```

PCNTL should now be enabled. To check to see whether it has been added, just run:

/Applications/MAMP/bin/php/php5.3.6/bin/php --ri pcntl

pcntl

pcntl support => enabled
```

If you see that, it's worked!

Helpful resources

For Windows:

How can I install PCNTL extension in Windows?

Use proc_open() instead of pcntl_fork() in simpletest

For Unix operating systems:

http://www.crimulus.com/2010/07/30/howto-enable-pcntl-in-ubuntu-php-installations/

For Mac:

How can I enable process control extension (PCNTL) in PHP MAMP?

Installing PCNTL module for PHP without recompiling

Other information:

[DX] Show a message if server:start is missing pcntl #12153

Body:
Consider:

cd c:\xampp\htdocs\login
php app/console server:start

This command needs the pcntl extension to run.

This is the error I get when I try to start the web server in my Symfony 2 environment...

I found a fix, by using the command:

php app/console server:run

But why doesn't server:start work on my desktop?

My goal is to:

Starting the Web server

Running a Symfony application using PHP's built-in web server is as easy as executing the server:start command:

php app/console server:start

Body:
On Windows

You can't install the pcntl extension on Windows. According to the PHP documentation:

Note: This extension is not available on Windows platforms.

Try using Vagrant or a plain virtual machine with a Linux distributions like Ubuntu, Debian or Mint.

On Unix

First, type in your command line in your home directory:

mkdir php
cd php
apt-get source php5
cd php5-(WHATEVER_RELEASE)/ext/pcntl
phpize
./configure
make

Then do this:

cp modules/pcntl.so /usr/lib/php5/WHEVER_YOUR_SO_FILES_ARE/
echo "extension=pcntl.so" > /etc/php5/conf.d/pcntl.ini

Finished!

On Mac

Taken from an answer to How can I enable process control extension (PCNTL) in PHP MAMP?!

There is a way of compiling PCNTL as an extension and linking it in to an existing PHP build, but it's a bit in-depth.

I'm doing the following on Mac OS X v10.6 (Snow Leopard) (64bit), with MAMP and PHP version 5.3.6. Remember to change PHP version numbers in the following lines if yours is different!

Please note that make is required, which isn't installed by default on Mac OS X. You need to install this via Mac developer tools, http://developer.apple.com/unix/.

First, download a tar of the PHP source code that matches the version you are using in MAMP (e.g., mine is 5.3.6), which you can do at Unsupported Historical Releases. Untar and cd to php-[version]/ext/pcntl, e.g.:

wget http://museum.php.net/php5/php-5.3.6.tar.gz
tar xvf php-5.3.6.tar.gz
cd php-5.3.6/ext/pcntl

You then need to run phpize in the pcntl directory, which is a binary file that comes with MAMP:

/Applications/MAMP/bin/php/php5.3.6/bin/phpize

This creates a bunch of files that are needed for preparing an extension for compiling.

We now need to add some flags to tell it to compile the library with dual 32-bit and 64-bit architecture, as the MAMP PHP has been built this way. If you don't do this, the compiled shared objects won't work.

MACOSX_DEPLOYMENT_TARGET=10.6
CFLAGS="-arch i386 -arch x86_64 -g -Os -pipe -no-cpp-precomp"
CCFLAGS="-arch i386 -arch x86_64 -g -Os -pipe"
CXXFLAGS="-arch i386 -arch x86_64 -g -Os -pipe"
LDFLAGS="-arch i386 -arch x86_64 -bind_at_load"
export CFLAGS CXXFLAGS LDFLAGS CCFLAGS MACOSX_DEPLOYMENT_TARGET

We can then run ./configure and make to build our shared object:

./configure
make

This puts a file called pcntl.so in the modules directory. Copy this file to your MAMP's PHP extensions directory:

cp modules/pcntl.so /Applications/MAMP/bin/php/php5.3.6/lib/php/extensions/no-debug-non-zts-20090626/

Finally, edit the PHP INI file to include the extension:

echo "extension=pcntl.so" >> /Applications/MAMP/bin/php/php5.3.6/conf/php.ini

PCNTL should now be enabled. To check to see whether it has been added, just run:

/Applications/MAMP/bin/php/php5.3.6/bin/php --ri pcntl

pcntl

pcntl support => enabled

If you see that, it's worked!

Helpful resources

For Windows:

How can I install PCNTL extension in Windows?

Use proc_open() instead of pcntl_fork() in simpletest

For Unix operating systems:

http://www.crimulus.com/2010/07/30/howto-enable-pcntl-in-ubuntu-php-installations/

For Mac:

How can I enable process control extension (PCNTL) in PHP MAMP?

Installing PCNTL module for PHP without recompiling

Other information:

[DX] Show a message if server:start is missing pcntl #12153

OwnerDisplayName: anon


答:
Upload your build to github.

Give your friend the link to the build repository.

Make your friend delete the files when they download the repo.

To answer your question: No, there is no way to prevent VS from automatically generating these build files. But there are ways to circumvent you from having to do the work, as I've stated above.

Title: How to Delete Additional build files from the Project Solution in visual studio

Body:
How to delete additional build files from the project solution in Visual Studio?

I am forced to clear this files everytime manually when I want to give my executable program to anyone

Any solution?

I am using C# and C++.


问:
Why an object is invisible?
I have a class. In this class I declare a a private variable private Agent agent;. In my class I have

```<code>private Thread controller = new Thread() {
...
}
</code>```

Within the above private thread I call getParameter which is a private method of the considered class. Within the getParameter I call one of the methods of the agent. As a result I get a NullPointerException. So, I conclude that agent is not visible from the getParameter.

Why is that? Can it be that the reason of that is that the getParameter is within the private Thread? And, if it is the case, how the described problem can be resolved?

ADDED

I realized that I need to be more specific. My code is organized like that:

```<code>public class GameWindow {
   ...
   private Agent agent;
   ...
   private Thread controller = new Thread() {
        public void run() {
           ...
           Agent agent = new Agent();
           ...
           parameter = getParameter();
        }
  }
  ...
  private String getParameter() {
     ...
     agent.someMethod();
     ...
  }
}
</code>```

ADDED 2
In the GameWindow I have:

```<code>public void startWindow() {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            controller.start();
        }
    });
}
</code>```

答:
Agent was never initialized.  You want something like this:

Agent agent = new Agent();

Title: Why an object is invisible?

Body:
I have a class. In this class I declare a a private variable private Agent agent;. In my class I have

private Thread controller = new Thread() {
...
}

Within the above private thread I call getParameter which is a private method of the considered class. Within the getParameter I call one of the methods of the agent. As a result I get a NullPointerException. So, I conclude that agent is not visible from the getParameter.

Why is that? Can it be that the reason of that is that the getParameter is within the private Thread? And, if it is the case, how the described problem can be resolved?

ADDED

I realized that I need to be more specific. My code is organized like that:

public class GameWindow {
   ...
   private Agent agent;
   ...
   private Thread controller = new Thread() {
        public void run() {
           ...
           Agent agent = new Agent();
           ...
           parameter = getParameter();
        }
  }
  ...
  private String getParameter() {
     ...
     agent.someMethod();
     ...
  }
}

ADDED 2
In the GameWindow I have:

public void startWindow() {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            controller.start();
        }
    });
}


问:
Dia crashing with Mac OS 10.11.6
Issue: Since "upgrading" to El Capitan, Dia won't open (icon briefly appears then vanishes).

Error message (when opening via commandline):

```<code>(process:45300): Gdk-WARNING **: locale not supported by C library

(process:45300): Gtk-WARNING **: Locale not supported by C library.
    Using the fallback 'C' locale.

(dia-bin:45300): Gtk-WARNING **: cannot open display: /private/tmp/com.apple.launchd.xxxxxxx/org.macosforge.xquartz:0
</code>```

Followed instruction on this bug report: https://sourceforge.net/p/dia-installer/support-requests/105/ without success:

Error message following code change suggested in bug report:

```<code>(process:44516): Gdk-WARNING **: locale not supported by C library

(process:44516): Gtk-WARNING **: Locale not supported by C library.
    Using the fallback 'C' locale.

(dia-bin:44516): Gtk-WARNING **: cannot open display: :0
</code>```

Relevant Version Information:

Dia version 0.97.2 (freshly downloaded from http://dia-installer.de/download/macosx.html)

XQuartz 2.7.11

Mac OS 10.11.6

Has anyone managed to get Dia working with El Capitan?

答:
In case this helps anyone else, a fresh install of XQuartz (https://www.xquartz.org) resolved the issue.

Note: still needed the export DISPLAY=:0 addition at line 39 in the source code.

Title: Dia crashing with Mac OS 10.11.6

Body:
Issue: Since "upgrading" to El Capitan, Dia won't open (icon briefly appears then vanishes).

Error message (when opening via commandline):

(process:45300): Gdk-WARNING **: locale not supported by C library

(process:45300): Gtk-WARNING **: Locale not supported by C library.
    Using the fallback 'C' locale.

(dia-bin:45300): Gtk-WARNING **: cannot open display: /private/tmp/com.apple.launchd.xxxxxxx/org.macosforge.xquartz:0

Followed instruction on this bug report: https://sourceforge.net/p/dia-installer/support-requests/105/ without success:

Error message following code change suggested in bug report:

(process:44516): Gdk-WARNING **: locale not supported by C library

(process:44516): Gtk-WARNING **: Locale not supported by C library.
    Using the fallback 'C' locale.

(dia-bin:44516): Gtk-WARNING **: cannot open display: :0

Relevant Version Information:

Dia version 0.97.2 (freshly downloaded from http://dia-installer.de/download/macosx.html)

XQuartz 2.7.11

Mac OS 10.11.6

Has anyone managed to get Dia working with El Capitan?