问:
Overlay an image when app is inactive
I'm using these code to

1) overlay an image when the app is inactive (double tap the home button twice).

2) Remove the image when the app is active (reopen the app)

In appdelegate.h file:

```<code>@property (nonatomic, strong) UIImageView *splashScreenImageView;
</code>```

In appdelegate.m file:

```<code>- (void)applicationWillResignActive:(UIApplication *)application
{
    UIImage *splashScreenImage = [UIImage imageNamed:@"BackgroundScreenCaching"];
    _splashScreenImageView = [[UIImageView alloc] initWithImage:splashScreenImage];
    [self.window addSubview:_splashScreenImageView];
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    if(_splashScreenImageView != nil) {
        [_splashScreenImageView removeFromSuperview];
        _splashScreenImageView = nil;
    }
}
</code>```

Problem:

However, SOMETIME when pressing the home button twice, the iOS still caches the app screen with sensitive information instead of the overlay image in iOS 11. Tested no issue in iOS10.

Updated

Issue still persist after changing to this:

```<code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

    BOOL result = [super application:application didFinishLaunchingWithOptions:launchOptions];
...
    UIImage *splashScreenImage = [UIImage imageNamed:@"BackgroundScreenCaching"];
    _splashScreenImageView = [[UIImageView alloc] initWithImage:splashScreenImage];
    [_splashScreenImageView setFrame:self.window.bounds];

    return result;
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    if(_splashScreenImageView != nil) {
        [_splashScreenImageView removeFromSuperview];
    }
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    [self.window addSubview:_splashScreenImageView];
}
</code>```

答:
Your code should work fine ,

May be your app didn't get time to alloc your imageView on time   when applicationWillResignActive called
and you are re-creating object every time . with  [UIImageView alloc] initWithImage

So my suggestion is put this code in didFinishLaunching

```<code>UIImage *splashScreenImage = [UIImage imageNamed:@"BackgroundScreenCaching"];
_splashScreenImageView = [[UIImageView alloc] initWithImage:splashScreenImage];
</code>```

and just add subview on UIWindow and remove it when  applicationDidBecomeActive

Also bring  _splashScreenImageView to front !!

Hope it may solve your problem

Good Luck

UPDATE

to add in main queue

```<code>dispatch_async(dispatch_get_main_queue(), ^{
       [self.window addSubview:_splashScreenImageView];
        [self.window bringSubviewToFront:_splashScreenImageView];
});
</code>```

to remove in main queue

```<code>dispatch_async(dispatch_get_main_queue(), ^{
    [_splashScreenImageView removeFromSuperview];
});
</code>```

UPDATE 2

according  to https://developer.apple.com/library/content/qa/qa1838/_index.html

and
https://developer.apple.com/library/content/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/StrategiesforHandlingAppStateTransitions/StrategiesforHandlingAppStateTransitions.html

Prepare for the App Snapshot
  Shortly after an app delegate’s applicationDidEnterBackground: method returns, the system takes a snapshot of the app’s windows. Similarly, when an app is woken up to perform background tasks, the system may take a new snapshot to reflect any relevant changes. For example, when an app is woken to process downloaded items, the system takes a new snapshot so that can reflect any changes caused by the incorporation of the items. The system uses these snapshot images in the multitasking UI to show the state of your app.

If you make changes to your views upon entering the background, you can call the snapshotViewAfterScreenUpdates: method of your main view to force those changes to be rendered. Calling the setNeedsDisplay method on a view is ineffective for snapshots because the snapshot is taken before the next drawing cycle, thus preventing any changes from being rendered. Calling the snapshotViewAfterScreenUpdates: method with a value of YES forces an immediate update to the underlying buffers that the snapshot machinery uses.

Try to present temp view controller applicationDidEnterBackground as done in demo of Apple

Title: Overlay an image when app is inactive

Body:
I'm using these code to

1) overlay an image when the app is inactive (double tap the home button twice).

2) Remove the image when the app is active (reopen the app)

In appdelegate.h file:

@property (nonatomic, strong) UIImageView *splashScreenImageView;

In appdelegate.m file:

- (void)applicationWillResignActive:(UIApplication *)application
{
    UIImage *splashScreenImage = [UIImage imageNamed:@"BackgroundScreenCaching"];
    _splashScreenImageView = [[UIImageView alloc] initWithImage:splashScreenImage];
    [self.window addSubview:_splashScreenImageView];
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    if(_splashScreenImageView != nil) {
        [_splashScreenImageView removeFromSuperview];
        _splashScreenImageView = nil;
    }
}

Problem:

However, SOMETIME when pressing the home button twice, the iOS still caches the app screen with sensitive information instead of the overlay image in iOS 11. Tested no issue in iOS10.

Updated

Issue still persist after changing to this:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

    BOOL result = [super application:application didFinishLaunchingWithOptions:launchOptions];
...
    UIImage *splashScreenImage = [UIImage imageNamed:@"BackgroundScreenCaching"];
    _splashScreenImageView = [[UIImageView alloc] initWithImage:splashScreenImage];
    [_splashScreenImageView setFrame:self.window.bounds];

    return result;
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    if(_splashScreenImageView != nil) {
        [_splashScreenImageView removeFromSuperview];
    }
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    [self.window addSubview:_splashScreenImageView];
}

Body:
Your code should work fine ,

May be your app didn't get time to alloc your imageView on time   when applicationWillResignActive called
and you are re-creating object every time . with  [UIImageView alloc] initWithImage

So my suggestion is put this code in didFinishLaunching

UIImage *splashScreenImage = [UIImage imageNamed:@"BackgroundScreenCaching"];
_splashScreenImageView = [[UIImageView alloc] initWithImage:splashScreenImage];

and just add subview on UIWindow and remove it when  applicationDidBecomeActive

Also bring  _splashScreenImageView to front !!

Hope it may solve your problem

Good Luck

UPDATE

to add in main queue

dispatch_async(dispatch_get_main_queue(), ^{
       [self.window addSubview:_splashScreenImageView];
        [self.window bringSubviewToFront:_splashScreenImageView];
});

to remove in main queue

dispatch_async(dispatch_get_main_queue(), ^{
    [_splashScreenImageView removeFromSuperview];
});

UPDATE 2

according  to https://developer.apple.com/library/content/qa/qa1838/_index.html

and
https://developer.apple.com/library/content/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/StrategiesforHandlingAppStateTransitions/StrategiesforHandlingAppStateTransitions.html

Prepare for the App Snapshot
  Shortly after an app delegate’s applicationDidEnterBackground: method returns, the system takes a snapshot of the app’s windows. Similarly, when an app is woken up to perform background tasks, the system may take a new snapshot to reflect any relevant changes. For example, when an app is woken to process downloaded items, the system takes a new snapshot so that can reflect any changes caused by the incorporation of the items. The system uses these snapshot images in the multitasking UI to show the state of your app.

If you make changes to your views upon entering the background, you can call the snapshotViewAfterScreenUpdates: method of your main view to force those changes to be rendered. Calling the setNeedsDisplay method on a view is ineffective for snapshots because the snapshot is taken before the next drawing cycle, thus preventing any changes from being rendered. Calling the snapshotViewAfterScreenUpdates: method with a value of YES forces an immediate update to the underlying buffers that the snapshot machinery uses.

Try to present temp view controller applicationDidEnterBackground as done in demo of Apple


来源: stackexchange

问:
How to add button for each row using for loop in datatables by ajax and jquery
i want to add buttons for each row using ajax function...I code something but is not work well.. Buttons move out of the table and view all buttons in the bottom if the page.I want to add these buttons to datatables row...

I want to add abc buttons one by one to [object Object] feild using for loop

ajax and jquery cord

```<code><script>
        $(document).ready(function () {
            $("#searchArea").hide();
            var uID = $("#userName").val();

            var tableProduct = $('#dataTbl').DataTable({
                "bSort": true
                , "oLanguage": {"sZeroRecords": "", "sEmptyTable": ""}
            });
            $.ajax({
                type: 'GET',
                url: '${pageContext.request.contextPath}/restservice/App50/' + uID,
                success: function (result) {
                    var jString = JSON.stringify(result);
                    var jdata = JSON.parse(jString);

                    for (var x = 0; x < jdata.length; x++) {
                        var pa = $('#aaa');
                        var td1 = jdata[x].snumber;
                        var td2 = jdata[x].date;
                        var td3 = jdata[x].slsNo + " in " + jdata[x].slsiUnit;
                        var td4 = jdata[x].productDesc;
                        var td5 = jdata[x].status;
                        var td6 = pa.append('<input type="button" class="btn btn-success" value="abc">');
                        var td7 = "jdata[x].hsCode";
                        var td8 = "jdata[x].hsCode";
                        tableProduct.row.add([td1, td2, td3, td4, td5, td6, td7, td8]).draw(true);
                    }
                }

            });

        });
    </script>
</code>```

jsp cord

```<code><body>
        <div id="bootstrapCssTest" class="hidden"></div>
        <div id="bootstrapCssTest" class="hidden"></div>

        <div class="container">
            <div class="row headerRow1">
                <div class="col-md-12">
                    <jsp:include page="template/banner.jsp"/>
                </div>
            </div>
            <div class="row">
                <div class="authheader">
                    <%@include file="template/message.jsp" %>
                </div>
            </div>
            <div class="row">
                <div class="col-xs-12 col-sm-4 col-md-3 col-lg-3">
                    <jsp:include page="template/header.jsp"/>
                </div>
                <div class="col-xs-12 col-sm-8 col-md-9 col-lg-9">
                    <div class="row">
                        <div class="col-lg-12">
                            <div class="well lead">List of Applications</div>
                        </div>
                    </div>
                    <div class="row">
                        <input type="hidden" id="userName" value="${userID}"/>
                        <input type="hidden" id="recentView" value="1"/>
                        <div class="panel panel-default">

                            <div id="ribbon">Search - <p id="viewSearchCategory" style="display: inline-block" >View Recent 50 Applications</p></div>
                            <div id="searchArea" class="well ">
                                <div class="row">
                                    VIEW RECENT
                                    <select id="viewNumbers" name="viewNumbers">
                                        <option value="50">50</option>
                                        <option value="100">100</option>
                                        <option value="150">150</option>
                                        <option value="200">200</option>
                                        <option value="500">500</option>
                                        <option value="750">750</option>
                                        <option value="1000">1000</option>
                                    </select>
                                    APPLICATIONS
                                </div>
                            </div>
                            <!-- Default panel contents -->
                            <div style="overflow-x:auto;">
                                <table id="dataTbl" class="table table-bordered table-hover" style="font-size:13px;">
                                    <thead>
                                        <tr>
                                            <th width="10%">SLSI Entry No</th>
                                            <th width="10%">Application Posted in</th>
                                            <th width="30%">SLS No and Unit</th>
                                            <th width="30%">Product Description</th>
                                            <th width="10%">Status</th>
                                            <th class="hidden-print"></th>
                                            <th class="hidden-print"></th>
                                            <th class="hidden-print"></th>
                                        </tr>
                                    </thead>
                                </table>
                            </div>
                            <p id="aaa"></p>
                        </div>
                    </div>
                </div>
            </div> <jsp:include page="template/footer.jsp"/></div>
    </body>
</code>```

help me someone

答:
You can use rows().every() property of dataTable

i will show you one example

```<code>var table = $('#example').DataTable();

table.rows().every( function ( rowIdx, tableLoop, rowLoop ) {
this
    .child(
        $(
            '<tr>'+
                '<td><input type="button" value="new button"/></td>'+
            '</tr>'
        )
    )
    .show();
} );
</code>```

This is an example Code.Please Change as per your requirements.

ContentLicense: CC BY-SA 3.0

Body:
i want to add buttons for each row using ajax function...I code something but is not work well.. Buttons move out of the table and view all buttons in the bottom if the page.I want to add these buttons to datatables row...

I want to add abc buttons one by one to [object Object] feild using for loop

ajax and jquery cord

jsp cord

                    <jsp:include page="template/banner.jsp"/>

                    <%@include file="template/message.jsp" %>

                    <jsp:include page="template/header.jsp"/>

List of Applications

                        <input type="hidden" id="userName" value="${userID}"/>
                        <input type="hidden" id="recentView" value="1"/>

Search -
View Recent 50 Applications

                                    VIEW RECENT
                                    <select id="viewNumbers" name="viewNumbers">
                                        <option value="50">50</option>
                                        <option value="100">100</option>
                                        <option value="150">150</option>
                                        <option value="200">200</option>
                                        <option value="500">500</option>
                                        <option value="750">750</option>
                                        <option value="1000">1000</option>
                                    </select>
                                    APPLICATIONS

                                            SLSI Entry No
                                            Application Posted in
                                            SLS No and Unit
                                            Product Description
                                            Status

 <jsp:include page="template/footer.jsp"/>

help me someone

Body:
You can use rows().every() property of dataTable

i will show you one example

var table = $('#example').DataTable();

table.rows().every( function ( rowIdx, tableLoop, rowLoop ) {
this
    .child(
        $(
            '<tr>'+
                '<td><input type="button" value="new button"/></td>'+
            '</tr>'
        )
    )
    .show();
} );

This is an example Code.Please Change as per your requirements.


问:
AngularJS - highlight text of an existing pdf file in frontend/Browser
I have found the library

PDF creation

With this library it is possible to create different styles of pdf documents.
My question would be if there is a possibility to mark text (and maybe add a link to this marked text) of an existing pdf file with AngularJS?
Or is there any workaround to do this?

答:
The question is a bit too broad as is - not sure what you mean by "mark" - do you mean highlighted in some way or actually selected?

Anyhow, firstly to get to the correct page -- you can use fragment identifiers in hyperlinks to link to a specific page in a PDF via the page parameter. e.g.

```<code><a href="file.pdf#page=1">page 1</a>
<a href="file.pdf#page=2">page 2</a>
</code>```

If you want to highlight a specific section of a page, via a hyperlink, you can use the highlight parameter, note you must also set the page to use the highlight parameter. e.g.

```<code><a href="file.pdf#page=1&highlight=10,10,50,50">page 1 - highlight</a>
</code>```

The rectangle values are integers in a coordinate system where 0,0 represents the top left, and the values are given in the order lt, rt, top, btm.

One can also open a PDF file to a "Named Destination", that is a named section in the document via the nameddest parameter. e.g.

```<code><a href="file.pdf#nameddest=mysection">my section</a>
</code>```

This is great as it doesn't matter if pages are inserted, removed etc as the section will always be correctly linked.

You can read about Named Destinations here and also the various Parameters for Opening PDF Files

Body:
The question is a bit too broad as is - not sure what you mean by "mark" - do you mean highlighted in some way or actually selected?

Anyhow, firstly to get to the correct page -- you can use fragment identifiers in hyperlinks to link to a specific page in a PDF via the page parameter. e.g.

<a href="file.pdf#page=1">page 1</a>
<a href="file.pdf#page=2">page 2</a>

If you want to highlight a specific section of a page, via a hyperlink, you can use the highlight parameter, note you must also set the page to use the highlight parameter. e.g.

<a href="file.pdf#page=1&highlight=10,10,50,50">page 1 - highlight</a>

The rectangle values are integers in a coordinate system where 0,0 represents the top left, and the values are given in the order lt, rt, top, btm.

One can also open a PDF file to a "Named Destination", that is a named section in the document via the nameddest parameter. e.g.

<a href="file.pdf#nameddest=mysection">my section</a>

This is great as it doesn't matter if pages are inserted, removed etc as the section will always be correctly linked.

You can read about Named Destinations here and also the various Parameters for Opening PDF Files


问:
Swift array element map
I have array [[one, two, three, four]] and I want to convert array in [["one", "two"," three", "four"]] without using a loop in Swift 3.

I tried

```<code>let myArray = array.map { String($0) }
</code>```

But this is returning ["[one, two, three, four]"].

答:
In your case, you actually have two arrays.  You have an array OF arrays of whatever one, etc. are.

Try:

```<code>let result = array.map { $0.map { String($0) } }
</code>```

Title: Swift array element map

Body:
I have array [[one, two, three, four]] and I want to convert array in [["one", "two"," three", "four"]] without using a loop in Swift 3.

I tried

let myArray = array.map { String($0) }

But this is returning ["[one, two, three, four]"].

Body:
In your case, you actually have two arrays.  You have an array OF arrays of whatever one, etc. are.

Try:

let result = array.map { $0.map { String($0) } }


问:
Why does points.sort(function(a, b){return a-b}); return -1, 0 or 1?
My difficulty here could be my mathematical illiteracy, but I was trying to sort some numbers in a JavaScript array and this is the solution I found online. It does indeed work, but my question is why?! I would really like to understand this piece of code properly.

The site, W3 Schools says:

You can fix this by providing a function that returns -1, 0, or 1:

```<code>var points = [40, 100, 1, 5, 25, 10];

points.sort(function(a,b){return a-b});
</code>```

Why would only -1, 0 or 1 be returned? I have Googled, and return can return pretty much any value you want.

Again, if this is an incredibly dumb question I apologise.

答:
If Function(a, b) is less than 0, sort a to an index lower than b, i.e. a comes first.

If Function(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements.

Note: the ECMAscript standard does not guarantee this behaviour, and
  thus not all browsers (e.g. Mozilla versions dating back to at least
  2003) respect this.

If Function(a, b) is greater than 0, sort b to an index lower than a, i.e. b comes first.
 Function(a, b) must always return the same value when given a specific pair of elements a and b as its two arguments. If inconsistent results are returned then the sort order is undefined.

Body:
My difficulty here could be my mathematical illiteracy, but I was trying to sort some numbers in a JavaScript array and this is the solution I found online. It does indeed work, but my question is why?! I would really like to understand this piece of code properly.

The site, W3 Schools says:

You can fix this by providing a function that returns -1, 0, or 1:

var points = [40, 100, 1, 5, 25, 10];

points.sort(function(a,b){return a-b});

Why would only -1, 0 or 1 be returned? I have Googled, and return can return pretty much any value you want.

Again, if this is an incredibly dumb question I apologise.


答: Array([[one, two, three, four]][0].map({String($0)}))

Title: Swift array element map


问:
Reflection + AOP - advice not intercepted when calling method via invoke
Via Reflection:

```<code>Class c = Class.forName("mypackage.DiodeService");
Method m = c.getDeclaredMethod("blink");
Object t = c.newInstance();
Object o = m.invoke(t);
</code>```

Method from DiodeService is invoked:

```<code>@ValueGreaterThan
public void blink(){
    log.info("Diode service: blink()");
}
</code>```

On the annotation @ValueGreaterThan is listening aspect:

```<code>@Around(value = "mypackage.CommonJoinPointConfig.valueGreaterThanAspect())") public void around(ProceedingJoinPoint joinPoint) throws Throwable {
    log.info("Value greater than aspect {}", joinPoint); }
</code>```

BUT: The around advice is never intercepted, when calling method by "invoke".

Around advice is intercepted normally, when calling by diodeService.blink()

Please, any ideas?

答:
The Spring AOP is based on runtime weaving due to the proxy-based nature of the Spring framework. This means the target bean is a Spring-managed bean. The bean is turned into a proxy during Spring runtime.

In the case where the DiodeService is a Spring proxy (managed by Spring), the Spring AOP will work normally as intended, i.e., the advice will be intercepted for any calls to blink.

The advice around blink will never be intercepted if DiodeService is instantiated directly and not via Spring. This is the case when you are instantiating DiodeService by calling newInstance,

Object t = c.newInstance()

Body:
Via Reflection:

Class c = Class.forName("mypackage.DiodeService");
Method m = c.getDeclaredMethod("blink");
Object t = c.newInstance();
Object o = m.invoke(t);

Method from DiodeService is invoked:

@ValueGreaterThan
public void blink(){
    log.info("Diode service: blink()");
}

On the annotation @ValueGreaterThan is listening aspect:

@Around(value = "mypackage.CommonJoinPointConfig.valueGreaterThanAspect())") public void around(ProceedingJoinPoint joinPoint) throws Throwable {
    log.info("Value greater than aspect {}", joinPoint); }

BUT: The around advice is never intercepted, when calling method by "invoke".

Around advice is intercepted normally, when calling by diodeService.blink()

Please, any ideas?


问:
Selecting index of tabBarController and passing data
I want to select the UIViewController at index 0 of my tabbarcontroller while passing data to it. It seems I am accessing the UINavigationController instead. Anyone know why this occurs?

```<code>SearchViewController *search = (SearchViewController *)[self.tabBarController.viewControllers objectAtIndex:0];
[search initWithText:@"This is a test"];

[[self.tabBarController.viewControllers objectAtIndex:1] pushViewController:search animated:NO];
</code>```

// Also receive the error using this:

```<code>self.tabBarController.selectedViewController = search;
</code>```

Error:

```<code>-[UINavigationController initWithText:]: unrecognized selector sent to instance
</code>```

答:
Wow, now I feel silly. This worked.</p>

```<code>UINavigationController *navController = [self.tabBarController.viewControllers objectAtIndex:0];
SearchViewController *search = [navController.viewControllers objectAtIndex:0];
[search initWithText:@"This is a test"];
self.tabBarController.selectedViewController = navController;
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I want to select the UIViewController at index 0 of my tabbarcontroller while passing data to it. It seems I am accessing the UINavigationController instead. Anyone know why this occurs?

SearchViewController *search = (SearchViewController *)[self.tabBarController.viewControllers objectAtIndex:0];
[search initWithText:@"This is a test"];

[[self.tabBarController.viewControllers objectAtIndex:1] pushViewController:search animated:NO];

// Also receive the error using this:

self.tabBarController.selectedViewController = search;

Error:

-[UINavigationController initWithText:]: unrecognized selector sent to instance

Body:
Wow, now I feel silly. This worked.

UINavigationController *navController = [self.tabBarController.viewControllers objectAtIndex:0];
SearchViewController *search = [navController.viewControllers objectAtIndex:0];
[search initWithText:@"This is a test"];
self.tabBarController.selectedViewController = navController;


问:
Consolidate / Manipulate array of objects
I have an array of objects like the following:

```<code>[{
  animal: "cat",
  dateString: "2017-01-03"
},{
  animal: "dog",
  dateString: "2017-02-05"
},{
  animal: "cat",
  dateString: "2017-03-04"
}]
</code>```

and I'd like to create a new array that looks like:

```<code>[{
  animal: "cat",
  values: [
    "2017-01-03",
    "2017-03-04"
  ]
},{
  animal: "dog",
  values: [
    "2017-02-05"
  ]
}]
</code>```

How can I consolidate the individual object properties into an array of values?

答:
We can simply iterate the array and build a result by mapping each animal to and object that contains its properties, e.g. {'cat': {'animal': 'cat', 'values': ["2017-01-03"]}}. When we're done, we'll extract only the values:

const arr = [{
  animal: "cat",
  dateString: "2017-01-03"
},{
  animal: "dog",
  dateString: "2017-02-05"
},{
  animal: "cat",
  dateString: "2017-03-04"
}]

let res=  {}
arr.forEach(obj => {
  if (res[obj.animal]) {
    res[obj.animal].values.push(obj.dateString)
  } else {
    res[obj.animal] = {animal: obj.animal, values: [obj.dateString]}
  }
})

res = Object.values(res)
console.log(res)```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I have an array of objects like the following:

[{
  animal: "cat",
  dateString: "2017-01-03"
},{
  animal: "dog",
  dateString: "2017-02-05"
},{
  animal: "cat",
  dateString: "2017-03-04"
}]

and I'd like to create a new array that looks like:

[{
  animal: "cat",
  values: [
    "2017-01-03",
    "2017-03-04"
  ]
},{
  animal: "dog",
  values: [
    "2017-02-05"
  ]
}]

How can I consolidate the individual object properties into an array of values?

Body:
We can simply iterate the array and build a result by mapping each animal to and object that contains its properties, e.g. {'cat': {'animal': 'cat', 'values': ["2017-01-03"]}}. When we're done, we'll extract only the values:

const arr = [{
  animal: "cat",
  dateString: "2017-01-03"
},{
  animal: "dog",
  dateString: "2017-02-05"
},{
  animal: "cat",
  dateString: "2017-03-04"
}]

let res=  {}
arr.forEach(obj => {
  if (res[obj.animal]) {
    res[obj.animal].values.push(obj.dateString)
  } else {
    res[obj.animal] = {animal: obj.animal, values: [obj.dateString]}
  }
})

res = Object.values(res)
console.log(res)

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Create panel with two columns
I am trying to create a template that has two columns in a panel. I am using plainBootstrap v3.3.7. Below you can find what I tried:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

Overview

                    #

                    Product

                    Payment Taken

                    Status

                    1

                    TB - Monthly

                    01/04/2012

                    Default

                  Section 1

                  Section 2

                    I'm in Section 1.

                    Howdy, I'm in Section 2.

```

However, my panel look like the following on my screen:

As you can see, in my panel the two columns inside overlap.

Any suggestions why my table and the section overlap so much?

I appreciate your replies!

答:
Because you are wrapping a table which is by default not responsive with .col-md-2 which is a responsive class.

So you have to wrap it with .table-responsive ( a bootstrap class for making tables responsive ), check the updated snippet:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

Overview

                                            #

                                            Product

                                            Payment Taken

                                            Status

                                            1

                                            TB - Monthly

                                            01/04/2012

                                            Default

                                    Section 1

                                    Section 2

                                        I'm in Section 1.

                                        Howdy, I'm in Section 2.

```

Hope this helps :)

Title: Create panel with two columns

Body:
I am trying to create a template that has two columns in a panel. I am using plainBootstrap v3.3.7. Below you can find what I tried:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

Overview

                    #

                    Product

                    Payment Taken

                    Status

                    1

                    TB - Monthly

                    01/04/2012

                    Default

                  Section 1

                  Section 2

                    I'm in Section 1.

                    Howdy, I'm in Section 2.

However, my panel look like the following on my screen:

As you can see, in my panel the two columns inside overlap.

Any suggestions why my table and the section overlap so much?

I appreciate your replies!

Body:
Because you are wrapping a table which is by default not responsive with .col-md-2 which is a responsive class.

So you have to wrap it with .table-responsive ( a bootstrap class for making tables responsive ), check the updated snippet:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div class="container">
    <div class="row">
        <div class="col-md-12">
            <div class="panel panel-default">
                <div class="panel-heading">Overview
                </div>
                <div class="panel-body">
                </div>
                <div class="container-fluid">
                    <div class="col-md-2">
                        <div class="table-responsive">
                            <table class="table">
                                <thead>
                                    <tr>
                                        <th>
                                            #
                                        </th>
                                        <th>
                                            Product
                                        </th>
                                        <th>
                                            Payment Taken
                                        </th>
                                        <th>
                                            Status
                                        </th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <td>
                                            1
                                        </td>
                                        <td>
                                            TB - Monthly
                                        </td>
                                        <td>
                                            01/04/2012
                                        </td>
                                        <td>
                                            Default
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                    <div class="col-md-10">
                        <div class="tabbable" id="tabs-305570">
                            <ul class="nav nav-tabs">
                                <li class="active">
                                    <a href="#panel-495769" data-toggle="tab">Section 1
                      </a>
                                </li>
                                <li>
                                    <a href="#panel-207616" data-toggle="tab">Section 2
                      </a>
                                </li>
                            </ul>
                            <div class="tab-content">
                                <div class="tab-pane active" id="panel-495769">
                                    <p>
                                        I'm in Section 1.
                                    </p>
                                </div>
                                <div class="tab-pane" id="panel-207616">
                                    <p>
                                        Howdy, I'm in Section 2.
                                    </p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

Hope this helps :)


问:
Join two Tables, ignore records from first table if exists in second
How to join to tables, if I prefer to get records only from the second table? If no second exists, take record the of the first table.

```<code>Table A         Table B         Result
pid,name,type   pid,name,type   pid,name,type
1,Anna,null     1,Anna,100      "1,Anna,100"
2,Bea,null      -               "2,Bea,Null"
3,Caro,null     3,Caro,100      "3,Caro,100"
                3,Caro,200      "3,Caro,200"
</code>```

Edit: I tried to improve my example table.

答:
```<code>SELECT
   ISNULL(A.column1, B.column1),  --perhaps name
   ISNULL(A.column2, B.column2)  --perhaps id
FROM
   TableA A
   FULL OUTER JOIN
   TableB B ON A.column1 = B.column1  --assume name is matching column
</code>```

Edit, I'm assuming you'd have no row in tableA, and "Dave, 6" in tableB. Otherwise, Cybernate's left join is enough

Body:
How to join to tables, if I prefer to get records only from the second table? If no second exists, take record the of the first table.

Table A         Table B         Result
pid,name,type   pid,name,type   pid,name,type
1,Anna,null     1,Anna,100      "1,Anna,100"
2,Bea,null      -               "2,Bea,Null"
3,Caro,null     3,Caro,100      "3,Caro,100"
                3,Caro,200      "3,Caro,200"

Edit: I tried to improve my example table.

Body:
SELECT
   ISNULL(A.column1, B.column1),  --perhaps name
   ISNULL(A.column2, B.column2)  --perhaps id
FROM
   TableA A
   FULL OUTER JOIN
   TableB B ON A.column1 = B.column1  --assume name is matching column

Edit, I'm assuming you'd have no row in tableA, and "Dave, 6" in tableB. Otherwise, Cybernate's left join is enough


问:
Issue in Realm List to [Model] in swift
I have two model classes AlertRSM and AlertRSMList

```<code>class AlertRSM : Object{

    var alertType : String?
    var alertTypeValue : String?
    var period : String?
    var colorValue : String?
    var tableName : String?

    convenience init(dict:Dictionary<String,Any>) {
        self.init()
        if let _alertType = dict["AlertType"] as? String {
            alertType = String(_alertType)
        }
        if let _alertTypeValue = dict["AlertTypeValue"] as? Double {
            alertTypeValue = String(_alertTypeValue)
        }
        if let _period = dict["Period"] as? String {
            period = _period
        }
        if let _colorValue = dict["ColorValue"] as? String {
            switch _colorValue {
                case "G":
                    self.colorValue = "008000"
                case "R":
                    self.colorValue = "FF0000"
                case "Y":
                    self.colorValue = "FFFF00"
            default: break
            }
        }
        if let _tableName = dict["TableName"] as? String {
            tableName = _tableName
        }
    }

    static func modelArrayFromDictionaryArray(dictArray : [Dictionary<String,Any>]) -> [AlertRSM] {
        var array = [AlertRSM]()

        for item in dictArray {
            array.append(AlertRSM(dict: item))
        }
        return array
    }
}

class AlertRSMList: Object {
    dynamic var companyAlt_Key :String?
    dynamic var dbEntryDate :String?

    var arrayOfAlertRSM = List<AlertRSM>()

    convenience init(dict:[AlertRSM]) {
        self.init()
        for item in dict {
            arrayOfAlertRSM.append(item)
        }
        dbEntryDate = CommonMethods.getDateInString()
        companyAlt_Key = STATIC_STORAGE.Company_Alt_Key
    }

    override static func primaryKey() -> String? {
        return "companyAlt_Key"
    }
}
</code>```

In my view controller I am getting data from Realm Database

```<code>let _toDaysAlertRSM = realm.objects(AlertRSMList.self)
let alertRSMList : [AlertRSMList] = _toDaysAlertRSM.filter { alertRSM in
    return alertRSM.dbEntryDate == CommonMethods.getDateInString()
}
</code>```

Now I print the alertRSMList

```<code>print(alertRSMList)
</code>```

the output is

```<code>[AlertRSMList {
companyAlt_Key = 3;
dbEntryDate = 02/12/2017;
arrayOfAlertRSM = RLMArray <0x6000000f1f80> (
    [0] AlertRSM {
        alertType = External;
        alertTypeValue = 14.77;
        period = M;
        colorValue = 008000;
        tableName = Alert;
    },
    [1] AlertRSM {
        alertType = External;
        alertTypeValue = 15.64;
        period = Q;
        colorValue = 008000;
        tableName = Alert;
    },
    [2] AlertRSM {
        alertType = Financial;
        alertTypeValue = 40.78;
        period = Q;
        colorValue = 008000;
        tableName = Alert;
    },
    [3] AlertRSM {
        alertType = Financial;
        alertTypeValue = 40.78;
        period = M;
        colorValue = 008000;
        tableName = Alert;
    },
    [4] AlertRSM {
        alertType = Financial;
        alertTypeValue = 40.78;
        period = W;
        colorValue = 008000;
        tableName = Alert;
    },
    [5] AlertRSM {
        alertType = External;
        alertTypeValue = 47.62;
        period = W;
        colorValue = FFFF00;
        tableName = Alert;
    },
    [6] AlertRSM {
        alertType = Statistical;
        alertTypeValue = 54.13;
        period = W;
        colorValue = FFFF00;
        tableName = Alert;
    },
    [7] AlertRSM {
        alertType = Statistical;
        alertTypeValue = 54.13;
        period = M;
        colorValue = FFFF00;
        tableName = Alert;
    },
    [8] AlertRSM {
        alertType = Statistical;
        alertTypeValue = 54.13;
        period = Q;
        colorValue = FFFF00;
        tableName = Alert;
    },
    [9] AlertRSM {
        alertType = NonFinancial;
        alertTypeValue = 78.76;
        period = W;
        colorValue = FF0000;
        tableName = Alert;
    },
    [10] AlertRSM {
        alertType = NonFinancial;
        alertTypeValue = 78.76;
        period = M;
        colorValue = FF0000;
        tableName = Alert;
    },
    [11] AlertRSM {
        alertType = NonFinancial;
        alertTypeValue = 78.76;
        period = Q;
        colorValue = FF0000;
        tableName = Alert;
    }
);
}]
(lldb)
</code>```

and print the AlertRSM array

```<code>print(alertRSMList[0].arrayOfAlertRSM)
</code>```

The output is

```<code>List<AlertRSM> <0x6080000f3280> (
[0] AlertRSM {
    alertType = External;
    alertTypeValue = 14.77;
    period = M;
    colorValue = 008000;
    tableName = Alert;
},
[1] AlertRSM {
    alertType = External;
    alertTypeValue = 15.64;
    period = Q;
    colorValue = 008000;
    tableName = Alert;
},
[2] AlertRSM {
    alertType = Financial;
    alertTypeValue = 40.78;
    period = Q;
    colorValue = 008000;
    tableName = Alert;
},
[3] AlertRSM {
    alertType = Financial;
    alertTypeValue = 40.78;
    period = M;
    colorValue = 008000;
    tableName = Alert;
},
[4] AlertRSM {
    alertType = Financial;
    alertTypeValue = 40.78;
    period = W;
    colorValue = 008000;
    tableName = Alert;
},
[5] AlertRSM {
    alertType = External;
    alertTypeValue = 47.62;
    period = W;
    colorValue = FFFF00;
    tableName = Alert;
},
[6] AlertRSM {
    alertType = Statistical;
    alertTypeValue = 54.13;
    period = W;
    colorValue = FFFF00;
    tableName = Alert;
},
[7] AlertRSM {
    alertType = Statistical;
    alertTypeValue = 54.13;
    period = M;
    colorValue = FFFF00;
    tableName = Alert;
},
[8] AlertRSM {
    alertType = Statistical;
    alertTypeValue = 54.13;
    period = Q;
    colorValue = FFFF00;
    tableName = Alert;
},
[9] AlertRSM {
    alertType = NonFinancial;
    alertTypeValue = 78.76;
    period = W;
    colorValue = FF0000;
    tableName = Alert;
},
[10] AlertRSM {
    alertType = NonFinancial;
    alertTypeValue = 78.76;
    period = M;
    colorValue = FF0000;
    tableName = Alert;
},
[11] AlertRSM {
    alertType = NonFinancial;
    alertTypeValue = 78.76;
    period = Q;
    colorValue = FF0000;
    tableName = Alert;
}
)
(lldb)
</code>```

Now the problem statement is if I want to print AlertRSM's each property, I am getting nil

```<code>print(alertRSMList[0].arrayOfAlertRSM[0].alertType)
</code>```

Output is nil where as it contains value "External"

```<code>nil
(lldb)
</code>```

If I loop through the AlertList

```<code>for item in alertRSMList[0].arrayOfAlertRSM[0] {
    print(item.alertType)
    print(item.alertTypeValue)
    print(item.period)
    print(item.colorValue)
    print(item.tableName)
}
</code>```

All prints nil

I am also getting warning on this line

```<code>print(alertRSMList[0].arrayOfAlertRSM[0].alertType)
// Warning
// Expression implicitly coerced from 'String?'to Any
</code>```

The continue code snippet is

```<code>let _toDaysAlertRSM = realm.objects(AlertRSMList.self)
let alertRSMList : [AlertRSMList] = _toDaysAlertRSM.filter { alertRSM in
    return alertRSM.dbEntryDate == CommonMethods.getDateInString()
}

print(alertRSMList)
print(alertRSMList[0].arrayOfAlertRSM)
print(alertRSMList[0].arrayOfAlertRSM[0].alertType)
</code>```

So please help me to get the values of

```<code>alertRSMList[0].arrayOfAlertRSM[0].alertType//alertTypeValue//period
</code>```

答: Specifiers dynamicand @objc are required by realm for member fields. Does it help to add these fields to AlertRSM class?

Title: Issue in Realm List to [Model] in swift

Body:
I have two model classes AlertRSM and AlertRSMList

class AlertRSM : Object{

    var alertType : String?
    var alertTypeValue : String?
    var period : String?
    var colorValue : String?
    var tableName : String?

    convenience init(dict:Dictionary<String,Any>) {
        self.init()
        if let _alertType = dict["AlertType"] as? String {
            alertType = String(_alertType)
        }
        if let _alertTypeValue = dict["AlertTypeValue"] as? Double {
            alertTypeValue = String(_alertTypeValue)
        }
        if let _period = dict["Period"] as? String {
            period = _period
        }
        if let _colorValue = dict["ColorValue"] as? String {
            switch _colorValue {
                case "G":
                    self.colorValue = "008000"
                case "R":
                    self.colorValue = "FF0000"
                case "Y":
                    self.colorValue = "FFFF00"
            default: break
            }
        }
        if let _tableName = dict["TableName"] as? String {
            tableName = _tableName
        }
    }

    static func modelArrayFromDictionaryArray(dictArray : [Dictionary<String,Any>]) -> [AlertRSM] {
        var array = [AlertRSM]()

        for item in dictArray {
            array.append(AlertRSM(dict: item))
        }
        return array
    }
}

class AlertRSMList: Object {
    dynamic var companyAlt_Key :String?
    dynamic var dbEntryDate :String?

    var arrayOfAlertRSM = List<AlertRSM>()

    convenience init(dict:[AlertRSM]) {
        self.init()
        for item in dict {
            arrayOfAlertRSM.append(item)
        }
        dbEntryDate = CommonMethods.getDateInString()
        companyAlt_Key = STATIC_STORAGE.Company_Alt_Key
    }

    override static func primaryKey() -> String? {
        return "companyAlt_Key"
    }
}

In my view controller I am getting data from Realm Database

let _toDaysAlertRSM = realm.objects(AlertRSMList.self)
let alertRSMList : [AlertRSMList] = _toDaysAlertRSM.filter { alertRSM in
    return alertRSM.dbEntryDate == CommonMethods.getDateInString()
}

Now I print the alertRSMList

print(alertRSMList)

the output is

[AlertRSMList {
companyAlt_Key = 3;
dbEntryDate = 02/12/2017;
arrayOfAlertRSM = RLMArray <0x6000000f1f80> (
    [0] AlertRSM {
        alertType = External;
        alertTypeValue = 14.77;
        period = M;
        colorValue = 008000;
        tableName = Alert;
    },
    [1] AlertRSM {
        alertType = External;
        alertTypeValue = 15.64;
        period = Q;
        colorValue = 008000;
        tableName = Alert;
    },
    [2] AlertRSM {
        alertType = Financial;
        alertTypeValue = 40.78;
        period = Q;
        colorValue = 008000;
        tableName = Alert;
    },
    [3] AlertRSM {
        alertType = Financial;
        alertTypeValue = 40.78;
        period = M;
        colorValue = 008000;
        tableName = Alert;
    },
    [4] AlertRSM {
        alertType = Financial;
        alertTypeValue = 40.78;
        period = W;
        colorValue = 008000;
        tableName = Alert;
    },
    [5] AlertRSM {
        alertType = External;
        alertTypeValue = 47.62;
        period = W;
        colorValue = FFFF00;
        tableName = Alert;
    },
    [6] AlertRSM {
        alertType = Statistical;
        alertTypeValue = 54.13;
        period = W;
        colorValue = FFFF00;
        tableName = Alert;
    },
    [7] AlertRSM {
        alertType = Statistical;
        alertTypeValue = 54.13;
        period = M;
        colorValue = FFFF00;
        tableName = Alert;
    },
    [8] AlertRSM {
        alertType = Statistical;
        alertTypeValue = 54.13;
        period = Q;
        colorValue = FFFF00;
        tableName = Alert;
    },
    [9] AlertRSM {
        alertType = NonFinancial;
        alertTypeValue = 78.76;
        period = W;
        colorValue = FF0000;
        tableName = Alert;
    },
    [10] AlertRSM {
        alertType = NonFinancial;
        alertTypeValue = 78.76;
        period = M;
        colorValue = FF0000;
        tableName = Alert;
    },
    [11] AlertRSM {
        alertType = NonFinancial;
        alertTypeValue = 78.76;
        period = Q;
        colorValue = FF0000;
        tableName = Alert;
    }
);
}]
(lldb)

and print the AlertRSM array

print(alertRSMList[0].arrayOfAlertRSM)

The output is

List<AlertRSM> <0x6080000f3280> (
[0] AlertRSM {
    alertType = External;
    alertTypeValue = 14.77;
    period = M;
    colorValue = 008000;
    tableName = Alert;
},
[1] AlertRSM {
    alertType = External;
    alertTypeValue = 15.64;
    period = Q;
    colorValue = 008000;
    tableName = Alert;
},
[2] AlertRSM {
    alertType = Financial;
    alertTypeValue = 40.78;
    period = Q;
    colorValue = 008000;
    tableName = Alert;
},
[3] AlertRSM {
    alertType = Financial;
    alertTypeValue = 40.78;
    period = M;
    colorValue = 008000;
    tableName = Alert;
},
[4] AlertRSM {
    alertType = Financial;
    alertTypeValue = 40.78;
    period = W;
    colorValue = 008000;
    tableName = Alert;
},
[5] AlertRSM {
    alertType = External;
    alertTypeValue = 47.62;
    period = W;
    colorValue = FFFF00;
    tableName = Alert;
},
[6] AlertRSM {
    alertType = Statistical;
    alertTypeValue = 54.13;
    period = W;
    colorValue = FFFF00;
    tableName = Alert;
},
[7] AlertRSM {
    alertType = Statistical;
    alertTypeValue = 54.13;
    period = M;
    colorValue = FFFF00;
    tableName = Alert;
},
[8] AlertRSM {
    alertType = Statistical;
    alertTypeValue = 54.13;
    period = Q;
    colorValue = FFFF00;
    tableName = Alert;
},
[9] AlertRSM {
    alertType = NonFinancial;
    alertTypeValue = 78.76;
    period = W;
    colorValue = FF0000;
    tableName = Alert;
},
[10] AlertRSM {
    alertType = NonFinancial;
    alertTypeValue = 78.76;
    period = M;
    colorValue = FF0000;
    tableName = Alert;
},
[11] AlertRSM {
    alertType = NonFinancial;
    alertTypeValue = 78.76;
    period = Q;
    colorValue = FF0000;
    tableName = Alert;
}
)
(lldb)

Now the problem statement is if I want to print AlertRSM's each property, I am getting nil

print(alertRSMList[0].arrayOfAlertRSM[0].alertType)

Output is nil where as it contains value "External"

nil
(lldb)

If I loop through the AlertList

for item in alertRSMList[0].arrayOfAlertRSM[0] {
    print(item.alertType)
    print(item.alertTypeValue)
    print(item.period)
    print(item.colorValue)
    print(item.tableName)
}

All prints nil

I am also getting warning on this line

print(alertRSMList[0].arrayOfAlertRSM[0].alertType)
// Warning
// Expression implicitly coerced from 'String?'to Any

The continue code snippet is

let _toDaysAlertRSM = realm.objects(AlertRSMList.self)
let alertRSMList : [AlertRSMList] = _toDaysAlertRSM.filter { alertRSM in
    return alertRSM.dbEntryDate == CommonMethods.getDateInString()
}

print(alertRSMList)
print(alertRSMList[0].arrayOfAlertRSM)
print(alertRSMList[0].arrayOfAlertRSM[0].alertType)

So please help me to get the values of

alertRSMList[0].arrayOfAlertRSM[0].alertType//alertTypeValue//period


问:
Weird acting for loop
My for loop is acting weird. I want to get a name of members in a team but instead of it I am getting only one last name triple. Can you please say me where can be the problem?

```<code>class Animal:
    def __init__(self, name):
        self.name = name

class Team:
    def __init__(self, name):
        self.name = name
        self.members = []

    def add_member(self, member):
        self.member = member
        self.members.append(team.member)

def print_team(team):
    list_members= []
    for member in team.members:
        list_members.append(team.member.name)

    print (list_members)

team = Team('Wolves')
team.add_member(Animal('Josh'))
team.add_member(Animal('Janette'))
team.add_member(Animal('Peter'))
print_team(team)
</code>```

I am getting -> Peter, Peter, Peter

I want to get -> Josh, Janette, Peter

答:
You are using team.member.name in print_team. it always takes last initialize value of team.member.

You can also sort your function,
There is no need use loop in print_team().
just save member.name in add_memeber function.

```<code>    class Animal:
        def __init__(self, name):
            self.name = name

    class Team:
        def __init__(self, name):
            self.name = name
            self.members = []

        def add_member(self, member):
            self.member = member
            self.members.append(member.name)

    def print_team(team):
        print team.members

    team = Team('Wolves')
    team.add_member(Animal('Josh'))
    team.add_member(Animal('Janette'))
    team.add_member(Animal('Peter'))
    print_team(team)
</code>```

Title: Weird acting for loop

Body:
My for loop is acting weird. I want to get a name of members in a team but instead of it I am getting only one last name triple. Can you please say me where can be the problem?

class Animal:
    def __init__(self, name):
        self.name = name

class Team:
    def __init__(self, name):
        self.name = name
        self.members = []

    def add_member(self, member):
        self.member = member
        self.members.append(team.member)

def print_team(team):
    list_members= []
    for member in team.members:
        list_members.append(team.member.name)

    print (list_members)

team = Team('Wolves')
team.add_member(Animal('Josh'))
team.add_member(Animal('Janette'))
team.add_member(Animal('Peter'))
print_team(team)

I am getting -> Peter, Peter, Peter

I want to get -> Josh, Janette, Peter

Body:
You are using team.member.name in print_team. it always takes last initialize value of team.member.

You can also sort your function,
There is no need use loop in print_team().
just save member.name in add_memeber function.

    class Animal:
        def __init__(self, name):
            self.name = name

    class Team:
        def __init__(self, name):
            self.name = name
            self.members = []

        def add_member(self, member):
            self.member = member
            self.members.append(member.name)

    def print_team(team):
        print team.members

    team = Team('Wolves')
    team.add_member(Animal('Josh'))
    team.add_member(Animal('Janette'))
    team.add_member(Animal('Peter'))
    print_team(team)


问:
How to re-index multiple Elastic Search types into a new index with a single type?
I am upgrading from ElasticSearch 5.6 to 6.0 and I have standard logstash-* indexes. In those indexes I have multiple (doc) types "attachmentsDbStats" and "attachmentsFileStats" which have the same schema. The only difference is the value of _type and type. I have created a new index attachments-* where the type is "attachement" and I want to reindex documents of both types into the new index. Obviously b/c of the new single type restriction in 6.0, both need to have the same type. I have update all of the documents in my old index such that the "type" field has a value "attachment." When I run reindex I am not able to upload the documents due to the restriction on the single type. I have attempted to update the _type field in the old indexes but that is immutable. Any ideas how to reindex and convert the type during the conversion?</p>

答:
Something like this should get you started:

```<code>POST _reindex
{
  "source": {
    "index": "logstash-*"
  },
  "dest": {
    "index": "attachments-*"
  },
  "script": {
    "source": """
    ctx._id = ctx._type + "-" + ctx._id;
    ctx._source.type = ctx._type;
    ctx._type = "attachement";
"""
  }
}
</code>```

Combining _type and _id into the new _id field, so it's definitely unique. Move the _type field to a custom type. And set the _type to "attachement" (note that the convention used by Elastic uses "doc" as the default type, but you can pick whatever you want as long as there is a single type).

Body:
Something like this should get you started:

POST _reindex
{
  "source": {
    "index": "logstash-*"
  },
  "dest": {
    "index": "attachments-*"
  },
  "script": {
    "source": """
    ctx._id = ctx._type + "-" + ctx._id;
    ctx._source.type = ctx._type;
    ctx._type = "attachement";
"""
  }
}

Combining _type and _id into the new _id field, so it's definitely unique. Move the _type field to a custom type. And set the _type to "attachement" (note that the convention used by Elastic uses "doc" as the default type, but you can pick whatever you want as long as there is a single type).


问:
Get a specific array element using Projection of MongoDB .Net Driver
I have some classes.

```<code>public class MyClass
{
  public string Id {get;set;}
  public List<MyElement> MyList {get;set;} = new List<MyElement>();

  //Other extra fields
}
public class MyElement
{
  public string Text {get;set;}
  public string AnotherField {get;set;}
}
</code>```

Here is my sample document of MyClass:

```<code>{
  "_id": "1",
  "MyList": [{
    "text":"Element 0"
  },{
    "text":"Element 1"
  }]
}
</code>```

Now I want to retrieve only Element 0. I wrote the following code using Projection:

```<code>Expression<Func<MyClass, MyElement>> getElementZero = (c => c.MyList[0]);
Expression<Func<MyClass, List<MyElement>>> getList = (c => c.MyList);
FilterDefinition<MyClass> filter = Builders<MyClass>.Filter.Eq(p => p.Id, "1");
//This is good
List<MyElement> myList = mongoCollection.Find(filter).Project(getList).First();

//However, myElement is null after this projection
MyElement myElement = mongoCollection.Find(filter).Project(getElementZero).First();
</code>```

Anybody know why? And how can I get a specific array element using the index of that element?

Update:

I did some experiment, and find out the following things:

If only the first element of an array is wanted, the following will work.

```<code>//this will work
MyElement myElement = mongoCollection.Find(filter).Project(c => c.MyList.First()).First();
//this is not going to work
MyElement myElement = mongoCollection.Find(filter).Project(c => c.MyList.GetElementAt(0)).First();
</code>```

If I explicitly write a function, it will work:

```<code>public MyElement GetElementAt(MyClass c, int index)
{
  return c.MyList[index];
}
//this will work
MyElement myElement = mongoCollection.Find(filter).Project(c => GetElementAt(c, someIndex)).First();
</code>```

答:
In Mongodb console(javaScript), you can achieve this using:

```<code>db.foo.find({_id:"1"}).map(function(u){return u.MyList[0].text})
</code>```

You can try converting this in C# there must be some functions.

Body:
I have some classes.

public class MyClass
{
  public string Id {get;set;}
  public List<MyElement> MyList {get;set;} = new List<MyElement>();

  //Other extra fields
}
public class MyElement
{
  public string Text {get;set;}
  public string AnotherField {get;set;}
}

Here is my sample document of MyClass:

{
  "_id": "1",
  "MyList": [{
    "text":"Element 0"
  },{
    "text":"Element 1"
  }]
}

Now I want to retrieve only Element 0. I wrote the following code using Projection:

Expression<Func<MyClass, MyElement>> getElementZero = (c => c.MyList[0]);
Expression<Func<MyClass, List<MyElement>>> getList = (c => c.MyList);
FilterDefinition<MyClass> filter = Builders<MyClass>.Filter.Eq(p => p.Id, "1");
//This is good
List<MyElement> myList = mongoCollection.Find(filter).Project(getList).First();

//However, myElement is null after this projection
MyElement myElement = mongoCollection.Find(filter).Project(getElementZero).First();

Anybody know why? And how can I get a specific array element using the index of that element?

Update:

I did some experiment, and find out the following things:

If only the first element of an array is wanted, the following will work.

//this will work
MyElement myElement = mongoCollection.Find(filter).Project(c => c.MyList.First()).First();
//this is not going to work
MyElement myElement = mongoCollection.Find(filter).Project(c => c.MyList.GetElementAt(0)).First();

If I explicitly write a function, it will work:

public MyElement GetElementAt(MyClass c, int index)
{
  return c.MyList[index];
}
//this will work
MyElement myElement = mongoCollection.Find(filter).Project(c => GetElementAt(c, someIndex)).First();

Body:
In Mongodb console(javaScript), you can achieve this using:

db.foo.find({_id:"1"}).map(function(u){return u.MyList[0].text})

You can try converting this in C# there must be some functions.


问:
Can anyone suggest me how to use carousel in angular2
I need to include angular2-carousel for the images present in the table. Can anyone help me to do this?

This is the HTML code I tried:

```<code>  <div class="row">
    <div class="col-md-12">
      <carousel>
        <img src="http://www.tripathihospital.com/images/hospital.jpg" style="margin:auto;">
          <div class="carousel-caption">
            <h3 style="background-color: transparent;color: white;">Slide {{index + 1}}</h3>
          </div>
       </carousel>
    </div>
  </div>
 </td>
</code>```

Console output:

```<code>Uncaught Error: Template parse errors:
'carousel' is not a known element:
1. If 'carousel' is an Angular component, then verify that it is part of this module.
</code>```

答:
It works fine check this Stackblitz example i created.

I think you are not installing the peer dependencies.

```<code>npm install @types/hammerjs
npm install hammerjs
</code>```

Body:
I need to include angular2-carousel for the images present in the table. Can anyone help me to do this?

This is the HTML code I tried:

      <carousel>

Slide {{index + 1}}

       </carousel>

Console output:

Uncaught Error: Template parse errors:
'carousel' is not a known element:
1. If 'carousel' is an Angular component, then verify that it is part of this module.

Body:
It works fine check this Stackblitz example i created.

I think you are not installing the peer dependencies.

npm install @types/hammerjs
npm install hammerjs


问:
What is an Enterprise architecture?
I am a web developer, I want to become software architect, and I learn everyday about it, but when I am learning software architecture I see TOGAF framework for enterprise architecture, I want to get solid understand in an enterprise architecture.

答:
If you want to be a software architect - aka Application Architect, then TOGAF is useful to know, but not necessary for you. Enterprise architects deal with things that impact the entire organisation, particularly things like Strategy & Planning. Organisational modelling, etc.

They can be sometimes involved as a governance role to ensure alignment with organisational design standards, or security standards. They can also sometimes be involved in setting organisational policy.

Either way - too many people assuming taking the "most senior looking" title will get them the best pay and the best life - this is not always true and an EA role is very very different to a software architect - even though they are both "Architects"

Now getting a solid understanding of Enterprise Archtiecture will be a challenge - because 1. its kind of undefined right now - or more accurately - there is around 460+ different models of what an Enterprise Architecture is - TOGAF only being one of them. 2. Most EAs like to get completely OCD around model definitions, and each one has a different OCD point of view exactly what they are - I should know, I'm one of them :)

One of the best general models I have found is DoDAF, but it sure isn't light bedtime reading. Wikipedia has a reasonably light definition though and it might be worth starting there if you haven't already

Title: What is an Enterprise architecture?


问:
How do I merge two csv files based on the words in a given list?
I have two csv files, each of them are in this format,

```<code>file1
zip     name    score
23431   david   12
23231   rob     45
33441   hary    23
98901   rgrg    55

file2
zip1    name1   score1
23433   david   12
23245   stel    45
33478   hary    23
98988   rob     55
12121   jass    33
</code>```

and I have a list that has the names, like this

```<code>lista = ['harry', 'rob', 'wine', 'david', 'jass']
</code>```

The final csv file should look like this:

```<code>name    zip     score       zip1     score1
harry   x       x           x           x
rob     23231   45          98988       55
wine    x       x           x           x
david   23431   12          23433       12
jass    x       x           12121       33
</code>```

that means, if any name from the list lies in either of the csv files, than we should include it in the new csv file along with its zip and score. Otherwise we should print 'x' in it.

This is what I have done so far:

```<code>import csv
with open('file1.csv', 'r') as input1, open('file2.csv', 'r') as input2, open('merge_final.csv', 'w') as output:
    writer = csv.writer(output)
    reader1 = csv.reader(input1)
    eader2 = csv.reader(input2)

    lista = ['harry', 'rob', 'wine', 'david', 'jass']
    writer.writerow(['name','zip','score','zip1','score'])

        for i in lista:
            for row in list(reader1):
                rev = row[1]
                if i in rev:
                    score = row[2]
                    zip = row[0]
                else:
                    score = 'x'
                    zip = 'x'
            for row in list(reader2):
                rev = row[1]
                if i in rev:
                    score1 = row[2]
                    zip1 = row[0]
                else:
                    score1 = 'x'
                    zip1 = 'x'
            writer.writerow([i, score, zip, score1, zip1])
</code>```

This code is not working as expected. This is the output I got using this code.

```<code>name    zip     score       zip1     score1
harry   x       x           x           x
rob     x      x            x            x
wine    x       x           x           x
david   x       x           x           x
jass    x       x           x           x
</code>```

Even thought there are many common words, only 'x' gets printed in the final merged csv file. I think the problem is with the loops. But, I don't seem to figure out the issue.

答:
Don't you think it would be better to read the two files into a single nested dictionary where the names would be the keys and the values would be dictionaries with keys 'zip,'zip1','score' and 'score1'?

```<code>    {'hary' :
        {'zip1':33478,
         'zip':33441 ,
         'score':23,
         'score1':23 }
    }
</code>```

Then iterate through the list and print 'x' for whatever the keys are not present

Body:
I have two csv files, each of them are in this format,

file1
zip     name    score
23431   david   12
23231   rob     45
33441   hary    23
98901   rgrg    55

file2
zip1    name1   score1
23433   david   12
23245   stel    45
33478   hary    23
98988   rob     55
12121   jass    33

and I have a list that has the names, like this

lista = ['harry', 'rob', 'wine', 'david', 'jass']

The final csv file should look like this:

name    zip     score       zip1     score1
harry   x       x           x           x
rob     23231   45          98988       55
wine    x       x           x           x
david   23431   12          23433       12
jass    x       x           12121       33

that means, if any name from the list lies in either of the csv files, than we should include it in the new csv file along with its zip and score. Otherwise we should print 'x' in it.

This is what I have done so far:

import csv
with open('file1.csv', 'r') as input1, open('file2.csv', 'r') as input2, open('merge_final.csv', 'w') as output:
    writer = csv.writer(output)
    reader1 = csv.reader(input1)
    eader2 = csv.reader(input2)

    lista = ['harry', 'rob', 'wine', 'david', 'jass']
    writer.writerow(['name','zip','score','zip1','score'])

        for i in lista:
            for row in list(reader1):
                rev = row[1]
                if i in rev:
                    score = row[2]
                    zip = row[0]
                else:
                    score = 'x'
                    zip = 'x'
            for row in list(reader2):
                rev = row[1]
                if i in rev:
                    score1 = row[2]
                    zip1 = row[0]
                else:
                    score1 = 'x'
                    zip1 = 'x'
            writer.writerow([i, score, zip, score1, zip1])

This code is not working as expected. This is the output I got using this code.

name    zip     score       zip1     score1
harry   x       x           x           x
rob     x      x            x            x
wine    x       x           x           x
david   x       x           x           x
jass    x       x           x           x

Even thought there are many common words, only 'x' gets printed in the final merged csv file. I think the problem is with the loops. But, I don't seem to figure out the issue.

Body:
Don't you think it would be better to read the two files into a single nested dictionary where the names would be the keys and the values would be dictionaries with keys 'zip,'zip1','score' and 'score1'?

    {'hary' :
        {'zip1':33478,
         'zip':33441 ,
         'score':23,
         'score1':23 }
    }

Then iterate through the list and print 'x' for whatever the keys are not present


问:
In MySQL, how to select data based on date?
I need to get record based on date but I got stuck.

```<code>rate  applicable_date

12        01/01/2001
13.5      01/05/2005
17.9      07/11/2017
</code>```

I need to get applicable rate based on applicable date. I used below SQL:

```<code>Select rate from ratetable where applicable_date <=$date;
</code>```

For $date = '12/02/2017';

It returns me 12

but for date 17/11/2017 it returns me all rates but I need only 17.9 latest one.

答:
```<code>select rate
from ratetable
where applicable_date <=$date
order by desc
limit 1;
</code>```

now it will return only 17.9

ContentLicense: CC BY-SA 4.0

Body:
I need to get record based on date but I got stuck.

rate  applicable_date

12        01/01/2001
13.5      01/05/2005
17.9      07/11/2017

I need to get applicable rate based on applicable date. I used below SQL:

Select rate from ratetable where applicable_date <=$date;

For $date = '12/02/2017';

It returns me 12

but for date 17/11/2017 it returns me all rates but I need only 17.9 latest one.

Body:
select rate
from ratetable
where applicable_date <=$date
order by desc
limit 1;

now it will return only 17.9


问:
gradle dependency version conflict
I have the following dependency script:

```<code>apply plugin: 'com.android.application'
apply plugin: 'com.google.protobuf'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"

    defaultConfig {
        applicationId "com.asdf.asdf"
        minSdkVersion 10
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    buildTypes.each {
        it.buildConfigField 'String', 'YOUTUBE_API_KEY', YoutubeApiKey
    }
}

protobuf {
    protoc {
        artifact = 'com.google.protobuf:protoc:3.0.0-beta-2'
    }
    plugins {
        grpc {
            artifact = 'io.grpc:protoc-gen-grpc-java:0.13.2'
        }
    }
    generateProtoTasks {
        all().each { task ->
            task.builtins {
                javanano {
                    option 'ignore_services=true'
                }
            }

            task.plugins {
                grpc {
                    option 'nano=true'
                }
            }
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.2.1'
    compile 'com.mcxiaoke.volley:library:1.0.19'
    compile 'com.android.support:design:23.2.1'
    compile 'com.android.support:support-v4:23.2.1'
    compile 'com.android.support:cardview-v7:23.2.1'
    compile 'com.android.support:support-annotations:23.2.1'
    compile 'com.android.support:customtabs:23.2.1'
    compile 'com.google.apis:google-api-services-youtube:v3-rev164-1.21.0'
    compile 'javax.annotation:javax.annotation-api:1.2'
    compile 'io.grpc:grpc-protobuf-nano:0.13.2'
    compile 'io.grpc:grpc-okhttp:0.13.2'
    compile 'io.grpc:grpc-stub:0.13.2'
    compile 'com.google.guava:guava:18.0'
}
</code>```

Though both the youtube library and the grpc library are dependent on the google guava library, they're reliant on different versions causing a conflict. Youtube is dependent on com.google.guava:guava-jdk5:17.0 and grpc on com.google.guava:guava:18.0.(Notice the artifact difference, if that is possibly relevant) The problem is grpc ends up trying to locate a method defined in youtube's version of guava when it only exists in in its own version of the dependency. How do I resolve this?

ERROR Message

```<code>FATAL EXCEPTION: SyncAdapterThread-1
    Process: com.asdf.asdf, PID: 4025
             java.lang.NoSuchMethodError: No static method directExecutor()Ljava/util/concurrent/Executor; in class Lcom/google/common/util/concurrent/MoreExecutors; or its super classes (declaration of 'com.google.common.util.concurrent.MoreExecutors' appears in /data/data/com.fentale.dalol/files/instant-run/dex/slice-guava-jdk5-17.0_a8ada10dcaf113cb6e3b4d3e5b46975833f8ae8f-classes.dex)
                at io.grpc.internal.ClientCallImpl.<init>(ClientCallImpl.java:100)
                at io.grpc.internal.ManagedChannelImpl$RealChannel.newCall(ManagedChannelImpl.java:320)
                at io.grpc.internal.ManagedChannelImpl.newCall(ManagedChannelImpl.java:299)
                at io.grpc.stub.ClientCalls.blockingUnaryCall(ClientCalls.java:130)
                at com.fentale.dalol.nano.DalolGrpc$DalolBlockingStub.topPosts(DalolGrpc.java:365)
</code>```

The method "directExecutor" is defined in guava-v18, but grpc tries to access it from the guava-jdk5.

答:
You have to edit project level build.gradle you have to

```<code>exclude module: 'guava-jdk5'
</code>```

inside dependencies. Please check attached screenshot for more details
If you are using firebase plugins add

```<code>classpath ('com.google.firebase:firebase-plugins:1.1.0') {
        exclude group: 'com.google.guava', module: 'guava-jdk5'
    }
</code>```

Title: gradle dependency version conflict

Body:
I have the following dependency script:

apply plugin: 'com.android.application'
apply plugin: 'com.google.protobuf'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"

    defaultConfig {
        applicationId "com.asdf.asdf"
        minSdkVersion 10
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    buildTypes.each {
        it.buildConfigField 'String', 'YOUTUBE_API_KEY', YoutubeApiKey
    }
}

protobuf {
    protoc {
        artifact = 'com.google.protobuf:protoc:3.0.0-beta-2'
    }
    plugins {
        grpc {
            artifact = 'io.grpc:protoc-gen-grpc-java:0.13.2'
        }
    }
    generateProtoTasks {
        all().each { task ->
            task.builtins {
                javanano {
                    option 'ignore_services=true'
                }
            }

            task.plugins {
                grpc {
                    option 'nano=true'
                }
            }
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.2.1'
    compile 'com.mcxiaoke.volley:library:1.0.19'
    compile 'com.android.support:design:23.2.1'
    compile 'com.android.support:support-v4:23.2.1'
    compile 'com.android.support:cardview-v7:23.2.1'
    compile 'com.android.support:support-annotations:23.2.1'
    compile 'com.android.support:customtabs:23.2.1'
    compile 'com.google.apis:google-api-services-youtube:v3-rev164-1.21.0'
    compile 'javax.annotation:javax.annotation-api:1.2'
    compile 'io.grpc:grpc-protobuf-nano:0.13.2'
    compile 'io.grpc:grpc-okhttp:0.13.2'
    compile 'io.grpc:grpc-stub:0.13.2'
    compile 'com.google.guava:guava:18.0'
}

Though both the youtube library and the grpc library are dependent on the google guava library, they're reliant on different versions causing a conflict. Youtube is dependent on com.google.guava:guava-jdk5:17.0 and grpc on com.google.guava:guava:18.0.(Notice the artifact difference, if that is possibly relevant) The problem is grpc ends up trying to locate a method defined in youtube's version of guava when it only exists in in its own version of the dependency. How do I resolve this?

ERROR Message

FATAL EXCEPTION: SyncAdapterThread-1
    Process: com.asdf.asdf, PID: 4025
             java.lang.NoSuchMethodError: No static method directExecutor()Ljava/util/concurrent/Executor; in class Lcom/google/common/util/concurrent/MoreExecutors; or its super classes (declaration of 'com.google.common.util.concurrent.MoreExecutors' appears in /data/data/com.fentale.dalol/files/instant-run/dex/slice-guava-jdk5-17.0_a8ada10dcaf113cb6e3b4d3e5b46975833f8ae8f-classes.dex)
                at io.grpc.internal.ClientCallImpl.<init>(ClientCallImpl.java:100)
                at io.grpc.internal.ManagedChannelImpl$RealChannel.newCall(ManagedChannelImpl.java:320)
                at io.grpc.internal.ManagedChannelImpl.newCall(ManagedChannelImpl.java:299)
                at io.grpc.stub.ClientCalls.blockingUnaryCall(ClientCalls.java:130)
                at com.fentale.dalol.nano.DalolGrpc$DalolBlockingStub.topPosts(DalolGrpc.java:365)

The method "directExecutor" is defined in guava-v18, but grpc tries to access it from the guava-jdk5.

Body:
You have to edit project level build.gradle you have to

exclude module: 'guava-jdk5'

inside dependencies. Please check attached screenshot for more details
If you are using firebase plugins add

classpath ('com.google.firebase:firebase-plugins:1.1.0') {
        exclude group: 'com.google.guava', module: 'guava-jdk5'
    }


问:
Postgres could not connect to server
After I did brew update and brew upgrade, my postgres got some problem. I tried to uninstall postgres and install it again, but it didn't work as well.

This is the error message. (I also got this error message when I try to do rake db:migrate)

$ psql
psql: could not connect to server: No such file or directory
    Is the server running locally and accepting
    connections on Unix domain socket "/tmp/.s.PGSQL.5432"?
```
<p>How can I solve it?</p>
<p>Mac version: Mountain lion.</p>
<p>homebrew version: 0.9.3</p>
<p>postgres version: psql (PostgreSQL) 9.2.1</p>
<p>And this is what I did:</p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$ brew uninstall postgresql
Uninstalling /usr/local/Cellar/postgresql/9.2.1...
$ brew uninstall postgresql
Uninstalling /usr/local/Cellar/postgresql/9.1.4...
$ psql --version
bash: /usr/local/bin/psql: No such file or directory
$ brew install postgresql
==> Downloading http://ftp.postgresql.org/pub/source/v9.2.1/postgresql-9.2.1.tar.bz2
Already downloaded: /Library/Caches/Homebrew/postgresql-9.2.1.tar.bz2
......
......
==> Summary
/usr/local/Cellar/postgresql/9.2.1: 2814 files, 38M, built in 2.7 minutes
$ initdb /usr/local/var/postgres -E utf8
The files belonging to this database system will be owned by user "laigary".
This user must also own the server process.

The database cluster will be initialized with locale "en_US.UTF-8".
The default text search configuration will be set to "english".

initdb: directory "/usr/local/var/postgres" exists but is not empty
If you want to create a new database system, either remove or empty
the directory "/usr/local/var/postgres" or run initdb
with an argument other than "/usr/local/var/postgres".
$ mkdir -p ~/Library/LaunchAgents
$ cp /usr/local/Cellar/postgresql/9.2.1/homebrew.mxcl.postgresql.plist ~/Library/LaunchAgents/
$ launchctl load -w ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist
homebrew.mxcl.postgresql: Already loaded
$ pg_ctl -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log start
server starting
$ env ARCHFLAGS="-arch x86_64" gem install pg
Building native extensions.  This could take a while...
Successfully installed pg-0.14.1
1 gem installed
$ psql --version
psql (PostgreSQL) 9.2.1
$ psql
psql: could not connect to server: No such file or directory
    Is the server running locally and accepting
    connections on Unix domain socket "/tmp/.s.PGSQL.5432"?</code>```

Now, after I reinstalled homebrew, when I use $ psql, it doesn't show any error message.

But I run rake db:migrate in my Rails app, it shows:

could not connect to server: No such file or directory
    Is the server running locally and accepting
    connections on Unix domain socket "/var/pgsql_socket/.s.PGSQL.5432"?

/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/postgresql_adapter.rb:1213:in `initialize'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/postgresql_adapter.rb:1213:in `new'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/postgresql_adapter.rb:1213:in `connect'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/postgresql_adapter.rb:329:in `initialize'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/postgresql_adapter.rb:28:in `new'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/postgresql_adapter.rb:28:in `postgresql_connection'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:309:in `new_connection'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:319:in `checkout_new_connection'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:241:in `block (2 levels) in checkout'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:236:in `loop'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:236:in `block in checkout'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/monitor.rb:211:in `mon_synchronize'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:233:in `checkout'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:96:in `block in connection'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/monitor.rb:211:in `mon_synchronize'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:95:in `connection'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:404:in `retrieve_connection'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_specification.rb:170:in `retrieve_connection'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_specification.rb:144:in `connection'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/railties/databases.rake:107:in `rescue in create_database'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/railties/databases.rake:51:in `create_database'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/railties/databases.rake:40:in `block (3 levels) in <top (required)>'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/railties/databases.rake:40:in `each'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/railties/databases.rake:40:in `block (2 levels) in <top (required)>'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/task.rb:205:in `call'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/task.rb:205:in `block in execute'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/task.rb:200:in `each'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/task.rb:200:in `execute'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/task.rb:158:in `block in invoke_with_call_chain'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/monitor.rb:211:in `mon_synchronize'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/task.rb:151:in `invoke_with_call_chain'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/task.rb:144:in `invoke'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/application.rb:116:in `invoke_task'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/application.rb:94:in `block (2 levels) in top_level'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/application.rb:94:in `each'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/application.rb:94:in `block in top_level'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/application.rb:133:in `standard_exception_handling'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/application.rb:88:in `top_level'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/application.rb:66:in `block in run'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/application.rb:133:in `standard_exception_handling'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/application.rb:63:in `run'
/usr/local/bin/rake:32:in `'
Couldn't create database for {"adapter"=>"postgresql", "encoding"=>"unicode", "database"=>"riy_development", "pool"=>5, "username"=>nil, "password"=>nil}```
</div>
</div>
</p>
<p><strong>Finally I've found a solution.</strong></p>
<pre class="lang-sh prettyprint-override"><code>sudo mkdir /var/pgsql_socket/
sudo ln -s /private/tmp/.s.PGSQL.5432 /var/pgsql_socket/
</code>```

This solution is a little tricky, but it works. Hope anyone has a better solution

Update

This works for me as well.

rm /usr/local/var/postgres/postmaster.pid
```

答:
If you are facing the issue while upgrading Postgres (or after upgrading), please follow the steps mentioned here to safely transfer data between versions, which will resolve the issue:

Upgrade PostgreSQL 9.6.5 to 10.0 using Homebrew (macOS)

Title: Postgres could not connect to server

Body:
After I did brew update and brew upgrade, my postgres got some problem. I tried to uninstall postgres and install it again, but it didn't work as well.

This is the error message. (I also got this error message when I try to do rake db:migrate)

$ psql
psql: could not connect to server: No such file or directory
    Is the server running locally and accepting
    connections on Unix domain socket "/tmp/.s.PGSQL.5432"?

How can I solve it?

Mac version: Mountain lion.

homebrew version: 0.9.3

postgres version: psql (PostgreSQL) 9.2.1

And this is what I did:

$ brew uninstall postgresql
Uninstalling /usr/local/Cellar/postgresql/9.2.1...
$ brew uninstall postgresql
Uninstalling /usr/local/Cellar/postgresql/9.1.4...
$ psql --version
bash: /usr/local/bin/psql: No such file or directory
$ brew install postgresql
==> Downloading http://ftp.postgresql.org/pub/source/v9.2.1/postgresql-9.2.1.tar.bz2
Already downloaded: /Library/Caches/Homebrew/postgresql-9.2.1.tar.bz2
......
......
==> Summary
/usr/local/Cellar/postgresql/9.2.1: 2814 files, 38M, built in 2.7 minutes
$ initdb /usr/local/var/postgres -E utf8
The files belonging to this database system will be owned by user "laigary".
This user must also own the server process.

The database cluster will be initialized with locale "en_US.UTF-8".
The default text search configuration will be set to "english".

initdb: directory "/usr/local/var/postgres" exists but is not empty
If you want to create a new database system, either remove or empty
the directory "/usr/local/var/postgres" or run initdb
with an argument other than "/usr/local/var/postgres".
$ mkdir -p ~/Library/LaunchAgents
$ cp /usr/local/Cellar/postgresql/9.2.1/homebrew.mxcl.postgresql.plist ~/Library/LaunchAgents/
$ launchctl load -w ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist
homebrew.mxcl.postgresql: Already loaded
$ pg_ctl -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log start
server starting
$ env ARCHFLAGS="-arch x86_64" gem install pg
Building native extensions.  This could take a while...
Successfully installed pg-0.14.1
1 gem installed
$ psql --version
psql (PostgreSQL) 9.2.1
$ psql
psql: could not connect to server: No such file or directory
    Is the server running locally and accepting
    connections on Unix domain socket "/tmp/.s.PGSQL.5432"?

Now, after I reinstalled homebrew, when I use $ psql, it doesn't show any error message.

But I run rake db:migrate in my Rails app, it shows:

could not connect to server: No such file or directory
    Is the server running locally and accepting
    connections on Unix domain socket "/var/pgsql_socket/.s.PGSQL.5432"?

/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/postgresql_adapter.rb:1213:in `initialize'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/postgresql_adapter.rb:1213:in `new'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/postgresql_adapter.rb:1213:in `connect'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/postgresql_adapter.rb:329:in `initialize'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/postgresql_adapter.rb:28:in `new'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/postgresql_adapter.rb:28:in `postgresql_connection'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:309:in `new_connection'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:319:in `checkout_new_connection'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:241:in `block (2 levels) in checkout'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:236:in `loop'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:236:in `block in checkout'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/monitor.rb:211:in `mon_synchronize'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:233:in `checkout'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:96:in `block in connection'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/monitor.rb:211:in `mon_synchronize'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:95:in `connection'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_pool.rb:404:in `retrieve_connection'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_specification.rb:170:in `retrieve_connection'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_specification.rb:144:in `connection'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/railties/databases.rake:107:in `rescue in create_database'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/railties/databases.rake:51:in `create_database'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/railties/databases.rake:40:in `block (3 levels) in <top (required)>'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/railties/databases.rake:40:in `each'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/railties/databases.rake:40:in `block (2 levels) in <top (required)>'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/task.rb:205:in `call'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/task.rb:205:in `block in execute'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/task.rb:200:in `each'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/task.rb:200:in `execute'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/task.rb:158:in `block in invoke_with_call_chain'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/monitor.rb:211:in `mon_synchronize'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/task.rb:151:in `invoke_with_call_chain'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/task.rb:144:in `invoke'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/application.rb:116:in `invoke_task'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/application.rb:94:in `block (2 levels) in top_level'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/application.rb:94:in `each'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/application.rb:94:in `block in top_level'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/application.rb:133:in `standard_exception_handling'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/application.rb:88:in `top_level'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/application.rb:66:in `block in run'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/application.rb:133:in `standard_exception_handling'
/usr/local/Cellar/ruby/1.9.3-p327/lib/ruby/1.9.1/rake/application.rb:63:in `run'
/usr/local/bin/rake:32:in `'
Couldn't create database for {"adapter"=>"postgresql", "encoding"=>"unicode", "database"=>"riy_development", "pool"=>5, "username"=>nil, "password"=>nil}

Finally I've found a solution.

sudo mkdir /var/pgsql_socket/
sudo ln -s /private/tmp/.s.PGSQL.5432 /var/pgsql_socket/

This solution is a little tricky, but it works. Hope anyone has a better solution

Update

This works for me as well.

rm /usr/local/var/postgres/postmaster.pid