问:
How to change constraint in ms sql if other bit column is true
I'm building a codebook in database.
There I have three columns:

[IDReal] int identity (1,1), [IsReal] bit not null, [Code] nvarchar (20) null

Now I have somehow get that when user change [IsReal] to 1, that my column [Code] change to not null and unique and vice versa.

I was trying something like

```<code>CREATE TABLE [dbo].[sReal](
[IDReal] [int] IDENTITY(1,1) NOT NULL,
[Code] [nvarchar](20) NULL,
[IsReal] [bit] NOT NULL,

ALTER TABLE [dbo].[sReal] ADD  CONSTRAINT [DEF_IsReal]  DEFAULT ((0)) FOR [IsReal]
    GO

ALTER TABLE [dbo].[sReal] ADD  CONSTRAINT [CHNG_IsReal] IF [IsReal]=1 THEN (ALTER TABLE [dbo].[sReal] ALTER COLUMN [Code] [nvarchar](20) not null unique)
ELSE END IF
GO`
</code>```

This, of course, is not working and I can't use triggers or functions or procedures to solve that.

Is there any other solution for accomplishing what I'm trying to do.

答:
A simple way can be :</p>

```<code>Declare @Variable1 int;
SELECT @Variable1 = [IsReal] From [sReal] WHERE  [IsReal]=1  --your user specific condition

IF @Variable1 = 1
BEGIN
    alter table [sReal] ALTER COLUMN [Code][nvarchar](20) NOT NULL
    alter table [sReal] ADD  CONSTRAINT [CHNG_IsReal] UNIQUE([Code])
END
ELSE
IF @Variable1 <> 1
BEGIN
    alter table [sReal] DROP  CONSTRAINT [CHNG_IsReal]
    alter table [sReal] ALTER COLUMN [Code][nvarchar](20) NULL
END
</code>```

Body:
I'm building a codebook in database.
There I have three columns:

[IDReal] int identity (1,1), [IsReal] bit not null, [Code] nvarchar (20) null

Now I have somehow get that when user change [IsReal] to 1, that my column [Code] change to not null and unique and vice versa.

I was trying something like

CREATE TABLE [dbo].[sReal](
[IDReal] [int] IDENTITY(1,1) NOT NULL,
[Code] [nvarchar](20) NULL,
[IsReal] [bit] NOT NULL,

ALTER TABLE [dbo].[sReal] ADD  CONSTRAINT [DEF_IsReal]  DEFAULT ((0)) FOR [IsReal]
    GO

ALTER TABLE [dbo].[sReal] ADD  CONSTRAINT [CHNG_IsReal] IF [IsReal]=1 THEN (ALTER TABLE [dbo].[sReal] ALTER COLUMN [Code] [nvarchar](20) not null unique)
ELSE END IF
GO`

This, of course, is not working and I can't use triggers or functions or procedures to solve that.

Is there any other solution for accomplishing what I'm trying to do.

Body:
A simple way can be :

Declare @Variable1 int;
SELECT @Variable1 = [IsReal] From [sReal] WHERE  [IsReal]=1  --your user specific condition

IF @Variable1 = 1
BEGIN
    alter table [sReal] ALTER COLUMN [Code][nvarchar](20) NOT NULL
    alter table [sReal] ADD  CONSTRAINT [CHNG_IsReal] UNIQUE([Code])
END
ELSE
IF @Variable1 <> 1
BEGIN
    alter table [sReal] DROP  CONSTRAINT [CHNG_IsReal]
    alter table [sReal] ALTER COLUMN [Code][nvarchar](20) NULL
END


来源: stackexchange

问:
Swift3: Openweather API returns nil and API errors
I'm trying to run an app that allows you to use a search bar and it'll return just temp, city, and conditions. When I run it I get a nil return on the temp and a 'Code: 401 API not valid' error. However, both codes I've tried should be working. I'm probably trying to take the wrong data from OpenWeather but I can't seem to find out where or how to fix it - there are no other errors that appear.

I'm trying to combine two tutorials/guides on this topic, but one uses a different API & the other is in Swift2.

Thanks!

```<code>import UIKit

class ViewController: UIViewController, UISearchBarDelegate {

    @IBOutlet weak var citySearchBar: UISearchBar!
    @IBOutlet weak var cityLabel: UILabel!
    @IBOutlet weak var conditionLabel: UILabel!
    @IBOutlet weak var tempLabel: UILabel!

    var temp: Int!
    var condition: String!
    var city: String!
    let apiID:String = "d7817e07565a0019c5e7851a59eeca73"

    var exists: Bool = true
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        citySearchBar.delegate = self
    }

    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {

        let urlRequest = URLRequest(url: URL(string: "http://api.openweathermap.org/data/2.5/weather?q=\(citySearchBar.text!.replacingOccurrences(of: " ", with: "_"))&appid=\(apiID))")!)

        let task = URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in

            if error == nil {
                do {

                    let weatherData = try JSONSerialization.jsonObject(
                        with: data!,
                        options: .mutableContainers) as! [String : AnyObject]

                    let weather = weatherData

                    DispatchQueue.main.async {

                        self.cityLabel.text = self.city
                        self.tempLabel.text = "\((self.temp))°"
                        self.conditionLabel.text = weather.description
                        }

                } catch let jsonError {
                    print(jsonError.localizedDescription)
                }  }  }

        task.resume()
    }  }
</code>```

答:
First of all the value for temp is a Double not an Int

```<code>var temp = 0.0
</code>```

Second of all you don't set temp in the code. The value for temp is in the dictionary main in weatherData

```<code>if let main = weatherData["main"] as? [String:Any],
   let tempValue = main["temp"] as? Double {
       self.temp = tempValue
       print(tempValue)
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to run an app that allows you to use a search bar and it'll return just temp, city, and conditions. When I run it I get a nil return on the temp and a 'Code: 401 API not valid' error. However, both codes I've tried should be working. I'm probably trying to take the wrong data from OpenWeather but I can't seem to find out where or how to fix it - there are no other errors that appear.

I'm trying to combine two tutorials/guides on this topic, but one uses a different API & the other is in Swift2.

Thanks!

import UIKit

class ViewController: UIViewController, UISearchBarDelegate {

    @IBOutlet weak var citySearchBar: UISearchBar!
    @IBOutlet weak var cityLabel: UILabel!
    @IBOutlet weak var conditionLabel: UILabel!
    @IBOutlet weak var tempLabel: UILabel!

    var temp: Int!
    var condition: String!
    var city: String!
    let apiID:String = "d7817e07565a0019c5e7851a59eeca73"

    var exists: Bool = true
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        citySearchBar.delegate = self
    }

    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {

        let urlRequest = URLRequest(url: URL(string: "http://api.openweathermap.org/data/2.5/weather?q=\(citySearchBar.text!.replacingOccurrences(of: " ", with: "_"))&appid=\(apiID))")!)

        let task = URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in

            if error == nil {
                do {

                    let weatherData = try JSONSerialization.jsonObject(
                        with: data!,
                        options: .mutableContainers) as! [String : AnyObject]

                    let weather = weatherData

                    DispatchQueue.main.async {

                        self.cityLabel.text = self.city
                        self.tempLabel.text = "\((self.temp))°"
                        self.conditionLabel.text = weather.description
                        }

                } catch let jsonError {
                    print(jsonError.localizedDescription)
                }  }  }

        task.resume()
    }  }

Body:
First of all the value for temp is a Double not an Int

var temp = 0.0

Second of all you don't set temp in the code. The value for temp is in the dictionary main in weatherData

if let main = weatherData["main"] as? [String:Any],
   let tempValue = main["temp"] as? Double {
       self.temp = tempValue
       print(tempValue)
}


问:
Getting users' current location in background thread for iOS 6/7
Hello i have a problem with getting users current location on iOS 6/7. I need users location on app startup but it takes 6-8 seconds to get users location, and until the location is retrieved the app doesn't hide the splash screen and that is not ok (for me).

I wanted to get the users location in background using dispatch_async (GCD) but it did not change a thing :( . So i wanted to know is there a way to fi my problem. I really appreciate any help. Thanks in advance.
Here is the code for init of my app:

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

self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

FinalMenuViewController *leftMenuViewController = [[FinalMenuViewController alloc] init];
MFSideMenuContainerViewController *container = [MFSideMenuContainerViewController
                                                containerWithCenterViewController:[self navigationController]
                                                leftMenuViewController:leftMenuViewController
                                                rightMenuViewController:nil];
container.panMode = MFSideMenuPanModeNone;
self.window.rootViewController = container;

if(([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0)){
    [[UIBarButtonItem appearance] setTintColor:[UIColor whiteColor]];
}else{
    [[UIBarButtonItem appearance] setTintColor:[UIColor colorWithRed:(250.0/255.0) green:(139.0/255.0) blue:(40.0/255.0) alpha:1.0]];
}

[self.window makeKeyAndVisible];

[self displaySplashImage];

[self setDefaultData];

[self initLocationManager];

return YES;
}

-(void) displaySplashImage{

CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;

UIImage* myImage;
NSString *imgName = ([[UIScreen mainScreen] bounds].size.height == 568) ? @"Default-568h@2x.png" : @"Default.png";
myImage = [UIImage imageNamed:imgName];
self.splashView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.window.frame.size.width, self.window.frame.size.height)];

mainV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, screenHeight)];
[mainV addSubview:self.splashView];
[mainV setBackgroundColor: [UIColor clearColor]];

self.splashView.image = myImage;
self.splashView.contentMode = UIViewContentModeScaleAspectFit;

[self.window addSubview:mainV];
[self.window bringSubviewToFront:mainV];
[self removeImageView];

}
-(void) removeImageView{
if(mainV){
    [mainV removeFromSuperview];
}
}
</code>```

--- EDIT ----
Here is the code for getting the current location

```<code>-(void) initManager{
locManager_ = [[CLLocationManager alloc] init];
locManager_.delegate = self;
locManager_.distanceFilter = 50;
locManager_.desiredAccuracy = kCLLocationAccuracyBest;
[locManager_ startUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locations __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_6_0){
CLLocation *loc = [locations lastObject];
GlobalVariables *vars = [GlobalVariables getInstance];
vars.currentLocatoin = loc;

}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
if ([error domain] == kCLErrorDomain) {
    switch ([error code]) {
        case kCLErrorDenied:{
            NSString *msg = @"ERROR_MSG_HERE";
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:msg delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
            [alert show];
            break;

        }
        case kCLErrorLocationUnknown:{
            NSString *msg = @"We were unable to find your location";
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:msg delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
            [alert show];
            break;
        }

        default:
            break;
    }
} else {

}
}
</code>```

答:
You can use dispatch_after to create a delay, and after the delay is finished, start executing code that requires the user location.  Here is a sample from my own code, where I subclass CLLocationManager and store the updated location in a private ivar (which is set inside the locationManager delegate method in my CLLocationManager subclass):

```<code>(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation;
</code>```

The updated location is then accessible through a getter (getLastUpdatedUserLocation).

Here's the code:

```<code>UserLocationManager* userLocationManager = [UserLocationManager sharedLocationManager];

    [userLocationManager requestAuthorizationAndStartUpdates];

    __block CLLocation* userLocation = [userLocationManager getLastUpdatedUserLocation];

    if(userLocation == nil){

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 6.00*NSEC_PER_SEC), dispatch_get_main_queue(), ^{

            userLocation = [userLocationManager getLastUpdatedUserLocation];

            NSLog(@"The user location after 6.00 secondss is lat: %f, long: %f",userLocation.coordinate.latitude,userLocation.coordinate.longitude);
        });
    }
</code>```

Body:
Hello i have a problem with getting users current location on iOS 6/7. I need users location on app startup but it takes 6-8 seconds to get users location, and until the location is retrieved the app doesn't hide the splash screen and that is not ok (for me).

I wanted to get the users location in background using dispatch_async (GCD) but it did not change a thing :( . So i wanted to know is there a way to fi my problem. I really appreciate any help. Thanks in advance.
Here is the code for init of my app:

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

self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

FinalMenuViewController *leftMenuViewController = [[FinalMenuViewController alloc] init];
MFSideMenuContainerViewController *container = [MFSideMenuContainerViewController
                                                containerWithCenterViewController:[self navigationController]
                                                leftMenuViewController:leftMenuViewController
                                                rightMenuViewController:nil];
container.panMode = MFSideMenuPanModeNone;
self.window.rootViewController = container;

if(([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0)){
    [[UIBarButtonItem appearance] setTintColor:[UIColor whiteColor]];
}else{
    [[UIBarButtonItem appearance] setTintColor:[UIColor colorWithRed:(250.0/255.0) green:(139.0/255.0) blue:(40.0/255.0) alpha:1.0]];
}

[self.window makeKeyAndVisible];

[self displaySplashImage];

[self setDefaultData];

[self initLocationManager];

return YES;
}

-(void) displaySplashImage{

CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;

UIImage* myImage;
NSString *imgName = ([[UIScreen mainScreen] bounds].size.height == 568) ? @"Default-568h@2x.png" : @"Default.png";
myImage = [UIImage imageNamed:imgName];
self.splashView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.window.frame.size.width, self.window.frame.size.height)];

mainV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, screenHeight)];
[mainV addSubview:self.splashView];
[mainV setBackgroundColor: [UIColor clearColor]];

self.splashView.image = myImage;
self.splashView.contentMode = UIViewContentModeScaleAspectFit;

[self.window addSubview:mainV];
[self.window bringSubviewToFront:mainV];
[self removeImageView];

}
-(void) removeImageView{
if(mainV){
    [mainV removeFromSuperview];
}
}

--- EDIT ----
Here is the code for getting the current location

-(void) initManager{
locManager_ = [[CLLocationManager alloc] init];
locManager_.delegate = self;
locManager_.distanceFilter = 50;
locManager_.desiredAccuracy = kCLLocationAccuracyBest;
[locManager_ startUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locations __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_6_0){
CLLocation *loc = [locations lastObject];
GlobalVariables *vars = [GlobalVariables getInstance];
vars.currentLocatoin = loc;

}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
if ([error domain] == kCLErrorDomain) {
    switch ([error code]) {
        case kCLErrorDenied:{
            NSString *msg = @"ERROR_MSG_HERE";
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:msg delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
            [alert show];
            break;

        }
        case kCLErrorLocationUnknown:{
            NSString *msg = @"We were unable to find your location";
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:msg delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
            [alert show];
            break;
        }

        default:
            break;
    }
} else {

}
}

Body:
You can use dispatch_after to create a delay, and after the delay is finished, start executing code that requires the user location.  Here is a sample from my own code, where I subclass CLLocationManager and store the updated location in a private ivar (which is set inside the locationManager delegate method in my CLLocationManager subclass):

(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation;

The updated location is then accessible through a getter (getLastUpdatedUserLocation).

Here's the code:

UserLocationManager* userLocationManager = [UserLocationManager sharedLocationManager];

    [userLocationManager requestAuthorizationAndStartUpdates];

    __block CLLocation* userLocation = [userLocationManager getLastUpdatedUserLocation];

    if(userLocation == nil){

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 6.00*NSEC_PER_SEC), dispatch_get_main_queue(), ^{

            userLocation = [userLocationManager getLastUpdatedUserLocation];

            NSLog(@"The user location after 6.00 secondss is lat: %f, long: %f",userLocation.coordinate.latitude,userLocation.coordinate.longitude);
        });
    }


问:
Best cross-browser method to capture CTRL+S with JQuery?
My users would like to be able to hit Ctrl+S to save a form.  Is there a good cross-browser way of capturing the Ctrl+S key combination and submit my form?

App is built on Drupal, so jQuery is available.

答:
This Plugin Made by me may be helpful.

Plugin

You can use this plugin you have to supply the key Codes and function to be run like this

```<code>simulatorControl([17,83], function(){
 console.log('You have pressed Ctrl+Z');
});
</code>```

In the code i have displayed how to perform for Ctrl+S. You will get Detailed Documentation On the link. Plugin is in JavaScript Code section Of my Pen on Codepen.

OwnerDisplayName: ceejayoz

LastEditorDisplayName: GateKiller

Body:
This Plugin Made by me may be helpful.

Plugin

You can use this plugin you have to supply the key Codes and function to be run like this

simulatorControl([17,83], function(){
 console.log('You have pressed Ctrl+Z');
});

In the code i have displayed how to perform for Ctrl+S. You will get Detailed Documentation On the link. Plugin is in JavaScript Code section Of my Pen on Codepen.


问:
Auto calculate value including decimals
I have a html form where users add hours to 5 input fields (days of the week).

The total hours is then displayed at the bottom of the form.

This is working fine for rounded hours, but when adding something like 7.4 the total is rounding it to 7

See below:
Is there a way to add the decimals too?

$(document).ready(function() {
  $('.calc').change(function() {
    var total = 0;
    $('.calc').each(function() {
      if ($(this).val() != '') {
        total += parseInt($(this).val());
      }
    });
    $('#total').html(total);
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="form-control  calc" name='mon'>
<input type="text" class="form-control  calc" name='tue'>
<span id="total"></span></code>```

答:
In order to get the number of decimals instead of a long and ugly float, change this line

```<code>total += parseInt($(this).val());
</code>```

To this

```<code>total += parseFloat($(this).val());
</code>```

And change this line

```<code>$('#total').html(total);
</code>```

To this

```<code>$('#total').html(total.toFixed(2)); //If you want two decimals
</code>```

Title: Auto calculate value including decimals

Body:
I have a html form where users add hours to 5 input fields (days of the week).

The total hours is then displayed at the bottom of the form.

This is working fine for rounded hours, but when adding something like 7.4 the total is rounding it to 7

See below:
Is there a way to add the decimals too?

$(document).ready(function() {
  $('.calc').change(function() {
    var total = 0;
    $('.calc').each(function() {
      if ($(this).val() != '') {
        total += parseInt($(this).val());
      }
    });
    $('#total').html(total);
  });
});

<input type="text" class="form-control  calc" name='mon'>
<input type="text" class="form-control  calc" name='tue'>

Body:
In order to get the number of decimals instead of a long and ugly float, change this line

total += parseInt($(this).val());

To this

total += parseFloat($(this).val());

And change this line

$('#total').html(total);

To this

$('#total').html(total.toFixed(2)); //If you want two decimals


问:
SpringBoot Rest Application + Arquillian
I want to test my Rest Application that uses SpringBoot to test with Arquillian but none of the online examples work i am not able to test a GET call and facing difficulties deploying to Jboss EAP-6.4. Can anyone guide me on how to achieve this. Any simple Examples ???</p>

答:
This link helped me to solve the issue : Adding all Maven dependencies to Arquillian.

The code that works :

```<code>@Deployment
public static Archive<?> createTestArchive() {

        File[] files = Maven.resolver()
                        .loadPomFromFile("pom.xml")
                        .importRuntimeDependencies()
                        .resolve().withTransitivity()
                        .asFile();

    return ShrinkWrap.create(WebArchive.class, "FileUploadIssue.war")
                     .addPackages(true,"com.example")
                     .addAsLibraries(files);
}

@Test
@RunAsClient
public void shouldGetFileContents() {

    String result = restTemplate.getForObject(contextPath + "upload/sayhello", String.class);

    System.out.println( "Test : " + result);
}
</code>```

Is there any way to refactor this code even more ??

Body:
This link helped me to solve the issue : Adding all Maven dependencies to Arquillian.

The code that works :

@Deployment
public static Archive<?> createTestArchive() {

        File[] files = Maven.resolver()
                        .loadPomFromFile("pom.xml")
                        .importRuntimeDependencies()
                        .resolve().withTransitivity()
                        .asFile();

    return ShrinkWrap.create(WebArchive.class, "FileUploadIssue.war")
                     .addPackages(true,"com.example")
                     .addAsLibraries(files);
}

@Test
@RunAsClient
public void shouldGetFileContents() {

    String result = restTemplate.getForObject(contextPath + "upload/sayhello", String.class);

    System.out.println( "Test : " + result);
}

Is there any way to refactor this code even more ??


问:
GraphQL: react-apollo client overwrites array elements
I have a GraphQL query that returns an array of items. I can run the query in GraphiQL and get the result I expected.

I have a react application that uses react-apollo and the @graphql decorator to resolve the very same query to component props. When running the query via react-apollo, every item in the returned array is the same - each item has been 'overwritten' by the last item.

I can see in the dev-tools network tab that the correct array items were sent over the network, so the issue seems to relate to react-apollo. What could be causing react-apollo to overwrite array elements?

答:
The issue was that my qgl fragment for the query did not include the id property for the items in the Array.

If you have a similar issue, ensure your schema includes an id or _id property on each item; that each id value is unique, and that you are requesting the id property in your query. Alternatively you can supply a dataIdFromObject function in your client to dynamically generate IDs for values.

You can read more in the Apollo docs for Normalization with dataIdFromObject


问:
Float Label hint (TextInputLayout) not works with Android Data Binding
I need create fields edit page in app. There are list of EditText for edit Contact. For each field type i have an layout. As example - for name and last name it is float labeled edit text. For facebook - simple edit text with icon. I am creating this list with Android Data Binding Library

I've created layout

```<code><data>

    <variable
        name="item"
        type="app.core.db.model.Field" />
</data>

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <android.support.design.widget.TextInputLayout
        android:layout_width="match_parent"
        android:layout_height="65dp"
        app:hintTextAppearance="@style/TextAppearence.App.TextInputLayout"
        app:theme="@style/EditFieldFloatLabeled">

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ellipsize="end"
            android:hint="@{item.getHint()}"
            android:imeOptions="actionNext"
            android:maxLines="1" />
    </android.support.design.widget.TextInputLayout>

</FrameLayout>
</code>```

But float label not works. I starts commenting line by line to find out reason. Float label became work when I've commented line

```<code>android:hint="@{item.getHint()}
</code>```

(And replace it with hardcoded text). getHint() returns R.string.{something} based on field type.

There I've found out than programmatically setting hint produce float label disappearing. I can not use static layout (instead recycler view) because fields list can increase dynsmically (ex: I am writing phone number in field and empty Phone field inserts after it for other phone number).

Is there way to create float label same way (by defining hint with field type)?

答:
The problem is that when nothing is assigned, 0 will be given as the resource ID. you're probably seeing an exception like this in your logcat:

```<code>android.content.res.Resources$NotFoundException: String resource ID #0x0
</code>```

It is likely that you haven't assigned a value to the item before the first evaluation of the expression. You should assign the item immediately after creating the binding if you want to ensure that the resource isn't set to the value 0.

```<code>MyBinding binding = MyBinding.inflate(inflater, parent, true);
binding.setItem(item);
</code>```

Body:
I need create fields edit page in app. There are list of EditText for edit Contact. For each field type i have an layout. As example - for name and last name it is float labeled edit text. For facebook - simple edit text with icon. I am creating this list with Android Data Binding Library

I've created layout

<data>

    <variable
        name="item"
        type="app.core.db.model.Field" />
</data>

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <android.support.design.widget.TextInputLayout
        android:layout_width="match_parent"
        android:layout_height="65dp"
        app:hintTextAppearance="@style/TextAppearence.App.TextInputLayout"
        app:theme="@style/EditFieldFloatLabeled">

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ellipsize="end"
            android:hint="@{item.getHint()}"
            android:imeOptions="actionNext"
            android:maxLines="1" />
    </android.support.design.widget.TextInputLayout>

</FrameLayout>

But float label not works. I starts commenting line by line to find out reason. Float label became work when I've commented line

android:hint="@{item.getHint()}

(And replace it with hardcoded text). getHint() returns R.string.{something} based on field type.

There I've found out than programmatically setting hint produce float label disappearing. I can not use static layout (instead recycler view) because fields list can increase dynsmically (ex: I am writing phone number in field and empty Phone field inserts after it for other phone number).

Is there way to create float label same way (by defining hint with field type)?

Body:
The problem is that when nothing is assigned, 0 will be given as the resource ID. you're probably seeing an exception like this in your logcat:

android.content.res.Resources$NotFoundException: String resource ID #0x0

It is likely that you haven't assigned a value to the item before the first evaluation of the expression. You should assign the item immediately after creating the binding if you want to ensure that the resource isn't set to the value 0.

MyBinding binding = MyBinding.inflate(inflater, parent, true);
binding.setItem(item);


问:
How to update a angular 4+ form values using console devtools?
I'm trying to fill a Angular 4+ form using console (devtools).

This is what I'm doing now:

function fillForm(){
    let el = document.querySelector('input[ng-reflect-name="my_input"]');
    let elProbe = ng.probe(el);
    elProbe._debugContext.component.value = 'new-value';
}
```

Some references I'm trying to use (if it helps anyone):

https://juristr.com/blog/2016/02/debugging-angular2-console/

Trigger Angular change detection from console

答:
Simple way of doing this could be running change detection cycle using core token for ApplicationRef

```<code>let el = document.querySelector('input[ng-reflect-name="my_input"]');
let elProbe = ng.probe(el);
elProbe._debugContext.component.value = 'new-value';
elProbe.injector.get(ng.coreTokens.ApplicationRef).tick()
</code>```

You can also take a look at integration tests

https://github.com/angular/angular/blob/master/packages/forms/test/template_integration_spec.ts#L28-L30

I think this way we check how our component works with NgModel and don't call direct API on inner NgModel directive.

Without calling change detection we can also the following code to simulate user action

```<code>let valueAccessor = elProbe.injector.get(elProbe.providerTokens
                       .find(x =>x.name === 'DefaultValueAccessor'));

el.value = 'some';
valueAccessor.onChange('some');
</code>```

But it looks very strange

Body:
I'm trying to fill a Angular 4+ form using console (devtools).

This is what I'm doing now:

function fillForm(){
    let el = document.querySelector('input[ng-reflect-name="my_input"]');
    let elProbe = ng.probe(el);
    elProbe._debugContext.component.value = 'new-value';
}

Some references I'm trying to use (if it helps anyone):

https://juristr.com/blog/2016/02/debugging-angular2-console/

Trigger Angular change detection from console

Body:
Simple way of doing this could be running change detection cycle using core token for ApplicationRef

let el = document.querySelector('input[ng-reflect-name="my_input"]');
let elProbe = ng.probe(el);
elProbe._debugContext.component.value = 'new-value';
elProbe.injector.get(ng.coreTokens.ApplicationRef).tick()

You can also take a look at integration tests

https://github.com/angular/angular/blob/master/packages/forms/test/template_integration_spec.ts#L28-L30

I think this way we check how our component works with NgModel and don't call direct API on inner NgModel directive.

Without calling change detection we can also the following code to simulate user action

let valueAccessor = elProbe.injector.get(elProbe.providerTokens
                       .find(x =>x.name === 'DefaultValueAccessor'));

el.value = 'some';
valueAccessor.onChange('some');

But it looks very strange


问:
Run code when pressing on the [x]
I am making a distributed concurrent game online using Java and Swing. I want to remove the player's icon from the game zone when the user press the [x] to close the window. How can i say to the VM to execute a function before terminating the process?</p>

答:
Assuming you are using a JFrame, set its default close operation do DO_NOTHING_ON_CLOSE and add a WindowListener to react on windowClosing.

This method can do what ever is needed and then just dispose the window to actually close it.

Note: this can also be used to ask the user if she/he really wants to exit...

Title: Run code when pressing on the [x]


问:
AWS Cloudwatch not triggering on API calls
I am trying to make a rule trigger on any API call for creation, but I haven't had any success.

I have another rule that triggers whenever and ec2 instance is running which works, but this rule does not trigger for RunInstances although I see the cloudtrail logs with RunInstances in the API log.

I have made a CloudWatch log from the cloudtrail and see the events that should be triggering it, but they don't. Is there a step I am missing? What are the necessary components to have CloudWatch properly trigger on API calls?

The rule mentioned:

```<code> {
      "source": [
        "aws.cloudtrail"
      ],
      "detail-type": [
        "AWS API Call via CloudTrail"
      ],
      "detail": {
        "eventSource": [
          "cloudtrail.amazonaws.com"
        ],
        "eventName": [
          "CreateUserPool",
          "CreateImage",
          "CreateCacheCluster",
          "RunInstances",
          "CreateActivation",
          "RunJobFlow ",
          "CreateVault",
          "CreateDeliveryStream",
          "CreateStream",
          "CreateCluster",
          "CreateDBInstance",
          "CreateHostedZone",
          "CreateBucket",
          "CreateLaunchConfiguration",
          "CreateStack",
          "CreateEnvironment",
          "CreateWorkspaces"
        ]
      }
    }
</code>```

To add more detail here is the other rule I used to test CloudWatch

```<code>{
  "source": [
    "aws.ec2"
  ],
  "detail-type": [
    "EC2 Instance State-change Notification"
  ],
  "detail": {
    "state": [
      "running"
    ]
  }
}
</code>```

This is the log of the startInstances and the following Lambda function running.

Cloudtrail of the the lambda function specifically which functions normally.

Here is the API call which should also initiate it according to the rule, but it does not.

Hopefully these images make it clearer as to what I am having trouble with.

P.S. I didn't know how much info I should consider confidential, so I over censored

答:
I misunderstood the rule I created. I thought "AWS API calls from Cloudtrail" when using the cloudtrail Service meant all the information stored in Cloudtrail. That does not seem to be the case.

As I mention in my comment, I am looking for other solutions for my problem, but I will make a separate question for that. Thanks!

Body:
I am trying to make a rule trigger on any API call for creation, but I haven't had any success.

I have another rule that triggers whenever and ec2 instance is running which works, but this rule does not trigger for RunInstances although I see the cloudtrail logs with RunInstances in the API log.

I have made a CloudWatch log from the cloudtrail and see the events that should be triggering it, but they don't. Is there a step I am missing? What are the necessary components to have CloudWatch properly trigger on API calls?

The rule mentioned:

 {
      "source": [
        "aws.cloudtrail"
      ],
      "detail-type": [
        "AWS API Call via CloudTrail"
      ],
      "detail": {
        "eventSource": [
          "cloudtrail.amazonaws.com"
        ],
        "eventName": [
          "CreateUserPool",
          "CreateImage",
          "CreateCacheCluster",
          "RunInstances",
          "CreateActivation",
          "RunJobFlow ",
          "CreateVault",
          "CreateDeliveryStream",
          "CreateStream",
          "CreateCluster",
          "CreateDBInstance",
          "CreateHostedZone",
          "CreateBucket",
          "CreateLaunchConfiguration",
          "CreateStack",
          "CreateEnvironment",
          "CreateWorkspaces"
        ]
      }
    }

To add more detail here is the other rule I used to test CloudWatch

{
  "source": [
    "aws.ec2"
  ],
  "detail-type": [
    "EC2 Instance State-change Notification"
  ],
  "detail": {
    "state": [
      "running"
    ]
  }
}

This is the log of the startInstances and the following Lambda function running.

Cloudtrail of the the lambda function specifically which functions normally.

Here is the API call which should also initiate it according to the rule, but it does not.

Hopefully these images make it clearer as to what I am having trouble with.

P.S. I didn't know how much info I should consider confidential, so I over censored


问:
duplicate symbol _OBJC_METACLASS_$_SBJSON when using CloudMade and Facebook iOs SDKs
I'm trying to compile a project that uses both CloudMade and Facebook.
The Facebook SDK also includes the SBJson library so I get a link error:

duplicate symbol _OBJC_METACLASS_$_SBJSON in ../CloudMadeApi/libs/CloudMade/libCloudMadeApi.a(SBJSON.o) and (...)/Objects-normal/i386/SBJSON.o

If I exclude the Facebook SBJson .m files from the build it compiles but then the SBJson methods are not found at run time.

I'm using the latest CloudMade and Facebook SDKs.

Can someone please help me?

Thanks.

答: this issue will be fixed soon by removing SBJSON from CloudMade iPhone and iPad SDK. Here is forum post about it: http://support.cloudmade.com/forums/iphone-sdk/posts/1399/show</p>

ContentLicense: CC BY-SA 2.5


问:
Jquery library symfony collection doesn't work with
 element
When I add a element in my custom form theme, the incrementation of my collection doesn't works !

I use this library : https://github.com/ninsuo/symfony-collection

```<code>{% block PriceType_row %}
    {{ form_widget(form) }}
{% endblock %}

{% block PriceType_widget %}
    <tr>
        <td>
            {{ form_widget(form.quantityFrom, {'attr': {'class': 'form-control'}}) }}
        </td>
        <td>
            {{ form_widget(form.quantityTo, {'attr': {'class': 'form-control'}}) }}
        </td>
        <td>
            {{ form_widget(form.bestUnitPrice, {'attr': {'class': 'form-control'}}) }}
    </td>
    <td>
        {{ form_widget(form.getPaid, {'attr': {'class': 'form-control'}}) }}
    </td>
    <td>
        {{ form_widget(form.vatRate, {'attr': {'class': 'form-control'}}) }}
    </td>
</tr>
{% endblock %}

{% block ProductType_widget %}
    {{ form_widget(form.prices) }}l
{% endblock %}
</code>```

Thanks for your help ! :)

答:
[Auto response]

I musted add an elements_selector to my collection javascript

```<code>$('.collection-prices').collection({
   elements_selector: '> tr',
});
</code>```

Title: Jquery library symfony collection doesn't work with <table> element

Body:
When I add a element in my custom form theme, the incrementation of my collection doesn't works !

I use this library : https://github.com/ninsuo/symfony-collection

{% block PriceType_row %}
    {{ form_widget(form) }}
{% endblock %}

{% block PriceType_widget %}

            {{ form_widget(form.quantityFrom, {'attr': {'class': 'form-control'}}) }}

            {{ form_widget(form.quantityTo, {'attr': {'class': 'form-control'}}) }}

            {{ form_widget(form.bestUnitPrice, {'attr': {'class': 'form-control'}}) }}

        {{ form_widget(form.getPaid, {'attr': {'class': 'form-control'}}) }}

        {{ form_widget(form.vatRate, {'attr': {'class': 'form-control'}}) }}

{% endblock %}

{% block ProductType_widget %}
    {{ form_widget(form.prices) }}l
{% endblock %}

Thanks for your help ! :)

Body:
[Auto response]

I musted add an elements_selector to my collection javascript

$('.collection-prices').collection({
   elements_selector: '> tr',
});


问:
Cannot open Eclipse Marketplace Cannot install remote marketplace locations: Cannot resolve host
I am using eclipse Kepler version and trying to install Sonar plugin from Eclipse marketplace.
But I am getting below error

Cannot open Eclipse Marketplace Cannot install remote marketplace
  locations: Cannot resolve host

This is most often caused by a problem with your internet connection.
  Please check your internet connection and retry. Unknown Host:
  http://marketplace.eclipse.org/catalogs/api/p marketplace.eclipse.org
  Cannot resolve host

This is most often caused by a problem with your internet connection.
  Please check your internet connection and retry.
  marketplace.eclipse.org

I tried below things as per solution suggested by some people.

Go to Window-> Preferences -> General -> Network Connection. And
change below settings Active Provider-> Manual-> and check---> HTTP,
HTTPS and SOCS. After restarting eclipse still the problem persisted.

I tried connecting to google.com from Eclipse Internet Explorer and able to see google homepage

Added line in eclipse.ini file
-vmargs
-Djava.net.preferIPv4Stack=true But still same issue

I am really frustated by this issue and couldn't find any help anywhere. If anyone has faced this issue and has an effective resolution, please assist.

Below is the snap of Proxy details

答: Try to add the host like this: marketplace.eclipse.org/catalogs/api* in Proxy bypass.


问:
Is material-ui friendly to form?
Recently, when I use React&material-ui to make a form, I find that many components do not have 'name' property, such as 'SelectField'. So I must get the value through a method. Is material-ui suitable for implementing a form? If the answer is yes, can you give me a intact example which uses some components such as 'TextField', 'SelectField', and how do I submit it?  </p>

答:
I could recommend connectin material-ui with redux-form:

http://redux-form.com/6.8.0/examples/material-ui/

Works fine as long as you pass component representing material-ui form into the Field from react redux

```<code>import { Field } from 'redux-form/immutable';
import TextField from 'material-ui/TextField';

<Field
    name="username"
    id="username"
    type="text"
    placeholder="Username"
    label="Username"
    required
    iconName="person"
    component={TextField}
  />
</code>```

And then you would have form values existing in redux state.

Title: Is material-ui friendly to form?

Body:
I could recommend connectin material-ui with redux-form:

http://redux-form.com/6.8.0/examples/material-ui/

Works fine as long as you pass component representing material-ui form into the Field from react redux

import { Field } from 'redux-form/immutable';
import TextField from 'material-ui/TextField';

<Field
    name="username"
    id="username"
    type="text"
    placeholder="Username"
    label="Username"
    required
    iconName="person"
    component={TextField}
  />

And then you would have form values existing in redux state.


问:
Align two buttons that are in two different DIVs
So I tried to play a bit with my code and was looking on many forums to see if the answer was already given. I didn't find anything yet. I wanted to know how to align the buttons divs to each other, like this :

At this time, my code is this :

.directeur {
  width: 50%;
  float: left;
}

.directeur p {
  width: 80%;
  text-align: center;
  margin-left: auto;
  margin-right: auto;
  margin-bottom: 10px;
  margin-top: 10px;
}

.directeur a>img {
  margin-left: auto;
  margin-right: auto;
  margin-bottom: 10px;
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="directeur">
  <img src="http://via.placeholder.com/500x150" alt="">
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tenetur maxime impedit amet labore facere. Quod quos consectetur nulla eaque soluta tenetur omnis quo sunt, modi optio iste consequuntur atque error.</p>
  <img src="http://via.placeholder.com/300x70" alt="">
</div>
<div class="directeur">
  <img src="http://via.placeholder.com/500x150" alt="">
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Repellendus rem delectus enim dolorem, error nulla earum maxime aliquid ipsam, recusandae molestiae ducimus iusto, dolore omnis. Saepe temporibus autem, provident dolor!</p>
  <img src="http://via.placeholder.com/300x70" alt="">
</div></code>```

Can someone help me ? I created other Divs, tried Vertical-Align and Inline-Block. I want the Green Button Rectangle to align like this in my code. At the moment, they are not align because of the height of the text box.

答:
Have you tried this.

```<code>.custom_element{
position: absolute;
left:0;
right:0;
text-align: center;
}
</code>```

Replace custom_element with your required element.

Body:
So I tried to play a bit with my code and was looking on many forums to see if the answer was already given. I didn't find anything yet. I wanted to know how to align the buttons divs to each other, like this :

At this time, my code is this :

.directeur {
  width: 50%;
  float: left;
}

.directeur p {
  width: 80%;
  text-align: center;
  margin-left: auto;
  margin-right: auto;
  margin-bottom: 10px;
  margin-top: 10px;
}

.directeur a>img {
  margin-left: auto;
  margin-right: auto;
  margin-bottom: 10px;
  display: block;
}

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tenetur maxime impedit amet labore facere. Quod quos consectetur nulla eaque soluta tenetur omnis quo sunt, modi optio iste consequuntur atque error.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Repellendus rem delectus enim dolorem, error nulla earum maxime aliquid ipsam, recusandae molestiae ducimus iusto, dolore omnis. Saepe temporibus autem, provident dolor!

Can someone help me ? I created other Divs, tried Vertical-Align and Inline-Block. I want the Green Button Rectangle to align like this in my code. At the moment, they are not align because of the height of the text box.

Body:
Have you tried this.

.custom_element{
position: absolute;
left:0;
right:0;
text-align: center;
}

Replace custom_element with your required element.


问:
PostgreSQL How to create a boolean column from conditions within a query
I have the following SQL code:

```<code>SELECT sensor_id, reader_id, rssi, date_time, time_diff_lead, reader_diff
FROM
    (
    SELECT doc->>'sensorId' as sensor_id, doc->>'readerId' as reader_id, (doc->>'rssi')::int as rssi, created_at as date_time,
    EXTRACT(EPOCH FROM lead(created_at) OVER w - created_at) as time_diff_lead,
    (lead(doc->>'readerId') OVER w)::int - (doc->>'readerId')::int as reader_diff
    FROM public.sensor_data
    WINDOW w AS (PARTITION BY doc->>'sensorId' ORDER BY created_at)
    ) as x
WHERE rssi > 380 OR time_diff_lead > 18.0 AND reader_diff = 0
ORDER BY sensor_id, date_time
</code>```

The WHERE clause defines the conditions I would like to use to create a boolean column.

All of this data comes from a table with a jsonB column and for efficiency (I think...) I would need to add this column to that table, by the correct keys.

That table will be updated at least every 30 seconds with a new record. And the query above will be ran less often than that. So there will be nulls in that column. In a general sense how would that affect querying to that table? (new to data science)

I am in a start up and trying to lay the foundations of our data gathering (and they have ME doing it :P) so please rip my code apart and point me to better methods!

答:
A condition is a boolean type, so you can just select the value you get from the boolean condition and give it a alias:

```<code>SELECT sensor_id, reader_id, rssi, date_time
 , time_diff_lead, reader_diff
 , (rssi > 380 OR time_diff_lead > 18.0 AND reader_diff = 0) AS bull
FROM    (
    SELECT doc->>'sensorId' as sensor_id, doc->>'readerId' as reader_id
     , (doc->>'rssi')::int as rssi, created_at as date_time
    ,  EXTRACT(EPOCH FROM lead(created_at) OVER w - created_at) as time_diff_lead
    , (lead(doc->>'readerId') OVER w)::int - (doc->>'readerId')::int as reader_diff
    FROM public.sensor_data
    WINDOW w AS (PARTITION BY doc->>'sensorId' ORDER BY created_at)
    ) as x
ORDER BY sensor_id, date_time
;
</code>```

[updated] using the computed columns will need the condition to be pulled to the main query.

Body:
I have the following SQL code:

SELECT sensor_id, reader_id, rssi, date_time, time_diff_lead, reader_diff
FROM
    (
    SELECT doc->>'sensorId' as sensor_id, doc->>'readerId' as reader_id, (doc->>'rssi')::int as rssi, created_at as date_time,
    EXTRACT(EPOCH FROM lead(created_at) OVER w - created_at) as time_diff_lead,
    (lead(doc->>'readerId') OVER w)::int - (doc->>'readerId')::int as reader_diff
    FROM public.sensor_data
    WINDOW w AS (PARTITION BY doc->>'sensorId' ORDER BY created_at)
    ) as x
WHERE rssi > 380 OR time_diff_lead > 18.0 AND reader_diff = 0
ORDER BY sensor_id, date_time

The WHERE clause defines the conditions I would like to use to create a boolean column.

All of this data comes from a table with a jsonB column and for efficiency (I think...) I would need to add this column to that table, by the correct keys.

That table will be updated at least every 30 seconds with a new record. And the query above will be ran less often than that. So there will be nulls in that column. In a general sense how would that affect querying to that table? (new to data science)

I am in a start up and trying to lay the foundations of our data gathering (and they have ME doing it :P) so please rip my code apart and point me to better methods!

Body:
A condition is a boolean type, so you can just select the value you get from the boolean condition and give it a alias:

SELECT sensor_id, reader_id, rssi, date_time
 , time_diff_lead, reader_diff
 , (rssi > 380 OR time_diff_lead > 18.0 AND reader_diff = 0) AS bull
FROM    (
    SELECT doc->>'sensorId' as sensor_id, doc->>'readerId' as reader_id
     , (doc->>'rssi')::int as rssi, created_at as date_time
    ,  EXTRACT(EPOCH FROM lead(created_at) OVER w - created_at) as time_diff_lead
    , (lead(doc->>'readerId') OVER w)::int - (doc->>'readerId')::int as reader_diff
    FROM public.sensor_data
    WINDOW w AS (PARTITION BY doc->>'sensorId' ORDER BY created_at)
    ) as x
ORDER BY sensor_id, date_time
;

[updated] using the computed columns will need the condition to be pulled to the main query.


问:
Linq: help me to make this work
I have this column:

```<code>    PersonId   CategoryId   SubCategoryId
1      61           47
2      61           48
3      61           0           424
4      61           0           425
5      84           55
6      61                       585
7      101          48
8      101                      424
8      666          47
10     666                      424
</code>```

When i search only for categoryId its fine, and subCategoryId its fine, but when i search for both, like categoryId = 47 && subCategoryId = 424.
I cant make it work... in this case i only need person 61 and person 666.

i can do with a foreach, but not a good idea for performance.

u guys can help me?

```<code>if (ids.IdCategory != null && ids.IdSubCategory != null)
{
    query = unitOfWork.PersonSkillsRepository.GetAll().Where(m => m.IdCategory == ids.IdCategory || m.IdSubCategory == ids.IdSubCategory);
}
else if (ids.IdCategory != null)
    query = unitOfWork.PersonSkillsRepository.GetAll().Where(m => m.IdCategory == ids.IdCategory);
else
    query = unitOfWork.PersonSkillsRepository.GetAll().Where(m => m.IdSubCategory == ids.IdSubCategory);
</code>```

first case i get half what i want... but i want some way to filter, because in this way i get 101 too and i dont know how to see if people have both category and subcategory

and i cant see a way to do this without a foreach

答:
Well, while I was working on mine, it seems 3 other people came up with the same thing, so I'll throw in mine --- with the critical addition the OP needs....

```<code>Func<IGrouping<int, CollectionObject>, bool> query  =
        gp=>
              gp.Any(g=>g.CategoryID == 47) &&
              gp.Any(g=>g.SubcategoryID == 424);

var q = (from p in ColObj
        group p by p.PersonID)
        .Where(query);
</code>```

You'll need to replace  query with your one-field versions on occasion.

Title: Linq: help me to make this work

Body:
I have this column:

    PersonId   CategoryId   SubCategoryId
1      61           47
2      61           48
3      61           0           424
4      61           0           425
5      84           55
6      61                       585
7      101          48
8      101                      424
8      666          47
10     666                      424

When i search only for categoryId its fine, and subCategoryId its fine, but when i search for both, like categoryId = 47 && subCategoryId = 424.
I cant make it work... in this case i only need person 61 and person 666.

i can do with a foreach, but not a good idea for performance.

u guys can help me?

if (ids.IdCategory != null && ids.IdSubCategory != null)
{
    query = unitOfWork.PersonSkillsRepository.GetAll().Where(m => m.IdCategory == ids.IdCategory || m.IdSubCategory == ids.IdSubCategory);
}
else if (ids.IdCategory != null)
    query = unitOfWork.PersonSkillsRepository.GetAll().Where(m => m.IdCategory == ids.IdCategory);
else
    query = unitOfWork.PersonSkillsRepository.GetAll().Where(m => m.IdSubCategory == ids.IdSubCategory);

first case i get half what i want... but i want some way to filter, because in this way i get 101 too and i dont know how to see if people have both category and subcategory

and i cant see a way to do this without a foreach

Body:
Well, while I was working on mine, it seems 3 other people came up with the same thing, so I'll throw in mine --- with the critical addition the OP needs....

Func<IGrouping<int, CollectionObject>, bool> query  =
        gp=>
              gp.Any(g=>g.CategoryID == 47) &&
              gp.Any(g=>g.SubcategoryID == 424);

var q = (from p in ColObj
        group p by p.PersonID)
        .Where(query);

You'll need to replace  query with your one-field versions on occasion.


问:
Php script, query ran from value thats passed in
I am pretty new at php, quick note this is an android application that i am calling this script, I am not having the users make up the script lol. There is a series of checkboxs and when they check off certain ones it appends a script to the string builder. i am trying to run a query based on the value of a variable that is being passed in. Usually i do something like this,

```<code>   mssql_query("UPDATE Userdata SET BrowseScript = '".$_REQUEST['sqlscript']."'
WHERE Userdata.Username = '".$_REQUEST['Username']."'");
</code>```

and where it says .$_REQUEST[''] I can grab values that i pass in.

But this time the .$_REQUEST[''] is the whole script, so i want something like this

```<code>mssql_query($_REQUEST['sqlscript']);
</code>```

and thats it i want it to run the query thats in that value, The query is correct, but it just will not return any value, I think i may have some type of syntax error or something, like i said i am new to php. Thanks for any help. Also I am not posting the whole code because everything is running ok, i just cant get that query to run. so all i need assistance with is the mssql_query part thanks again.

答:
First of all there is huge security flaw in what you are doing. You should always sanitalize and escape the variables you use in your queries for example using mysql_real_escape_string or prepared statements.

Since you are importing whole script for your query, it could be that quotes are not escaped. You need to put these functions like this before your variables:

```<code>mysql_real_escape_string($_REQUEST['your_var']);
</code>```

Using $_REQUEST in itself instead of proper $_GET or $_POST is vulnerable.

Body:
I am pretty new at php, quick note this is an android application that i am calling this script, I am not having the users make up the script lol. There is a series of checkboxs and when they check off certain ones it appends a script to the string builder. i am trying to run a query based on the value of a variable that is being passed in. Usually i do something like this,

   mssql_query("UPDATE Userdata SET BrowseScript = '".$_REQUEST['sqlscript']."'
WHERE Userdata.Username = '".$_REQUEST['Username']."'");

and where it says .$_REQUEST[''] I can grab values that i pass in.

But this time the .$_REQUEST[''] is the whole script, so i want something like this

mssql_query($_REQUEST['sqlscript']);

and thats it i want it to run the query thats in that value, The query is correct, but it just will not return any value, I think i may have some type of syntax error or something, like i said i am new to php. Thanks for any help. Also I am not posting the whole code because everything is running ok, i just cant get that query to run. so all i need assistance with is the mssql_query part thanks again.

Body:
First of all there is huge security flaw in what you are doing. You should always sanitalize and escape the variables you use in your queries for example using mysql_real_escape_string or prepared statements.

Since you are importing whole script for your query, it could be that quotes are not escaped. You need to put these functions like this before your variables:

mysql_real_escape_string($_REQUEST['your_var']);

Using $_REQUEST in itself instead of proper $_GET or $_POST is vulnerable.


问:
Efficient way to run a function over the columns of a pandas Dataframe?
I want to run a function over the columns of a Pandas Dataframe.
Corpus is a pd.Dataframe

```<code>import pandas as pd
import numpy as np
from scipy.spatial.distance import cosine

corpus = pd.DataFrame([[3,1,1,1,1,60],[2,2,0,2,0,20], [0,2,1,1,0,0], [0,0,2,1,0,1],[0,0,0,0,1,0]],index=["stark","groß","schwach","klein", "dick"],columns=["d1", "d2", "d3","d4","d5","d6"])
</code>```

And I have query. Query is a Pandas Series.

```<code>query = pd.Series([1,1,0,0,0], index=["stark","groß","schwach","klein", "dick"])
</code>```

Now I want to run the cosine function over every column in corpus and the query.

```<code>for column in corpus:
print("Similarity of Documents", column," and query: \n" ,1-cosine(query, corpus[column]))
</code>```

Is there a better way to run the cosine fuction over the columns? Maybe some method that gets the columns and runs the function over every column. I want to avoid the for Loop.

答:
You could use scipy.spatial.distance.cdist's 'cosine' functionality for a vectorized soliution, like so -

```<code>from scipy.spatial.distance import cdist

out = 1-cdist(query.values[None], corpus.values.T, 'cosine')
</code>```

Sample run -

```<code>In [192]: corpus
Out[192]:
         d1  d2  d3  d4  d5  d6
stark     3   1   1   1   1  60
groß      2   2   0   2   0  20
schwach   0   2   1   1   0   0
klein     0   0   2   1   0   1
dick      0   0   0   0   1   0

In [193]: query
Out[193]:
stark      1
groß       1
schwach    0
klein      0
dick       0
dtype: int64

In [194]: from scipy.spatial.distance import cosine

In [195]: for column in corpus:
     ...:     print(1-cosine(query, corpus[column]))
     ...:
0.980580675691
0.707106781187
0.288675134595
0.801783725737
0.5
0.89431540856

In [196]: 1-cdist(query.values[None], corpus.values.T, 'cosine')
Out[196]: array([[ 0.98058,  0.70711,  0.28868,  0.80178,  0.5    ,  0.89432]])
</code>```

Runtime test -

```<code>In [225]: corpus = pd.DataFrame(np.random.rand(100,10000))

In [226]: query = pd.Series(np.random.rand(100))

# @C.Square's apply based soln
In [227]: %timeit corpus.apply(lambda x:1-cosine(query, x), axis=0)
1 loop, best of 3: 352 ms per loop

 # Proposed in this post using cdist()
In [228]: %timeit 1-cdist(query.values[None], corpus.values.T, 'cosine')
100 loops, best of 3: 3.2 ms per loop
</code>```

Body:
I want to run a function over the columns of a Pandas Dataframe.
Corpus is a pd.Dataframe

import pandas as pd
import numpy as np
from scipy.spatial.distance import cosine

corpus = pd.DataFrame([[3,1,1,1,1,60],[2,2,0,2,0,20], [0,2,1,1,0,0], [0,0,2,1,0,1],[0,0,0,0,1,0]],index=["stark","groß","schwach","klein", "dick"],columns=["d1", "d2", "d3","d4","d5","d6"])

And I have query. Query is a Pandas Series.

query = pd.Series([1,1,0,0,0], index=["stark","groß","schwach","klein", "dick"])

Now I want to run the cosine function over every column in corpus and the query.

for column in corpus:
print("Similarity of Documents", column," and query: \n" ,1-cosine(query, corpus[column]))

Is there a better way to run the cosine fuction over the columns? Maybe some method that gets the columns and runs the function over every column. I want to avoid the for Loop.

Body:
You could use scipy.spatial.distance.cdist's 'cosine' functionality for a vectorized soliution, like so -

from scipy.spatial.distance import cdist

out = 1-cdist(query.values[None], corpus.values.T, 'cosine')

Sample run -

In [192]: corpus
Out[192]:
         d1  d2  d3  d4  d5  d6
stark     3   1   1   1   1  60
groß      2   2   0   2   0  20
schwach   0   2   1   1   0   0
klein     0   0   2   1   0   1
dick      0   0   0   0   1   0

In [193]: query
Out[193]:
stark      1
groß       1
schwach    0
klein      0
dick       0
dtype: int64

In [194]: from scipy.spatial.distance import cosine

In [195]: for column in corpus:
     ...:     print(1-cosine(query, corpus[column]))
     ...:
0.980580675691
0.707106781187
0.288675134595
0.801783725737
0.5
0.89431540856

In [196]: 1-cdist(query.values[None], corpus.values.T, 'cosine')
Out[196]: array([[ 0.98058,  0.70711,  0.28868,  0.80178,  0.5    ,  0.89432]])

Runtime test -

In [225]: corpus = pd.DataFrame(np.random.rand(100,10000))

In [226]: query = pd.Series(np.random.rand(100))

# @C.Square's apply based soln
In [227]: %timeit corpus.apply(lambda x:1-cosine(query, x), axis=0)
1 loop, best of 3: 352 ms per loop

 # Proposed in this post using cdist()
In [228]: %timeit 1-cdist(query.values[None], corpus.values.T, 'cosine')
100 loops, best of 3: 3.2 ms per loop


问:
Reducer returned undefined during initialization but am returning initialState as default in reducer switch
I am attempting to follow the instructions found in the redux-persist docs to delay the render until rehydration is complete, and I am now receiving this error

"Reducer 'auth' returned undefined during initialization. If the state passed to the reducer is undefined, you must explicitly return the initial state. The initial state may not be undefined."

However, I am defining and returning the initialState in my auth reducer as follows:

```<code>const initialState = {
    authenticated: false,
    authenticating: false,
    loginError: '',
}
export default function reducer(state = initialState, action) {
    switch (action.type) {
        ...my switch cases here

        default:
        return state
    }
}
</code>```

I did not change how I am creating my store so I am not sure why I am now receiving this error. I will also include my store creation and combine reducers method below

```<code>const store = createStore(
    reducers,
    undefined,
    compose(
        applyMiddleware(thunk),
        autoRehydrate({ log: true }),
        window.devToolsExtension ? window.devToolsExtension() : (f) => f
    )
)

export default class AppProvider extends Component {
  constructor(props) {
    super(props)
    this.state = {
      rehydrated: false,
    }
  }

  componentWillMount() {
    persistStore(store, {storage: AsyncStorage}, () => {
      this.setState({ rehydrated: true })
    })
  }

  render() {
    if (!this.state.rehydrated) {
      return <ActivityIndicator />
    }
    return (
      <Provider store={store}>
      <App/>
      </Provider>
    )
  }
}
</code>```

My reducers export file

```<code>export default reducers = combineReducers({
    auth,
    connection,
    initialLoad,
    queue,
})
</code>```

答:
It seems to be something on your store creation. The F8App is a good reference for this.

You can do the following:

```<code>// configureStore.js
// ... imports

const middlewares = [thunk, promise, array];
var createAppStore = applyMiddleware(...middlewares)(createStore);

export default configureStore = (onComplete) => {
    const store = autoRehydrate()(createAppStore)(reducers);
    persistStore(store, { storage: AsyncStorage }, onComplete);
    return store;
}

// AppProvider.js
// ...
    constructor() {
        super();
        this.state = {
            isLoading: true,
            store: configureStore(() => {
                this.setState({ isLoading: false });
            }),
        };
    }
    render() {
        if (this.state.isLoading) {
            return <ActivityIndicator />;
        }
        return (
            <Provider store={this.state.store}>
                <App />
            </Provider>
        );
    }
// ...
</code>```

Body:
I am attempting to follow the instructions found in the redux-persist docs to delay the render until rehydration is complete, and I am now receiving this error

"Reducer 'auth' returned undefined during initialization. If the state passed to the reducer is undefined, you must explicitly return the initial state. The initial state may not be undefined."

However, I am defining and returning the initialState in my auth reducer as follows:

const initialState = {
    authenticated: false,
    authenticating: false,
    loginError: '',
}
export default function reducer(state = initialState, action) {
    switch (action.type) {
        ...my switch cases here

        default:
        return state
    }
}

I did not change how I am creating my store so I am not sure why I am now receiving this error. I will also include my store creation and combine reducers method below

const store = createStore(
    reducers,
    undefined,
    compose(
        applyMiddleware(thunk),
        autoRehydrate({ log: true }),
        window.devToolsExtension ? window.devToolsExtension() : (f) => f
    )
)

export default class AppProvider extends Component {
  constructor(props) {
    super(props)
    this.state = {
      rehydrated: false,
    }
  }

  componentWillMount() {
    persistStore(store, {storage: AsyncStorage}, () => {
      this.setState({ rehydrated: true })
    })
  }

  render() {
    if (!this.state.rehydrated) {
      return <ActivityIndicator />
    }
    return (
      <Provider store={store}>
      <App/>
      </Provider>
    )
  }
}

My reducers export file

export default reducers = combineReducers({
    auth,
    connection,
    initialLoad,
    queue,
})

Body:
It seems to be something on your store creation. The F8App is a good reference for this.

You can do the following:

// configureStore.js
// ... imports

const middlewares = [thunk, promise, array];
var createAppStore = applyMiddleware(...middlewares)(createStore);

export default configureStore = (onComplete) => {
    const store = autoRehydrate()(createAppStore)(reducers);
    persistStore(store, { storage: AsyncStorage }, onComplete);
    return store;
}

// AppProvider.js
// ...
    constructor() {
        super();
        this.state = {
            isLoading: true,
            store: configureStore(() => {
                this.setState({ isLoading: false });
            }),
        };
    }
    render() {
        if (this.state.isLoading) {
            return <ActivityIndicator />;
        }
        return (
            <Provider store={this.state.store}>
                <App />
            </Provider>
        );
    }
// ...


问:
JSON Deserializing string value to List<T> using Newtonsoft - constructor arg is null in C#
I am using Newtonsoft libraries for serialization and deserialization json object.
The reference code is below:

```<code> public abstract class BaseNode
{
    [JsonConstructor]
    protected BaseNode(string [] specifications)
    {
        if (specifications == null)
        {
            throw new ArgumentNullException();
        }
        if (specifications.Length == 0)
        {
            throw new ArgumentException();
        }

        Name = specifications[0];
        Identifier = specifications[1];
        //Owner = specifications[2];
    }

    public string Name{ get; protected set; }
    public string Identifier { get; protected set; }
    public string Owner { get; protected set; }
}

public class ComputerNode: BaseNode
{
    [JsonConstructor]
    public ComputerNode(string[] specifications):base(specifications)
    {
        Owner = specifications[2];
    }
}
</code>```

Serialization works fine and I can save the json formatted data in a file. I am storing a list of ComputerNode objects in a file.
Following code for file read/write operation:

```<code>public class Operation<T>
{
    public string path;

    public Operation()
    {
        var path = Path.Combine(Directory.GetCurrentDirectory(), "nodes.txt");

        if (File.Exists(path) == false)
        {
            using (File.Create(path))
            {
            }
        }
        this.path = path;
    }

    public void Write(string path, List<T> nodes)
    {
        var ser = JsonConvert.SerializeObject(nodes);

        File.WriteAllText(path, ser);
    }

    public List<T> Read(string path)
    {
        var text = File.ReadAllText(path);

        var res =  JsonConvert.DeserializeObject<List<T>>(text);
        return res;
    }

}
</code>```

The expected file Read result should be a list of ComputerNode objects stored in a file.
However, while deserialization - creating an object of ComputerNode, correct constructor is called but the argument (string[] specifications) is null.

Is there any better way to work with it.

Please do not suggest to change BaseNode.cs or ComputerNode.cs

Thanks for suggestion...

Correct Answer

Overridden with new Json constructor. In BaseNode.cs

```<code>    [JsonConstructor]
    public BaseNode(string Owner, string Name, string Identifier)
    {
        this.Name = Name;
        this.Identifier = Identifier;
    }
</code>```

and
Overridden a Json constructor - ComputerNode.cs

```<code>    [JsonConstructor]
    public ComputerNode(string Owner, string Name, string Identifier):base(Owner, Name, Identifier)
    {
        this.Owner = Owner;
    }
</code>```

答:
https://stackoverflow.com/a/23017892/34092 states:

It is important that the constructor parameter names match the
  corresponding property names of the JSON object for this to work
  correctly.

Your constructor parameter is called specifications. There is no property in the JSON with the name of specifications. This is why the value is passed as null.

See also http://www.newtonsoft.com/json/help/html/JsonConstructorAttribute.htm .

Body:
I am using Newtonsoft libraries for serialization and deserialization json object.
The reference code is below:

 public abstract class BaseNode
{
    [JsonConstructor]
    protected BaseNode(string [] specifications)
    {
        if (specifications == null)
        {
            throw new ArgumentNullException();
        }
        if (specifications.Length == 0)
        {
            throw new ArgumentException();
        }

        Name = specifications[0];
        Identifier = specifications[1];
        //Owner = specifications[2];
    }

    public string Name{ get; protected set; }
    public string Identifier { get; protected set; }
    public string Owner { get; protected set; }
}

public class ComputerNode: BaseNode
{
    [JsonConstructor]
    public ComputerNode(string[] specifications):base(specifications)
    {
        Owner = specifications[2];
    }
}

Serialization works fine and I can save the json formatted data in a file. I am storing a list of ComputerNode objects in a file.
Following code for file read/write operation:

public class Operation<T>
{
    public string path;

    public Operation()
    {
        var path = Path.Combine(Directory.GetCurrentDirectory(), "nodes.txt");

        if (File.Exists(path) == false)
        {
            using (File.Create(path))
            {
            }
        }
        this.path = path;
    }

    public void Write(string path, List<T> nodes)
    {
        var ser = JsonConvert.SerializeObject(nodes);

        File.WriteAllText(path, ser);
    }

    public List<T> Read(string path)
    {
        var text = File.ReadAllText(path);

        var res =  JsonConvert.DeserializeObject<List<T>>(text);
        return res;
    }

}

The expected file Read result should be a list of ComputerNode objects stored in a file.
However, while deserialization - creating an object of ComputerNode, correct constructor is called but the argument (string[] specifications) is null.

Is there any better way to work with it.

Please do not suggest to change BaseNode.cs or ComputerNode.cs

Thanks for suggestion...

Correct Answer

Overridden with new Json constructor. In BaseNode.cs

    [JsonConstructor]
    public BaseNode(string Owner, string Name, string Identifier)
    {
        this.Name = Name;
        this.Identifier = Identifier;
    }

and
Overridden a Json constructor - ComputerNode.cs

    [JsonConstructor]
    public ComputerNode(string Owner, string Name, string Identifier):base(Owner, Name, Identifier)
    {
        this.Owner = Owner;
    }


问:
Is there a way to use gitlab command line export functionalities on a Windows 10 server?
I am setting up a gitlab project for my team's workflow, but the catch is that we all use Windows 10. I installed gitlab on my Windows 10 workstation, but could not configure it because the "bash for windows" feature does not include an actual ubantu kernel, and therefore does not have a /com directory, which gitlab configuration needs. I would like to set up a nightly service to run gitlab's export commands on a Windows 10 server. Has anyone figured out how to either run gitlab on Windows 10 or export in another way?

This is the code I was planning to use if gitlab had configured correctly:

```<code>    sudo -u git -H bundle exec rake gitlab:backup:create RAILS_ENV=production
</code>```

答:
GitLab is not supported on Windows.

If you proceed this will be just the beginning of your struggles.

Instead, simply install a Linux VM and install GitLab there.

Body:
I am setting up a gitlab project for my team's workflow, but the catch is that we all use Windows 10. I installed gitlab on my Windows 10 workstation, but could not configure it because the "bash for windows" feature does not include an actual ubantu kernel, and therefore does not have a /com directory, which gitlab configuration needs. I would like to set up a nightly service to run gitlab's export commands on a Windows 10 server. Has anyone figured out how to either run gitlab on Windows 10 or export in another way?

This is the code I was planning to use if gitlab had configured correctly:

    sudo -u git -H bundle exec rake gitlab:backup:create RAILS_ENV=production


答:
The main cause is that you pass in undefined as the preloaded state. Just pass in your root reducer and middlewares and the error should disappear

```<code>const store = createStore(
    reducers,
    compose(
        applyMiddleware(thunk),
        autoRehydrate({ log: true }),
        window.devToolsExtension ? window.devToolsExtension() : (f) => f
    )
)
</code>```

Also, It is complaining that auth is undefined, so you should make sure that all of your reducers are imported correctly in the root reducer reducers.

Title: Reducer returned undefined during initialization but am returning initialState as default in reducer switch

Body:
The main cause is that you pass in undefined as the preloaded state. Just pass in your root reducer and middlewares and the error should disappear

const store = createStore(
    reducers,
    compose(
        applyMiddleware(thunk),
        autoRehydrate({ log: true }),
        window.devToolsExtension ? window.devToolsExtension() : (f) => f
    )
)

Also, It is complaining that auth is undefined, so you should make sure that all of your reducers are imported correctly in the root reducer reducers.


问:
Pandas/Google BigQuery: Schema mismatch makes the upload fail
The schema in my google table looks like this:

```<code>price_datetime : DATETIME,
symbol         : STRING,
bid_open       : FLOAT,
bid_high       : FLOAT,
bid_low        : FLOAT,
bid_close      : FLOAT,
ask_open       : FLOAT,
ask_high       : FLOAT,
ask_low        : FLOAT,
ask_close      : FLOAT
</code>```

After I do a pandas.read_gbq I get a dataframe with column dtypes like this:

```<code>price_datetime     object
symbol             object
bid_open          float64
bid_high          float64
bid_low           float64
bid_close         float64
ask_open          float64
ask_high          float64
ask_low           float64
ask_close         float64
dtype: object
</code>```

Now I want to use to_gbq so I convert my local dataframe (which I just made) from these dtypes:

```<code>price_datetime    datetime64[ns]
symbol                    object
bid_open                 float64
bid_high                 float64
bid_low                  float64
bid_close                float64
ask_open                 float64
ask_high                 float64
ask_low                  float64
ask_close                float64
dtype: object
</code>```

to these dtypes:

```<code>price_datetime     object
symbol             object
bid_open          float64
bid_high          float64
bid_low           float64
bid_close         float64
ask_open          float64
ask_high          float64
ask_low           float64
ask_close         float64
dtype: object
</code>```

by doing:

```<code>df['price_datetime'] = df['price_datetime'].astype(object)
</code>```

Now I (think) I am read to use to_gbq so I do:

```<code>import pandas
pandas.io.gbq.to_gbq(df, <table_name>, <project_name>, if_exists='append')
</code>```

but I get the error:

```<code>---------------------------------------------------------------------------
InvalidSchema                             Traceback (most recent call last)
<ipython-input-15-d5a3f86ad382> in <module>()
      1 a = time.time()
----> 2 pandas.io.gbq.to_gbq(df, <table_name>, <project_name>, if_exists='append')
      3 b = time.time()
      4
      5 print(b-a)

C:\Users\me\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\io\gbq.py in to_gbq(dataframe, destination_table, project_id, chunksize, verbose, reauth, if_exists, private_key)
    825         elif if_exists == 'append':
    826             if not connector.verify_schema(dataset_id, table_id, table_schema):
--> 827                 raise InvalidSchema("Please verify that the structure and "
    828                                     "data types in the DataFrame match the "
    829                                     "schema of the destination table.")

InvalidSchema: Please verify that the structure and data types in the DataFrame match the schema of the destination table.
</code>```

答:
I had to do two things that solved the issue for me. First, I deleted my table and reuploaded it with the columns as TIMESTAMP types rather than DATETIME types. This made sure that the schema matched when the pandas.DataFrame with column type datetime64[ns] was uploaded to using to_gbq, which converts datetime64[ns] to TIMESTAMP type and not to DATETIME type (for now).

The second thing I did was upgrade from pandas 0.19 to pandas 0.20. These two things solved my problem of a schema mismatch.

Body:
The schema in my google table looks like this:

price_datetime : DATETIME,
symbol         : STRING,
bid_open       : FLOAT,
bid_high       : FLOAT,
bid_low        : FLOAT,
bid_close      : FLOAT,
ask_open       : FLOAT,
ask_high       : FLOAT,
ask_low        : FLOAT,
ask_close      : FLOAT

After I do a pandas.read_gbq I get a dataframe with column dtypes like this:

price_datetime     object
symbol             object
bid_open          float64
bid_high          float64
bid_low           float64
bid_close         float64
ask_open          float64
ask_high          float64
ask_low           float64
ask_close         float64
dtype: object

Now I want to use to_gbq so I convert my local dataframe (which I just made) from these dtypes:

price_datetime    datetime64[ns]
symbol                    object
bid_open                 float64
bid_high                 float64
bid_low                  float64
bid_close                float64
ask_open                 float64
ask_high                 float64
ask_low                  float64
ask_close                float64
dtype: object

to these dtypes:

price_datetime     object
symbol             object
bid_open          float64
bid_high          float64
bid_low           float64
bid_close         float64
ask_open          float64
ask_high          float64
ask_low           float64
ask_close         float64
dtype: object

by doing:

df['price_datetime'] = df['price_datetime'].astype(object)

Now I (think) I am read to use to_gbq so I do:

import pandas
pandas.io.gbq.to_gbq(df, <table_name>, <project_name>, if_exists='append')

but I get the error:

---------------------------------------------------------------------------
InvalidSchema                             Traceback (most recent call last)
<ipython-input-15-d5a3f86ad382> in <module>()
      1 a = time.time()
----> 2 pandas.io.gbq.to_gbq(df, <table_name>, <project_name>, if_exists='append')
      3 b = time.time()
      4
      5 print(b-a)

C:\Users\me\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\io\gbq.py in to_gbq(dataframe, destination_table, project_id, chunksize, verbose, reauth, if_exists, private_key)
    825         elif if_exists == 'append':
    826             if not connector.verify_schema(dataset_id, table_id, table_schema):
--> 827                 raise InvalidSchema("Please verify that the structure and "
    828                                     "data types in the DataFrame match the "
    829                                     "schema of the destination table.")

InvalidSchema: Please verify that the structure and data types in the DataFrame match the schema of the destination table.


问:
Add gutter on masonry with the bootstrap3 grid
I'm having trouble with coding gutter on masonry with the bootstrap3 grid.

This is my jsfiddle.   https://jsfiddle.net/shelly_W/bg67fdjm/

```<code><div class="container bg">
<h1>Masonry - Bootstrap 3 grid media queries</h1>
<!-- add extra container element for Masonry -->
<div class="grid">
<div class="grid-sizer col-xs-6 col-sm-4"></div>
<div class="grid-item col-xs-12 col-sm-8 col-md-8 ">
<!-- add inner element for column content -->
<div class="grid-item-content grid-item-content--height400">1</div>
</div>
<div class="grid-item col-xs-12 col-sm-4 col-md-4">
<div class="grid-item-content grid-item-content--height230">2</div>
</div>
<div class="grid-item col-xs-12 col-sm-4 col-md-4">
<div class="grid-item-content grid-item-content--height443">3</div>
</div>
<div class="grid-item col-xs-12 col-sm-4 col-md-4">
<div class="grid-item-content grid-item-content--height230">4</div>
</div>
<div class="grid-item col-xs-12 col-sm-4 col-md-4">
<div class="grid-item-content grid-item-content--height518">5</div>
</div>
<div class="grid-item col-xs-12 col-sm-4 col-md-4">
<div class="grid-item-content grid-item-content--height518">6</div>
</div>
<div class="grid-item col-xs-12 col-sm-4 col-md-4">
<div class="grid-item-content grid-item-content--height230">7</div>
</div>
<div class="grid-item col-xs-12 col-sm-8 col-md-8">
<div class="grid-item-content grid-item-content--height230">8</div>
</div>
</div>
</code>```

Source is: https://masonry.desandro.com/

What I’m trying to achieve is having 15px gutters between the masonry grid. I want to create a space between grid 1 and grid 2. I don’t want padding on either of the outer container div edges of grid 1 or grid 2.
I attempted to insert a 15px gutter by js, but this approach breaks the bootstrap responsive columns.

I’ve been trying to work this out for some time, but I can't figure out the right approach. Does anyone have any suggestions on how I might resolve this issue?

Please let me know if you need any further information.
Thank you in advance for your help!

答:
If you want a solution that goes all the way to the edges and maintains a 15px gutter, you can keep your padding and use the CSS calc() method to adjust for the responsive container.

```<code>.grid-sizer { width:calc(33.33% - 10px); }
.grid-item { width: calc(33.33% - 10px); }
.grid-item--width2 { width: calc(66.66% - 5px); }
</code>```

Then you just need to add media queries to your CSS to responsively change the width of the items:

```<code>@media (max-width: 500px) {
  .grid-sizer { width:calc(50% - 7.5px); }
  .grid-item { width: calc(50% - 7.5px); }
  .grid-item--width2 { width: 100%; }
}
@media (max-width: 350px) {
  .grid-sizer { width:100%; }
  .grid-item { width: 100%; }
}
</code>```

Check out this fiddle:
JSFiddle

Body:
I'm having trouble with coding gutter on masonry with the bootstrap3 grid.

This is my jsfiddle.   https://jsfiddle.net/shelly_W/bg67fdjm/

Masonry - Bootstrap 3 grid media queries

1

2

3

4

5

6

7

8

Source is: https://masonry.desandro.com/

What I’m trying to achieve is having 15px gutters between the masonry grid. I want to create a space between grid 1 and grid 2. I don’t want padding on either of the outer container div edges of grid 1 or grid 2.
I attempted to insert a 15px gutter by js, but this approach breaks the bootstrap responsive columns.

I’ve been trying to work this out for some time, but I can't figure out the right approach. Does anyone have any suggestions on how I might resolve this issue?

Please let me know if you need any further information.
Thank you in advance for your help!

Body:
If you want a solution that goes all the way to the edges and maintains a 15px gutter, you can keep your padding and use the CSS calc() method to adjust for the responsive container.

.grid-sizer { width:calc(33.33% - 10px); }
.grid-item { width: calc(33.33% - 10px); }
.grid-item--width2 { width: calc(66.66% - 5px); }

Then you just need to add media queries to your CSS to responsively change the width of the items:

@media (max-width: 500px) {
  .grid-sizer { width:calc(50% - 7.5px); }
  .grid-item { width: calc(50% - 7.5px); }
  .grid-item--width2 { width: 100%; }
}
@media (max-width: 350px) {
  .grid-sizer { width:100%; }
  .grid-item { width: 100%; }
}

Check out this fiddle:
JSFiddle


问:
Spotfire get row
anyone know how to reduce the number of returned results from an information link? Something like this </p>

```<code>SELECT
  R1."COLUMN NAME"
  R1."COLUMN NAME 2"
  R1."COLUMN NAME 3"
FROM
   "TABLENAME"
WHERE
ROWNUM <
    (SELECT COUNT - 500000
     FROM TABLENAME)
</code>```

答:
In the information designer...

Double click on your Information Link to bring up the Edit Window

At the very bottom, click the SQL button

In the Modified SQL: window, add the conditions you want to the WHERE clause

Pay attention to how Spotfire quotes and aliases your statement and follow this design. i.e. (SQL Server example)

FROM
   "Server"."schema"."TABLE" A1
WHERE
   A1."SomeColumn" = "some value"

SQL Server doesn't use double quotes, or even single quotes on table and server names, but you have to in this designer.  Anyway, modify the statement as you need and click OK. That's it!

Title: Spotfire get row

Body:
anyone know how to reduce the number of returned results from an information link? Something like this

SELECT
  R1."COLUMN NAME"
  R1."COLUMN NAME 2"
  R1."COLUMN NAME 3"
FROM
   "TABLENAME"
WHERE
ROWNUM <
    (SELECT COUNT - 500000
     FROM TABLENAME)


问:
How does app know if it started from a crash
Whenever I start the app I want to know if the app recovered from a crash. Can I store it in a flag ?

Do the crash and regular app exit scenario go through the same steps(lifecycle) in android ?

答:
You don't get this information at all from the Android SDK. There are two options you could try, first is would be to have extensive logging/tracking of the apps life-cycle. In all of your activities keep track of when you activities are started, resumed, paused, stopped, and destroyed. (Also handle special usecase of when the device is rotated and the activity will experience a tear-down and restart). From here you will have information of when an activity has been stopped and you check the last state in the onCreate, onStart, or onResume of you activities to make sure that you're expected life-cycles where hit. If not, then you more than likely experienced a crash. Also note, on older version of Android certain teardown life-cycle callbacks weren't guaranteed to be called.

Second option would be to try using Thread.setDefaultUncaughtExceptionHandler. I have never personally used it but it may help in the usecase where an uncaught exception occurs. You could log such an event and check that flag once, the app is resumed. I am not sure of all of the side effects of using this mechanism such as, will this override the default uncaught exception behavior and remove the default stack trace that gets printed out, which would be very very very bad.


答:
There is no way for the app to know whether it started from a crash; this is indistinguishable from starting the application for the first time after booting. In both cases you will see the onCreate lifecycle event for your activity.

If your application crashes, it stops processing lifecycle events. So no, lifecycle events will not be processed in the same way.

If you want to know whether your application is crashing, perhaps a better approach is to directly record when the application crashes. There are tools like Errbit that help record this when the application is running on general users' devices.

Title: How does app know if it started from a crash

Body:
Whenever I start the app I want to know if the app recovered from a crash. Can I store it in a flag ?

Do the crash and regular app exit scenario go through the same steps(lifecycle) in android ?


问:
Pandas Dataframe cutting off extra digits from excel import
I am reading in an excel sheet into the dataframe, which has worked great. However, one of the columns in the excel sheet has an ID number which is forced to 5 forward digits. Thus, rather than 32, the excel sheet has 00032 and for 500 it would be 00500. When I read this file into pandas however it converts these numbers to it's base value, thus 00500 becomes 500 in the dataframe. However, as I am trying to match the file names which use the 5 digit index value to the ID number this is actually causing an issue. I would just use a list system but I need pandas to easily access multiple columns of data when iterating through the rows. Here is the gist:

```<code>downloads = r'C:\Users\...'
filelist = os.listdir(downloads)
SDC = []
for file in filelist:
    if file.startswith('sdc'):
        SDC.append(file[3:8])
print SDC
if SDC == []:
    print "There are no downloaded files to grab at this time."

dir = r'C:\...'
os.chdir(dir)
for i, row in df.iterrows():
    if row['SDC ID'] in SDC:
        dir = r'C:\bleh\Temporary Folder' + row['Theme']
        if not os.path.exists(dir):
             os.makedirs(dir)
</code>```

How do I force the original value in pandas to quickly iterate and check values against the list?

答:
The line if row['SDC ID'] in SDC: checks if an integer exists in a list of strings. There are two simple solutions that I can see:

Compare as strings. Format your integer into a string and keep the test mostly as-is. Something like if '{:05d}'.format(row['SDC ID']) in SDC: should do it. It will format your integer to a zero padded five-digit number.

Compare as integers. You can convert the numbers from the file names directly into integers as you find them since you don't appear to be using their string properties anywhere. Change the line SDC.append(file[3:8]) to SDC.append(int(file[3:8])).

Given the information shown, I would prefer the second option, but not by much and for no good reason beyond aesthetics.

Body:
I am reading in an excel sheet into the dataframe, which has worked great. However, one of the columns in the excel sheet has an ID number which is forced to 5 forward digits. Thus, rather than 32, the excel sheet has 00032 and for 500 it would be 00500. When I read this file into pandas however it converts these numbers to it's base value, thus 00500 becomes 500 in the dataframe. However, as I am trying to match the file names which use the 5 digit index value to the ID number this is actually causing an issue. I would just use a list system but I need pandas to easily access multiple columns of data when iterating through the rows. Here is the gist:

downloads = r'C:\Users\...'
filelist = os.listdir(downloads)
SDC = []
for file in filelist:
    if file.startswith('sdc'):
        SDC.append(file[3:8])
print SDC
if SDC == []:
    print "There are no downloaded files to grab at this time."

dir = r'C:\...'
os.chdir(dir)
for i, row in df.iterrows():
    if row['SDC ID'] in SDC:
        dir = r'C:\bleh\Temporary Folder' + row['Theme']
        if not os.path.exists(dir):
             os.makedirs(dir)

How do I force the original value in pandas to quickly iterate and check values against the list?