问:
Thumbnail View issue in uploaded PDF file (Angular 2)
I'm new in angular 2 . I tried to upload a PDF and show its thumbnail in UI  using ng2-pdf-viewer but i'm facing some error like this.

```<code>AppComponent.html:10 ERROR Error: Invalid parameter object: need either .data, .range or .url
    at error (pdf.combined.js:357)
    at Object.getDocument (pdf.combined.js:11832)
    at PdfViewerComponent.webpackJsonp../node_modules/ng2-pdf-viewer/dist/pdf-viewer.component.js.PdfViewerComponent.loadPDF (pdf-viewer.component.js:89)
    at PdfViewerComponent.webpackJsonp../node_modules/ng2-pdf-viewer/dist/pdf-viewer.component.js.PdfViewerComponent.ngOnChanges (pdf-viewer.component.js:78)
    at checkAndUpdateDirectiveInline (core.es5.js:10891)
    at checkAndUpdateNodeInline (core.es5.js:12382)
    at checkAndUpdateNode (core.es5.js:12321)
    at debugCheckAndUpdateNode (core.es5.js:13182)
    at debugCheckDirectivesFn (core.es5.js:13123)
    at Object.eval [as updateDirectives] (AppComponent.html:10)
</code>```

My codes are given below.

app.component

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import {FormsModule} from '@angular/forms';

import { AppComponent } from './app.component';
import { PdfViewerComponent } from 'ng2-pdf-viewer';

@NgModule({
  declarations: [
    AppComponent
  , PdfViewerComponent],
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
platformBrowserDynamic().bootstrapModule(AppModule);
</code>```

app.component.html

```<code><div class="container">
<div class="form-group col-sm-3">
          <label for="">PDF file</label>
          <input type="file"  (change)="fileChange($event)" accept=".pdf">
        </div>
    <div class="row">
        <div class="col-md-5">
            <div class="thumbnail" style="width: 150px;height: 200px;" (click)="pdfShow=!pdfShow">
                <p>click me to view PDF in Iframe!</p>
                <pdf-viewer [src]="fileData"
                            [page]="page"
                            [original-size]="false"
                            style="display: block;"
                 ></pdf-viewer>
            </div>
            <br>
        </div>
        <div class="col-md-7">
            <div *ngIf="pdfShow">
                <h4>PDF in Iframe</h4>
                <iframe width="500" height="600" [src]="fileData" type="application/pdf"></iframe>
            </div>
        </div>
    </div>
</div>
</code>```

app.component.ts

```<code>import { Component } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  pdfSrc;
  ngOnInit() {
  }

  fileData: File;
  fileChange(event) {
    let fileList: FileList = event.target.files;
    if (fileList.length > 0) {
      this.fileData = fileList[0];
    }
  }
}
</code>```

can any one help me.

答:
Made some changes in app.component.html and app.component.ts. Now its  works .

app.component.html

```<code><div class="container">
<div class="form-group col-sm-3">
          <label for="">PDF file</label>
          <input type="file"  (change)="fileChange($event)" accept=".pdf">
        </div>
    <div class="row">
        <div class="col-md-5">
            <div class="thumbnail" style="width: 150px;height: 200px;">
                <pdf-viewer [src]="pdfSrc"
                            [page]="page"
                            [original-size]="false"
                            style="display: block;"
                 ></pdf-viewer>
            </div>
            <br>
        </div>
    </div>
</div>
</code>```

app.component.ts

```<code>import { Component } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  pdfSrc;
  loaded;
  ngOnInit() {
  }

  file: File;
  fileChange(event) {
    let fileList: FileList = event.target.files;
    if (fileList.length > 0) {
     this.handleInputChange(event);
    }
  }

  handleInputChange(e) {
        this.file = e.dataTransfer ? e.dataTransfer.files[0] : e.target.files[0];

        var reader = new FileReader();

        this.loaded = false;
        reader.onload = this._handleReaderLoaded.bind(this);
        reader.readAsDataURL(this.file);
    }

     _handleReaderLoaded(e) {
        var reader = e.target;
        this.pdfSrc = reader.result;
        this.loaded = true;
    }

}
</code>```

Body:
I'm new in angular 2 . I tried to upload a PDF and show its thumbnail in UI  using ng2-pdf-viewer but i'm facing some error like this.

AppComponent.html:10 ERROR Error: Invalid parameter object: need either .data, .range or .url
    at error (pdf.combined.js:357)
    at Object.getDocument (pdf.combined.js:11832)
    at PdfViewerComponent.webpackJsonp../node_modules/ng2-pdf-viewer/dist/pdf-viewer.component.js.PdfViewerComponent.loadPDF (pdf-viewer.component.js:89)
    at PdfViewerComponent.webpackJsonp../node_modules/ng2-pdf-viewer/dist/pdf-viewer.component.js.PdfViewerComponent.ngOnChanges (pdf-viewer.component.js:78)
    at checkAndUpdateDirectiveInline (core.es5.js:10891)
    at checkAndUpdateNodeInline (core.es5.js:12382)
    at checkAndUpdateNode (core.es5.js:12321)
    at debugCheckAndUpdateNode (core.es5.js:13182)
    at debugCheckDirectivesFn (core.es5.js:13123)
    at Object.eval [as updateDirectives] (AppComponent.html:10)

My codes are given below.

app.component

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import {FormsModule} from '@angular/forms';

import { AppComponent } from './app.component';
import { PdfViewerComponent } from 'ng2-pdf-viewer';

@NgModule({
  declarations: [
    AppComponent
  , PdfViewerComponent],
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
platformBrowserDynamic().bootstrapModule(AppModule);

app.component.html

          PDF file
          <input type="file"  (change)="fileChange($event)" accept=".pdf">

click me to view PDF in Iframe!

                <pdf-viewer [src]="fileData"
                            [page]="page"
                            [original-size]="false"
                            style="display: block;"
                 ></pdf-viewer>

PDF in Iframe

app.component.ts

import { Component } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  pdfSrc;
  ngOnInit() {
  }

  fileData: File;
  fileChange(event) {
    let fileList: FileList = event.target.files;
    if (fileList.length > 0) {
      this.fileData = fileList[0];
    }
  }
}

can any one help me.

Body:
Made some changes in app.component.html and app.component.ts. Now its  works .

app.component.html

<div class="container">
<div class="form-group col-sm-3">
          <label for="">PDF file</label>
          <input type="file"  (change)="fileChange($event)" accept=".pdf">
        </div>
    <div class="row">
        <div class="col-md-5">
            <div class="thumbnail" style="width: 150px;height: 200px;">
                <pdf-viewer [src]="pdfSrc"
                            [page]="page"
                            [original-size]="false"
                            style="display: block;"
                 ></pdf-viewer>
            </div>
            <br>
        </div>
    </div>
</div>

app.component.ts

import { Component } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  pdfSrc;
  loaded;
  ngOnInit() {
  }

  file: File;
  fileChange(event) {
    let fileList: FileList = event.target.files;
    if (fileList.length > 0) {
     this.handleInputChange(event);
    }
  }

  handleInputChange(e) {
        this.file = e.dataTransfer ? e.dataTransfer.files[0] : e.target.files[0];

        var reader = new FileReader();

        this.loaded = false;
        reader.onload = this._handleReaderLoaded.bind(this);
        reader.readAsDataURL(this.file);
    }

     _handleReaderLoaded(e) {
        var reader = e.target;
        this.pdfSrc = reader.result;
        this.loaded = true;
    }

}


来源: stackexchange

问:
Overwrite response header in Yesod
How can I overwrite previously set response header in Yesod? When I use the addHeader function, it adds another header with the same name instead of overwriting it. For example, if inside a handler function I do this:

```<code>addHeader "foo" "bar"
addHeader "foo" "baz"
</code>```

I get

```<code>foo: bar
foo: baz
</code>```

but I want to get just

```<code>foo: baz
</code>```

In my case, the header is an authentication token, and it works in a way that if it's present in the request, then I send it back in the response. I implemented this as a middleware. However, if it's a login request, a new token is generated, and it should be sent instead of the value from the request header.

答:
addHeader implementation by Writer.
https://www.stackage.org/haddock/lts-8.21/yesod-core-1.4.35/src/Yesod.Core.Handler.html#addHeaderInternal

It's not possible using addHeader.

It can be achieved by using sendWaiResponse and creating Response by hand, but it's messy.

ContentLicense: CC BY-SA 3.0

Title: Overwrite response header in Yesod

Body:
How can I overwrite previously set response header in Yesod? When I use the addHeader function, it adds another header with the same name instead of overwriting it. For example, if inside a handler function I do this:

addHeader "foo" "bar"
addHeader "foo" "baz"

I get

foo: bar
foo: baz

but I want to get just

foo: baz

In my case, the header is an authentication token, and it works in a way that if it's present in the request, then I send it back in the response. I implemented this as a middleware. However, if it's a login request, a new token is generated, and it should be sent instead of the value from the request header.


问:
Change the default color of materialize.css input fields. I have attached screenshot

I have tried to add custom css, but not worked. I need to change the color of text after selecting the input fields.

```<code><div class="input-field form-group">
    <input id="first_name" class="active validate form-control" name="first_name" type="text" value="">
    <label for="first_name" class="mat-label">First Name</label>
</div>
</code>```

答:
When using Sass, you can change the color scheme of your site
  extremely quickly.

To change the style of input/form you will only have to modify the variables under 10. Forms:
https://github.com/Dogfalo/materialize/blob/master/sass/components/_variables.scss

After changing the values, you need to build the new CSS file using SASS command line

Also check out: http://materializecss.com/sass.html, http://sass-lang.com/

Body:
I have tried to add custom css, but not worked. I need to change the color of text after selecting the input fields.

    <input id="first_name" class="active validate form-control" name="first_name" type="text" value="">
    First Name

ContentLicense: CC BY-SA 4.0


问:
iphone app blank in simulator: moved from 3.1.3 to 4.1
I have a 3.1 xcode project that has been running my app just fine under the 3.1.3 version of the OS.  I've been testing this app on my iphone 3G ( not running IOS 4 ).

I just copied over the XCode project and files, downloaded the latest XCode 3.2.4 with the 4.1 SDK.  When I run my application via the simulator it just comes up blank instead of showing my app.  I can see via the NSLog statements that it's actually getting to my initWithFrame() and viewDidLoad() methods but it's like it didn't load the images correctly.
I've tried copying the files back into the xcode project and allowing it to update references.  I've also tried using 4.0 and 4.1 of the SDK along with the iphone 4 and iphone simulators under hardware.

I do see some errors from system.log:

```<code>Sep 20 21:59:01 s-macbook-pro-17 [0x0-0x18018].com.apple.Xcode[484]: Xcode(484,0x7fff70216c20) malloc: reference count underflow for 0x2019c0a40, break on auto_refcount_underflow_error to debug.
Sep 20 21:59:01 s-macbook-pro-17 Xcode[484]: Xcode(484,0x7fff70216c20) malloc: reference count underflow for 0x2019c0a40, break on auto_refcount_underflow_error to debug.
Sep 20 21:59:03 s-macbook-pro-17 com.apple.launchd.peruser.502[127] (com.apple.iPhoneSimulator:com.apple.managedconfiguration.profiled): Bug: launchd_core_logic.c:4598 (24108):2
Sep 20 21:59:03 s-macbook-pro-17 com.apple.launchd.peruser.502[127] (com.apple.iPhoneSimulator:com.apple.managedconfiguration.profiled): Path monitoring failed on "/Users/m/Library/Application Support/iPhone Simulator/4.1/Library/ConfigurationProfiles/profiledRunning": No such file or directory
Sep 20 21:59:03 s-macbook-pro-17 com.apple.launchd.peruser.502[127] (com.apple.iPhoneSimulator:com.apple.managedconfiguration.profiled): Bug: launchd_core_logic.c:4598 (24108):2
Sep 20 21:59:03 s-macbook-pro-17 com.apple.launchd.peruser.502[127] (com.apple.iPhoneSimulator:com.apple.managedconfiguration.profiled): Path monitoring failed on "/Users/m/Library/Application Support/iPhone Simulator/4.1/Library/ConfigurationProfiles/MCOutstandingNagComputation": No such file or directory
Sep 20 21:59:03 s-macbook-pro-17 com.apple.launchd.peruser.502[127] (com.apple.iPhoneSimulator:com.apple.managedconfiguration.mdmd): Bug: launchd_core_logic.c:4598 (24108):2
Sep 20 21:59:03 s-macbook-pro-17 com.apple.launchd.peruser.502[127] (com.apple.iPhoneSimulator:com.apple.managedconfiguration.mdmd): Path monitoring failed on "/Users/m/Library/Application Support/iPhone Simulator/4.1/Library/ConfigurationProfiles/MDMOutstandingActivities.plist": No such file or directory
Sep 20 21:59:03 s-macbook-pro-17 vot[929]: ******** AX INSPECTOR MODE ************
Sep 20 21:59:03 s-macbook-pro-17 vot[929]: **** Running VoiceOver Lite ****
Sep 20 21:59:06 s-macbook-pro-17 app[935]: MainView alloc
Sep 20 21:59:06 s-macbook-pro-17 app[935]: MainView alloc complete
Sep 20 21:59:06 s-macbook-pro-17 app[935]: loadView complete
</code>```

答:
Similar situation in my app, but my problem was that somehow, in the MainWindow.xib in IB, the File Owner's delegate was no longer linked up to my app delegate (right click on File Owner in IB and check the delegate button).  Was working in Ipad simulator because I have 2 different MainWindow xib files, one for iphone/ipod and one for ipad.

Hope this helps someone experiencing a blank screen on startup.

ContentLicense: CC BY-SA 2.5

Body:
I have a 3.1 xcode project that has been running my app just fine under the 3.1.3 version of the OS.  I've been testing this app on my iphone 3G ( not running IOS 4 ).

I just copied over the XCode project and files, downloaded the latest XCode 3.2.4 with the 4.1 SDK.  When I run my application via the simulator it just comes up blank instead of showing my app.  I can see via the NSLog statements that it's actually getting to my initWithFrame() and viewDidLoad() methods but it's like it didn't load the images correctly.
I've tried copying the files back into the xcode project and allowing it to update references.  I've also tried using 4.0 and 4.1 of the SDK along with the iphone 4 and iphone simulators under hardware.

I do see some errors from system.log:

Sep 20 21:59:01 s-macbook-pro-17 [0x0-0x18018].com.apple.Xcode[484]: Xcode(484,0x7fff70216c20) malloc: reference count underflow for 0x2019c0a40, break on auto_refcount_underflow_error to debug.
Sep 20 21:59:01 s-macbook-pro-17 Xcode[484]: Xcode(484,0x7fff70216c20) malloc: reference count underflow for 0x2019c0a40, break on auto_refcount_underflow_error to debug.
Sep 20 21:59:03 s-macbook-pro-17 com.apple.launchd.peruser.502[127] (com.apple.iPhoneSimulator:com.apple.managedconfiguration.profiled): Bug: launchd_core_logic.c:4598 (24108):2
Sep 20 21:59:03 s-macbook-pro-17 com.apple.launchd.peruser.502[127] (com.apple.iPhoneSimulator:com.apple.managedconfiguration.profiled): Path monitoring failed on "/Users/m/Library/Application Support/iPhone Simulator/4.1/Library/ConfigurationProfiles/profiledRunning": No such file or directory
Sep 20 21:59:03 s-macbook-pro-17 com.apple.launchd.peruser.502[127] (com.apple.iPhoneSimulator:com.apple.managedconfiguration.profiled): Bug: launchd_core_logic.c:4598 (24108):2
Sep 20 21:59:03 s-macbook-pro-17 com.apple.launchd.peruser.502[127] (com.apple.iPhoneSimulator:com.apple.managedconfiguration.profiled): Path monitoring failed on "/Users/m/Library/Application Support/iPhone Simulator/4.1/Library/ConfigurationProfiles/MCOutstandingNagComputation": No such file or directory
Sep 20 21:59:03 s-macbook-pro-17 com.apple.launchd.peruser.502[127] (com.apple.iPhoneSimulator:com.apple.managedconfiguration.mdmd): Bug: launchd_core_logic.c:4598 (24108):2
Sep 20 21:59:03 s-macbook-pro-17 com.apple.launchd.peruser.502[127] (com.apple.iPhoneSimulator:com.apple.managedconfiguration.mdmd): Path monitoring failed on "/Users/m/Library/Application Support/iPhone Simulator/4.1/Library/ConfigurationProfiles/MDMOutstandingActivities.plist": No such file or directory
Sep 20 21:59:03 s-macbook-pro-17 vot[929]: ******** AX INSPECTOR MODE ************
Sep 20 21:59:03 s-macbook-pro-17 vot[929]: **** Running VoiceOver Lite ****
Sep 20 21:59:06 s-macbook-pro-17 app[935]: MainView alloc
Sep 20 21:59:06 s-macbook-pro-17 app[935]: MainView alloc complete
Sep 20 21:59:06 s-macbook-pro-17 app[935]: loadView complete


问:
Apache Arrow Java API Documentation
I am looking for useful documentations or examples for the Apache Arrow API. Can anyone point to some useful resources? I was only able to find some blogs and JAVA documentation (which doesn't say much). </p>

<p>From what I read, it is a standard in-memory columnar database for fast analytics. Is it possible to load the data to arrow memory and to manipulate it ? </p>

答:
You should use arrow as a middle man between two applications which need to communicate using passing objects.

Arrow isn’t a standalone piece of software but rather a component used
  to accelerate analytics within a particular system and to allow
  Arrow-enabled systems to exchange data with low overhead.

For example Arrow improves the performance for data movement within a cluster.

See tests for examples.

```<code>  @Test
  public void test() throws Exception {
    BufferAllocator allocator = new RootAllocator(Integer.MAX_VALUE);
    File testInFile = testFolder.newFile("testIn.arrow");
    File testOutFile = testFolder.newFile("testOut.arrow");

    writeInput(testInFile, allocator);

    String[] args = {"-i", testInFile.getAbsolutePath(), "-o", testOutFile.getAbsolutePath()};
    int result = new FileRoundtrip(System.out, System.err).run(args);
    assertEquals(0, result);

    validateOutput(testOutFile, allocator);
}
</code>```

Also Apache Parquet uses it. There are conversion examples from/to arrow objects:

```<code>MessageType parquet = converter.fromArrow(allTypesArrowSchema).getParquetSchema();

Schema arrow = converter.fromParquet(supportedTypesParquetSchema).getArrowSchema();
</code>```

Title: Apache Arrow Java API Documentation

Body:
I am looking for useful documentations or examples for the Apache Arrow API. Can anyone point to some useful resources? I was only able to find some blogs and JAVA documentation (which doesn't say much).

From what I read, it is a standard in-memory columnar database for fast analytics. Is it possible to load the data to arrow memory and to manipulate it ?

Body:
You should use arrow as a middle man between two applications which need to communicate using passing objects.

Arrow isn’t a standalone piece of software but rather a component used
  to accelerate analytics within a particular system and to allow
  Arrow-enabled systems to exchange data with low overhead.

For example Arrow improves the performance for data movement within a cluster.

See tests for examples.

  @Test
  public void test() throws Exception {
    BufferAllocator allocator = new RootAllocator(Integer.MAX_VALUE);
    File testInFile = testFolder.newFile("testIn.arrow");
    File testOutFile = testFolder.newFile("testOut.arrow");

    writeInput(testInFile, allocator);

    String[] args = {"-i", testInFile.getAbsolutePath(), "-o", testOutFile.getAbsolutePath()};
    int result = new FileRoundtrip(System.out, System.err).run(args);
    assertEquals(0, result);

    validateOutput(testOutFile, allocator);
}

Also Apache Parquet uses it. There are conversion examples from/to arrow objects:

MessageType parquet = converter.fromArrow(allTypesArrowSchema).getParquetSchema();

Schema arrow = converter.fromParquet(supportedTypesParquetSchema).getArrowSchema();


问:
Why isnt my jquery working when i echo it out with php
I am trying to echo out to easily change videos and load it up so i can work with it and this is the code for the jquery to echo out

```<code><script type="text/javascript">
  <?php
    $latest = 1;
    include_once 'dbh.inc.php';
    $sql = "SELECT * FROM videos";
    $result = mysqli_query($conn, $sql);
    if (mysqli_num_rows($result) > 0) {
      while ($row = mysqli_fetch_assoc($result)) {
        echo '

          $("' . $row['vid_class'] . '").click(function() {
          $(".video-display iframe").attr("src", "' . $row['vid_link'] . '");
          $(".video-display").toggle();
       });';
      }
    }
  ?>
</script>
</code>```

this is what it will echo out and it doesn't run

```<code><script type="text/javascript">
$("into-the-unknown").click(function() {
  $(".video-display iframe").attr("src", "https://www.youtube.com/embed/DkGKLhDUN4g?rel=0&showinfo=0&autoplay=1");
  $(".video-display").toggle();
});

$("wwoman").click(function() {
  $(".video-display iframe").attr("src", "https://www.youtube.com/embed/VSB4wGIdDwo?rel=0&showinfo=0&autoplay=1");
  $(".video-display").toggle();
});
</script>
</code>```

And it is called after the jquery tag to make it work just above the body

答:
Because you forgot to include . in the generated jQuery code to denote class reference.

Change:

```<code>echo '
      $("' . $row['vid_class'] . '").click(function() {
      $(".video-display iframe").attr("src", "' . $row['vid_link'] . '");
      $(".video-display").toggle();
   });';
</code>```

to

```<code>echo '
      $(".' . $row['vid_class'] . '").click(function() {
      $(".video-display iframe").attr("src", "' . $row['vid_link'] . '");
      $(".video-display").toggle();
   });';
</code>```

Body:
I am trying to echo out to easily change videos and load it up so i can work with it and this is the code for the jquery to echo out

this is what it will echo out and it doesn't run

And it is called after the jquery tag to make it work just above the body

Body:
Because you forgot to include . in the generated jQuery code to denote class reference.

Change:

echo '
      $("' . $row['vid_class'] . '").click(function() {
      $(".video-display iframe").attr("src", "' . $row['vid_link'] . '");
      $(".video-display").toggle();
   });';

to

echo '
      $(".' . $row['vid_class'] . '").click(function() {
      $(".video-display iframe").attr("src", "' . $row['vid_link'] . '");
      $(".video-display").toggle();
   });';


问:
Numpy - load csv with first row as names immediately to a structured array?
Is there a way to avoid having to predefine the names of column headers in numpy/pandas to create a structured array, and instead have numpy/pandas read in the first row as the header names, and load the rest of the data to a structured array? E.g. for this data,

```<code>#        Date     low    open   close
#  2015-08-08  266.00  280.04  266.82
#  2015-07-08  233.00  280.04  266.82
</code>```

I would want to call some function like a = pd.read_csv() and be able to access the columns immediately as a['Date'], without predefining names = [Date, low, open, close] and having to pass that into read_csv(). Is this possible?

答:
For the sake of completeness, a numpy example:

```<code>rec_arr = np.genfromtxt("try.csv", delimiter = " ", names=True, dtype=None)
rec_arr
array([(b'2015-08-08',  266.,  280.04,  266.82),
       (b'2015-07-08',  233.,  280.04,  266.82)],
      dtype=[('Date', 'S10'), ('low', '<f8'), ('open', '<f8'), ('close', '<f8')])
</code>```

Then, you can access columns like:

```<code>rec_arr['close']
array([ 266.82,  266.82])
</code>```

and do some math as usual:

```<code>rec_arr['close'].mean()
266.81999999999999
</code>```

Body:
Is there a way to avoid having to predefine the names of column headers in numpy/pandas to create a structured array, and instead have numpy/pandas read in the first row as the header names, and load the rest of the data to a structured array? E.g. for this data,

#        Date     low    open   close
#  2015-08-08  266.00  280.04  266.82
#  2015-07-08  233.00  280.04  266.82

I would want to call some function like a = pd.read_csv() and be able to access the columns immediately as a['Date'], without predefining names = [Date, low, open, close] and having to pass that into read_csv(). Is this possible?

Body:
For the sake of completeness, a numpy example:

rec_arr = np.genfromtxt("try.csv", delimiter = " ", names=True, dtype=None)
rec_arr
array([(b'2015-08-08',  266.,  280.04,  266.82),
       (b'2015-07-08',  233.,  280.04,  266.82)],
      dtype=[('Date', 'S10'), ('low', '<f8'), ('open', '<f8'), ('close', '<f8')])

Then, you can access columns like:

rec_arr['close']
array([ 266.82,  266.82])

and do some math as usual:

rec_arr['close'].mean()
266.81999999999999


问:
'undefined' reported when bind gridview using AJAX in C#
I want to bind the gridview using AJAX. So, for that I done client side code using AJAX and server side code as a webmethod.

Everything is working fine even I alert the data in success method at that time also data is showing but in loop I really confused that it is showing undefined in alert. So for that's why grid is not binding.

Here is my code

```<code>$.ajax({
    type: "POST",
    url: "schoolregistration.aspx/GetGridData",
    contentType: "application/json; charset=utf-8",
    datatype: "json",
    success: function (data) {
        for (var i = 0; i < data.d.length; i++) {
            $("#grid_schooldata").append("<tr><td>" + data.d[i].schoolName);
        }
    },
    failure: function () {
        alert("error! try again...");
    }
});
</code>```

```<code>using (var con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
using (var cmd = new SqlCommand("select schoolname as [School Name] from tbl_schoolregistration", con))
{
    con.Open();
    object val = cmd.ExecuteScalar();
    return val == DBNull.Value ? "" : (string)val;
}
</code>```

答:
First of all

ExecuteScalar   Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.

In this case you will have a single string.

Secondly beware of the name in your query leave it as schoolname not [School Name].

Then you have to Serialize into json and again parse into json in order to loop through objects.

Here is fully working code:

```<code>$.ajax({
    type: "POST",
    url: "schoolregistration.aspx/GetGridData",
    contentType: "application/json; charset=utf-8",
    datatype: "json",
    success: function (data) {
        data = JSON.parse(data.d);
        for (var i = 0; i < data.length; i++) {
          $("#grid_schooldata").append("<tr><td>" + data[i].schoolname +"</td></tr>");
        }
    },
    failure: function () {
        alert("error! try again...");
    }
});

[WebMethod]
public static string GetGridData()
{
    using (var con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
    using (var cmd = new SqlCommand("select schoolname from tbl_schoolregistration", con))
    {
        con.Open();
        //object val = cmd.ExecuteScalar();
        SqlDataAdapter adp = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        adp.Fill(dt); // fills data from select query

        // return val == DBNull.Value ? "" : (string)val;
        return JsonConvert.SerializeObject(dt);
    }
}
</code>```

Body:
I want to bind the gridview using AJAX. So, for that I done client side code using AJAX and server side code as a webmethod.

Everything is working fine even I alert the data in success method at that time also data is showing but in loop I really confused that it is showing undefined in alert. So for that's why grid is not binding.

Here is my code

$.ajax({
    type: "POST",
    url: "schoolregistration.aspx/GetGridData",
    contentType: "application/json; charset=utf-8",
    datatype: "json",
    success: function (data) {
        for (var i = 0; i < data.d.length; i++) {
            $("#grid_schooldata").append("
" + data.d[i].schoolName);
        }
    },
    failure: function () {
        alert("error! try again...");
    }
});

using (var con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
using (var cmd = new SqlCommand("select schoolname as [School Name] from tbl_schoolregistration", con))
{
    con.Open();
    object val = cmd.ExecuteScalar();
    return val == DBNull.Value ? "" : (string)val;
}

Body:
First of all

ExecuteScalar   Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.

In this case you will have a single string.

Secondly beware of the name in your query leave it as schoolname not [School Name].

Then you have to Serialize into json and again parse into json in order to loop through objects.

Here is fully working code:

$.ajax({
    type: "POST",
    url: "schoolregistration.aspx/GetGridData",
    contentType: "application/json; charset=utf-8",
    datatype: "json",
    success: function (data) {
        data = JSON.parse(data.d);
        for (var i = 0; i < data.length; i++) {
          $("#grid_schooldata").append("<tr><td>" + data[i].schoolname +"</td></tr>");
        }
    },
    failure: function () {
        alert("error! try again...");
    }
});

[WebMethod]
public static string GetGridData()
{
    using (var con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
    using (var cmd = new SqlCommand("select schoolname from tbl_schoolregistration", con))
    {
        con.Open();
        //object val = cmd.ExecuteScalar();
        SqlDataAdapter adp = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        adp.Fill(dt); // fills data from select query

        // return val == DBNull.Value ? "" : (string)val;
        return JsonConvert.SerializeObject(dt);
    }
}


问:
why can not match chinese characters by using ”regex“ at python ？

 import re
 html="""

                   0
                   0 天
                   0
                   0 时
                   0
                   0 分
                   0
                   0 秒
     """
 tmp=re.compile(u"(
).*?([\u4e00-\u9fa5]).*?",re.U)
 result=re.findall(tmp,html.decode("utf-8"))
 print result
 []
```

As mentioned above why my code can not match  Chinese characters？

答:
Yuu're using single quotes in
 for your regex pattern whereas html has div's class in double quotes. I think there's a simpler pattern which can extract what you want:

```<code>tmp = re.compile(u"(?m)([\u4e00-\u9fa5])+", re.U)
result=re.findall(tmp,html)
print result
</code>```

Output:
['天', '时', '分', '秒']

If your html is bigger than what is shown in the question, and you want only the Chinese characters in
, you can first extract the text within the div and then search inside that text:

```<code>inside_text = re.search(r'<div class="tB-mb">[\s\S]+</div>', html).group()
result = re.findall(tmp,inside_text)
</code>```

Output will be as desired.

Body:
 import re
 html="""

                   0
                   0 天
                   0
                   0 时
                   0
                   0 分
                   0
                   0 秒
     """
 tmp=re.compile(u"(
).*?([\u4e00-\u9fa5]).*?",re.U)
 result=re.findall(tmp,html.decode("utf-8"))
 print result
 []

As mentioned above why my code can not match  Chinese characters？

Body:
Yuu're using single quotes in <div class='tB-mb'> for your regex pattern whereas html has div's class in double quotes. I think there's a simpler pattern which can extract what you want:

tmp = re.compile(u"(?m)([\u4e00-\u9fa5])+", re.U)
result=re.findall(tmp,html)
print result

Output:
['天', '时', '分', '秒']

If your html is bigger than what is shown in the question, and you want only the Chinese characters in <div class="tB-mb">, you can first extract the text within the div and then search inside that text:

inside_text = re.search(r'<div class="tB-mb">[\s\S]+</div>', html).group()
result = re.findall(tmp,inside_text)

Output will be as desired.


问:
Why notification doesn't work?
I want to create a notification that works every 5 minute,for example. For this, I use BroadCastReceiver. Here is my code:

```<code>   public void notifyMe()
   Calendar calendar = Calendar.getInstance() ;

    calendar.set(Calendar.HOUR,0);

    calendar.set(Calendar.MINUTE,5);

    calendar.set(Calendar.SECOND,0);

    Log.d("tagger",calendar.getTime().toString());

    Intent intent = new Intent(this,MyBroadcastReceiver.class);

    PendingIntent sender = PendingIntent.getBroadcast(this,0,intent,PendingIntent.FLAG_CANCEL_CURRENT);

    AlarmManager am = (AlarmManager)this.getSystemService(Context.ALARM_SERVICE);

    am.setInexactRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),5*60*1000,sender);
   }
</code>```

Also for Receiver:

```<code>public class MyBroadcastReceiver extends BroadcastReceiver {

private static final int NOTIFY_ID = 101;

@Override
public void onReceive(Context context, Intent intent) {

    Log.d("BroadcastReceiver", "debut receive");

    Intent resultIntent  =  new Intent(context,DetailActivity.class) ;

    PendingIntent resultPendingIntent = PendingIntent.getActivity(context,
            0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    Notification.Builder mBuilder = new Notification.Builder(context)
            .setContentTitle("title")
            .setContentText("some text");

    mBuilder.setAutoCancel(true);

    mBuilder.setContentIntent(resultPendingIntent);

    int id = 001 ;

    NotificationManager mNotifyManager = (NotificationManager)context.getSystemService(Application.NOTIFICATION_SERVICE);

    mNotifyManager.notify(id,mBuilder.build());
}
}
</code>```

Manifest:

```<code>   <application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:name=".PrefsApplication"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".DetailActivity" />
    <activity android:name=".ActionsActivity"

        ></activity>

    <receiver android:name=".MyBroadcastReceiver">

    </receiver>
</application>
</code>```

What it doesn't work? I didn't forget to add receiver to the manifest. I need to use Service instead of Receiver?

答:
Try this:

```<code> private void notificationManager(Context context, String message) {

    try {
        long when = System.currentTimeMillis();

        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        Log.v("message", "," + message);

        Intent notificationIntent = new Intent(context, SplashActivity.class);

        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, 0);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
        builder.setAutoCancel(true);
        builder.setContentTitle(context.getString(R.string.app_name));
        builder.setStyle(new NotificationCompat.BigTextStyle().bigText(message));
        builder.setContentText(message);
        builder.setTicker(message);
        builder.setLights(Color.GREEN, 500, 500);
        builder.setWhen(when);
        builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
        builder.setSmallIcon(R.mipmap.ic_launcher);
        builder.setContentIntent(intent);

        Notification notification = builder.build();
        notification.ledARGB = 0xFFff0000;
        notification.flags = Notification.FLAG_SHOW_LIGHTS;
        notification.ledOnMS = 100;
        notification.ledOffMS = 100;
        notificationManager.notify(1, notification);

        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "TAG");
        wl.acquire(15000);

    } catch (Exception e) {
        e.printStackTrace();
    }

}
</code>```

Hope this helps.

Title: Why notification doesn't work?

Body:
I want to create a notification that works every 5 minute,for example. For this, I use BroadCastReceiver. Here is my code:

   public void notifyMe()
   Calendar calendar = Calendar.getInstance() ;

    calendar.set(Calendar.HOUR,0);

    calendar.set(Calendar.MINUTE,5);

    calendar.set(Calendar.SECOND,0);

    Log.d("tagger",calendar.getTime().toString());

    Intent intent = new Intent(this,MyBroadcastReceiver.class);

    PendingIntent sender = PendingIntent.getBroadcast(this,0,intent,PendingIntent.FLAG_CANCEL_CURRENT);

    AlarmManager am = (AlarmManager)this.getSystemService(Context.ALARM_SERVICE);

    am.setInexactRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),5*60*1000,sender);
   }

Also for Receiver:

public class MyBroadcastReceiver extends BroadcastReceiver {

private static final int NOTIFY_ID = 101;

@Override
public void onReceive(Context context, Intent intent) {

    Log.d("BroadcastReceiver", "debut receive");

    Intent resultIntent  =  new Intent(context,DetailActivity.class) ;

    PendingIntent resultPendingIntent = PendingIntent.getActivity(context,
            0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    Notification.Builder mBuilder = new Notification.Builder(context)
            .setContentTitle("title")
            .setContentText("some text");

    mBuilder.setAutoCancel(true);

    mBuilder.setContentIntent(resultPendingIntent);

    int id = 001 ;

    NotificationManager mNotifyManager = (NotificationManager)context.getSystemService(Application.NOTIFICATION_SERVICE);

    mNotifyManager.notify(id,mBuilder.build());
}
}

Manifest:

   <application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:name=".PrefsApplication"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".DetailActivity" />
    <activity android:name=".ActionsActivity"

        ></activity>

    <receiver android:name=".MyBroadcastReceiver">

    </receiver>
</application>

What it doesn't work? I didn't forget to add receiver to the manifest. I need to use Service instead of Receiver?

Body:
Try this:

 private void notificationManager(Context context, String message) {

    try {
        long when = System.currentTimeMillis();

        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        Log.v("message", "," + message);

        Intent notificationIntent = new Intent(context, SplashActivity.class);

        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, 0);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
        builder.setAutoCancel(true);
        builder.setContentTitle(context.getString(R.string.app_name));
        builder.setStyle(new NotificationCompat.BigTextStyle().bigText(message));
        builder.setContentText(message);
        builder.setTicker(message);
        builder.setLights(Color.GREEN, 500, 500);
        builder.setWhen(when);
        builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
        builder.setSmallIcon(R.mipmap.ic_launcher);
        builder.setContentIntent(intent);

        Notification notification = builder.build();
        notification.ledARGB = 0xFFff0000;
        notification.flags = Notification.FLAG_SHOW_LIGHTS;
        notification.ledOnMS = 100;
        notification.ledOffMS = 100;
        notificationManager.notify(1, notification);

        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "TAG");
        wl.acquire(15000);

    } catch (Exception e) {
        e.printStackTrace();
    }

}

Hope this helps.


问:
before_save except on new record if field value changes
I need to execute a hook in a rails4 app if a field changes and only if its not a record record.

I know I can do...

```<code>  before_save :reset_confirmation, if: :email_changed?
  def reset_confirmation
    self.confirmed_at = nil
    self.confirmation_sent_at = nil
  end
</code>```

and I'm pretty sure this works...

```<code>  before_save :reset_confirmation, unless: new_record?
  def reset_confirmation
    self.confirmed_at = nil
    self.confirmation_sent_at = nil
  end
</code>```

but how do I combine the two, or is there an easier way to achieve what I want and I'm overthinking things. The field (email) will always contains a value after it's been created if that helps?

答:
I wonder if the readability and maintainability of the class improve when the callback is replaced by an explicit setter method:</p>

```<code>def email=(new_email)
  unless new_email == email
    self.confirmed_at = nil
    self.confirmation_sent_at = nil
    write_attribute(:email, new_email)
  end
end
</code>```

Body:
I need to execute a hook in a rails4 app if a field changes and only if its not a record record.

I know I can do...

  before_save :reset_confirmation, if: :email_changed?
  def reset_confirmation
    self.confirmed_at = nil
    self.confirmation_sent_at = nil
  end

and I'm pretty sure this works...

  before_save :reset_confirmation, unless: new_record?
  def reset_confirmation
    self.confirmed_at = nil
    self.confirmation_sent_at = nil
  end

but how do I combine the two, or is there an easier way to achieve what I want and I'm overthinking things. The field (email) will always contains a value after it's been created if that helps?

Body:
I wonder if the readability and maintainability of the class improve when the callback is replaced by an explicit setter method:

def email=(new_email)
  unless new_email == email
    self.confirmed_at = nil
    self.confirmation_sent_at = nil
    write_attribute(:email, new_email)
  end
end


问:
How to adjust or format the column width in output of Package Manager Console
I ran below command in Package Manager Console in Visual Studio:

```<code>Find-Package analysisservices
</code>```

This command gives below output:

For several packages whose name is relatively longer than the width of the Id column it shows three dots ... in the end. It doesn't show any tool-tip when I hover mouse over the long names having three dots ....

Is there any way to adjust the width of the displayed columns so that long names don't get truncated?

Update: One thing which is still not solved. Is there any other additional parameter to the command Get-Package | ft -AutoSize which I can use so that all three output columns get expanded in table view itself. I don't mind if that results in a horizontal scroll bar.

答:
This is to add additional details to complement Emiel Koning's answer.

I came across another output format for Find-Package command. With the help of this format, we can display only desired columns on the output console. Find-Package command displays three columns by default namely Id, Name and Description. On various general purpose monitors, there isn't enough space to display all three columns completely.

When the number of displayed columns is less then each column gets more space on the console output. Hence, the dots ... go away automatically. Here is the command format -

```<code>Find-Package analysisservices | Format-Table -Property Id,Versions
</code>```

It returns below output:

If we want to see only Id and Description columns then we can use below command:

```<code>Find-Package analysisservices | Format-Table -Property Id,Description
</code>```

Note: ft is an alias for Format-Table argument. It is not case-sensitive. So all the commands mentioned below are equivalent and will give same output:

```<code>Find-Package analysisservices | Format-Table -Property Id,Versions
Find-Package analysisservices | FT -Property Id,Versions
Find-Package analysisservices | ft -Property Id,Versions
Find-Package analysisservices | Ft -Property Id,Versions
Find-Package analysisservices | fT -Property Id,Versions
</code>```

Body:
I ran below command in Package Manager Console in Visual Studio:

Find-Package analysisservices

This command gives below output:

For several packages whose name is relatively longer than the width of the Id column it shows three dots ... in the end. It doesn't show any tool-tip when I hover mouse over the long names having three dots ....

Is there any way to adjust the width of the displayed columns so that long names don't get truncated?

Update: One thing which is still not solved. Is there any other additional parameter to the command Get-Package | ft -AutoSize which I can use so that all three output columns get expanded in table view itself. I don't mind if that results in a horizontal scroll bar.

Body:
This is to add additional details to complement Emiel Koning's answer.

I came across another output format for Find-Package command. With the help of this format, we can display only desired columns on the output console. Find-Package command displays three columns by default namely Id, Name and Description. On various general purpose monitors, there isn't enough space to display all three columns completely.

When the number of displayed columns is less then each column gets more space on the console output. Hence, the dots ... go away automatically. Here is the command format -

Find-Package analysisservices | Format-Table -Property Id,Versions

It returns below output:

If we want to see only Id and Description columns then we can use below command:

Find-Package analysisservices | Format-Table -Property Id,Description

Note: ft is an alias for Format-Table argument. It is not case-sensitive. So all the commands mentioned below are equivalent and will give same output:

Find-Package analysisservices | Format-Table -Property Id,Versions
Find-Package analysisservices | FT -Property Id,Versions
Find-Package analysisservices | ft -Property Id,Versions
Find-Package analysisservices | Ft -Property Id,Versions
Find-Package analysisservices | fT -Property Id,Versions


问:
Pandas DataFrame mutability
I am pretty new to Panda's Dataframe and it would be highly appreciated if someone can briefly discuss about the mutability of DataFrame to me with the following example:

```<code>d1=pd.date_range('1/1/2016',periods=10,freq='w')
col1=['open','high','low','close']
list1=np.random.rand(10,4)
df1=pd.DataFrame(list1,d1,col1)
</code>```

To my understanding, currently df1 is a reference to a df object.

If I pass df1 or slicing of df1 (e.g. df1.iloc[2:3,1:2]) as an input to a new df, (e.g. df2=pd.DataFrame(df1)), does df2 return a new instance of dataframe or it is still referring to df1 that makes df1 exposed to df2?

Also any other point that I should pay attention to regarding mutability of DataFrame will be very much appreciated.

答:
This:

```<code>df2 = pd.DataFrame(df1)
</code>```

Constructs a new DataFrame.  There is a copy parameter whose default argument is False.  According to the documentation, it means:

```<code>> Copy data from inputs. Only affects DataFrame / 2d ndarray input
</code>```

So data will be shared between df2 and df1 by default.  If you want there to be no sharing, but rather a complete copy, do this:

```<code>df2 = pd.DataFrame(df1, copy=True)
</code>```

Or more concisely and idiomatically:

```<code>df2 = df1.copy()
</code>```

If you do this:

```<code>df2 = df1.iloc[2:3,1:2].copy()
</code>```

You will again get an independent copy.  But if you do this:

```<code>df2 = pd.DataFrame(df1.iloc[2:3,1:2])
</code>```

It will probably share the data, but this style is pretty unclear if you intend to modify df, so I suggest not writing such code.  Instead, if you want no copy, just say this:

```<code>df2 = df1.iloc[2:3,1:2]
</code>```

In summary: if you want a reference to existing data, do not call pd.DataFrame() or any other method at all.  If you want an independent copy, call .copy().

Title: Pandas DataFrame mutability

Body:
I am pretty new to Panda's Dataframe and it would be highly appreciated if someone can briefly discuss about the mutability of DataFrame to me with the following example:

d1=pd.date_range('1/1/2016',periods=10,freq='w')
col1=['open','high','low','close']
list1=np.random.rand(10,4)
df1=pd.DataFrame(list1,d1,col1)

To my understanding, currently df1 is a reference to a df object.

If I pass df1 or slicing of df1 (e.g. df1.iloc[2:3,1:2]) as an input to a new df, (e.g. df2=pd.DataFrame(df1)), does df2 return a new instance of dataframe or it is still referring to df1 that makes df1 exposed to df2?

Also any other point that I should pay attention to regarding mutability of DataFrame will be very much appreciated.

Body:
This:

df2 = pd.DataFrame(df1)

Constructs a new DataFrame.  There is a copy parameter whose default argument is False.  According to the documentation, it means:

> Copy data from inputs. Only affects DataFrame / 2d ndarray input

So data will be shared between df2 and df1 by default.  If you want there to be no sharing, but rather a complete copy, do this:

df2 = pd.DataFrame(df1, copy=True)

Or more concisely and idiomatically:

df2 = df1.copy()

If you do this:

df2 = df1.iloc[2:3,1:2].copy()

You will again get an independent copy.  But if you do this:

df2 = pd.DataFrame(df1.iloc[2:3,1:2])

It will probably share the data, but this style is pretty unclear if you intend to modify df, so I suggest not writing such code.  Instead, if you want no copy, just say this:

df2 = df1.iloc[2:3,1:2]

In summary: if you want a reference to existing data, do not call pd.DataFrame() or any other method at all.  If you want an independent copy, call .copy().


问:
How to resize background image on Safari?
In Chrome

In Chrome, it works just like the picture above.

In Safari

However, in Safari, it does not work as shown above.

The CSS code is as follows:

```<code>background-image: url(rendyhome.png);
background-size: auto 66vh;
background-repeat: no-repeat;
background-position: right;
</code>```

How do I fix it?

答:
background-size: contain;

You can try with the following code that tell the browser keeping image inside the container, then, to center it. This solution may create a blank color around the image that can be filled using background color;

```<code>background-size: contain;
background-position: center;
</code>```

https://developer.mozilla.org/en-US/docs/Web/CSS/background-size

A keyword that scales the image as large as possible and maintains
  image aspect ratio (image doesn't get squished). Image is letterboxed
  within the container. When the image and container have different
  dimensions, the empty areas (either top/bottom of left/right) are
  filled with the background-color.

background-size: cover;

You can also use background-size: cover; that will entirely fill the screen with your image.

Be careful: using this technique, you need to know the image may be cut by the browser if the screen ratio is not the same as your image (think responsive). As I can see on your image, there are some wording inside, so the cover solution may be inappropriate to keep them visible.

When the image and container have different dimensions, the image is
  clipped either left/right or top/bottom.

Both solutions are good, but effects are different. It depends on your behaviour preference. Even if image ratio is respected in both solution, one solution clip/cut and the other create a blank around the image.

This is an image from marcarea.com, in order to summarize. You can see behaviours I described before.

Body:
In Chrome

In Chrome, it works just like the picture above.

In Safari

However, in Safari, it does not work as shown above.

The CSS code is as follows:

background-image: url(rendyhome.png);
background-size: auto 66vh;
background-repeat: no-repeat;
background-position: right;

How do I fix it?

Body:
background-size: contain;

You can try with the following code that tell the browser keeping image inside the container, then, to center it. This solution may create a blank color around the image that can be filled using background color;

background-size: contain;
background-position: center;

https://developer.mozilla.org/en-US/docs/Web/CSS/background-size

A keyword that scales the image as large as possible and maintains
  image aspect ratio (image doesn't get squished). Image is letterboxed
  within the container. When the image and container have different
  dimensions, the empty areas (either top/bottom of left/right) are
  filled with the background-color.

background-size: cover;

You can also use background-size: cover; that will entirely fill the screen with your image.

Be careful: using this technique, you need to know the image may be cut by the browser if the screen ratio is not the same as your image (think responsive). As I can see on your image, there are some wording inside, so the cover solution may be inappropriate to keep them visible.

When the image and container have different dimensions, the image is
  clipped either left/right or top/bottom.

Both solutions are good, but effects are different. It depends on your behaviour preference. Even if image ratio is respected in both solution, one solution clip/cut and the other create a blank around the image.

This is an image from marcarea.com, in order to summarize. You can see behaviours I described before.


问:
how can route form in laravel 5.2
My EventsController function is this in My Laravel app

```<code>public function storetask(Request $request, $id, Task $task)
    {
        $task = new Task;
        $task->task_name   = $request->input('name');
        $task->body = $request->input('body');
        $task->assign          = $request->input('status');
        $task->priority        = $request->input('status');
        $task->duedate  = $request->input('date');
        $task->project_id        = $id;

        $task->save();
}
</code>```

I need save form data in My events folder show.blade.php file using above controller function
My form route is this

```<code><form method="post" action="{{ route('events.storetask') }}">
</code>```

My route.php is this

```<code>Route::resource('events', 'EventsController');
</code>```

but I got this error message

```<code>Route [events.storetask] not defined. (View: C:\Users\Flex\Desktop\kuruja\resources\views\events\show.blade.php)
</code>```

how can solve this?

答:
Define your route like below:

```<code>Route::post('/storeTask/{projectId}',array('uses'=>'EventsController@storetask','as'=>'storeTask'));
</code>```

And call in your view

```<code><form method="post" action="{{ route('storeTask',$yourProjectId) }}">
</code>```

Replace your controller function with the below function:

```<code>public function storetask($id=0)
{
        $task = new Task();
        $task->task_name    = \Input::get('name');
        $task->body         = \Input::get('body');
        $task->assign       = \Input::get('status');
        $task->priority     = \Input::get('status');
        $task->duedate      = \Input::get('date');
        $task->project_id   = $id;

        $task->save();
}
</code>```

Title: how can route form in laravel 5.2

Body:
My EventsController function is this in My Laravel app

public function storetask(Request $request, $id, Task $task)
    {
        $task = new Task;
        $task->task_name   = $request->input('name');
        $task->body = $request->input('body');
        $task->assign          = $request->input('status');
        $task->priority        = $request->input('status');
        $task->duedate  = $request->input('date');
        $task->project_id        = $id;

        $task->save();
}

I need save form data in My events folder show.blade.php file using above controller function
My form route is this

<form method="post" action="{{ route('events.storetask') }}">

My route.php is this

Route::resource('events', 'EventsController');

but I got this error message

Route [events.storetask] not defined. (View: C:\Users\Flex\Desktop\kuruja\resources\views\events\show.blade.php)

how can solve this?

Body:
Define your route like below:

Route::post('/storeTask/{projectId}',array('uses'=>'EventsController@storetask','as'=>'storeTask'));

And call in your view

<form method="post" action="{{ route('storeTask',$yourProjectId) }}">

Replace your controller function with the below function:

public function storetask($id=0)
{
        $task = new Task();
        $task->task_name    = \Input::get('name');
        $task->body         = \Input::get('body');
        $task->assign       = \Input::get('status');
        $task->priority     = \Input::get('status');
        $task->duedate      = \Input::get('date');
        $task->project_id   = $id;

        $task->save();
}


问:
Combine two json sections into one json object
I would like to combine topData and bottomData into completeData.

```<code>var topData = {
    "auth": "1vmPoG22V3qqf43mPeMc",
    "property" : "ATL-D406",
    "status" : 1,
    "user" : "test001@aaa.com",
    "name" : "Abraham Denson"
}

var bottomData = {
    "agent" : "pusher@agent.com",
    "agency" : "Thai Tims Agency",
    "agentCommission" : 1000,
    "arrival" : "arrive 12pm at condo",
    "departure" : "leaving room at 6pm",
}

var completeData = topData.concat(bottomData)
</code>```

Since these are not arrays, concat wont work here.

Can this be done without making foreach loops?

答:
You can use Object.assign() to concatenate your objects.

```<code>var newObj = Object.assign({}, topData, bottomData)
</code>```

From MDN:

The Object.assign() method is used to copy the values of all
  enumerable own properties from one or more source objects to a target
  object. It will return the target object.

var topData = {
    "auth": "1vmPoG22V3qqf43mPeMc",
    "property" : "ATL-D406",
    "status" : 1,
    "user" : "test001@aaa.com",
    "name" : "Abraham Denson"
}

var bottomData = {
    "agent" : "pusher@agent.com",
    "agency" : "Thai Tims Agency",
    "agentCommission" : 1000,
    "arrival" : "arrive 12pm at condo",
    "departure" : "leaving room at 6pm",
}

var completeData = Object.assign({}, topData, bottomData);

console.log(completeData);```

Body:
I would like to combine topData and bottomData into completeData.

var topData = {
    "auth": "1vmPoG22V3qqf43mPeMc",
    "property" : "ATL-D406",
    "status" : 1,
    "user" : "test001@aaa.com",
    "name" : "Abraham Denson"
}

var bottomData = {
    "agent" : "pusher@agent.com",
    "agency" : "Thai Tims Agency",
    "agentCommission" : 1000,
    "arrival" : "arrive 12pm at condo",
    "departure" : "leaving room at 6pm",
}

var completeData = topData.concat(bottomData)

Since these are not arrays, concat wont work here.

Can this be done without making foreach loops?

Body:
You can use Object.assign() to concatenate your objects.

var newObj = Object.assign({}, topData, bottomData)

From MDN:

The Object.assign() method is used to copy the values of all
  enumerable own properties from one or more source objects to a target
  object. It will return the target object.

var topData = {
    "auth": "1vmPoG22V3qqf43mPeMc",
    "property" : "ATL-D406",
    "status" : 1,
    "user" : "test001@aaa.com",
    "name" : "Abraham Denson"
}

var bottomData = {
    "agent" : "pusher@agent.com",
    "agency" : "Thai Tims Agency",
    "agentCommission" : 1000,
    "arrival" : "arrive 12pm at condo",
    "departure" : "leaving room at 6pm",
}

var completeData = Object.assign({}, topData, bottomData);

console.log(completeData);


答:
You need a route for storetask.  When you use resource it creates 7 routes you should have on your Events controller.  index, create, store, show, edit, update, destroy.  You could just direct your form to store or create storetask instead.

You can also use php artisan routes command to view all your routes and you can see there isn't one named storetask.

Title: how can route form in laravel 5.2


问:
Error in enabling a selector using jQuery
I'm trying to enable a multi selector only when a checkbox is checked. My code is generating an alert, but won't enable the selector

Selector & checkbox html+Script:

Enabling function:

```<code>$("#checkbox").bind("click", function () {

     if ($('#checkbox').is(":checked"))
          {  alert("checked");
            $("#sel").attr('disabled',false);

          }
    else
          {
            //Do nothing
          }
});
</code>```

答:
For starters, you're using the id "sel" as the selector within your jQuery, when that is not defined within your HTML.

So, I've gone ahead and changed that to "#example-getting-started". Along with changing the value of the disabled attribute to "false", as opposed to false.

```<code>$(document).on("click", function(e){
    if($("#checkbox").is(":checked")){
        alert("Checked");
        $("#example-getting-started").attr("disabled", "false");
    }
});
</code>```

Hopefully, this works for you! :)

Body:
I'm trying to enable a multi selector only when a checkbox is checked. My code is generating an alert, but won't enable the selector

Selector & checkbox html+Script:

Enabling function:

$("#checkbox").bind("click", function () {

     if ($('#checkbox').is(":checked"))
          {  alert("checked");
            $("#sel").attr('disabled',false);

          }
    else
          {
            //Do nothing
          }
});

Body:
For starters, you're using the id "sel" as the selector within your jQuery, when that is not defined within your HTML.

So, I've gone ahead and changed that to "#example-getting-started". Along with changing the value of the disabled attribute to "false", as opposed to false.

$(document).on("click", function(e){
    if($("#checkbox").is(":checked")){
        alert("Checked");
        $("#example-getting-started").attr("disabled", "false");
    }
});

Hopefully, this works for you! :)


答:
I think the issue is here:

```<code><form method="post" action="{{ route('events.storetask') }}">
</code>```

As when you register a resourceful route to the controller like:

```<code>Route::resource('photo', 'PhotoController');
</code>```

This single route declaration creates multiple routes to handle a variety of RESTful actions on the photo resource. Likewise, the generated controller will already have methods stubbed for each of these actions, including notes informing you which URIs and verbs they handle.

Actions Handled By Resource Controller

```<code>Verb    Path    Action  Route Name
GET /photo  index   photo.index
GET /photo/create   create  photo.create
POST    /photo  store   photo.store
GET /photo/{photo}  show    photo.show
GET /photo/{photo}/edit edit    photo.edit
PUT/PATCH   /photo/{photo}  update  photo.update
DELETE  /photo/{photo}  destroy photo.destroy
</code>```

but in your case the the method storetask do not match with the above list. So change the name according to the list and try again.

Reference

Title: how can route form in laravel 5.2

Body:
I think the issue is here:

<form method="post" action="{{ route('events.storetask') }}">

As when you register a resourceful route to the controller like:

Route::resource('photo', 'PhotoController');

This single route declaration creates multiple routes to handle a variety of RESTful actions on the photo resource. Likewise, the generated controller will already have methods stubbed for each of these actions, including notes informing you which URIs and verbs they handle.

Actions Handled By Resource Controller

Verb    Path    Action  Route Name
GET /photo  index   photo.index
GET /photo/create   create  photo.create
POST    /photo  store   photo.store
GET /photo/{photo}  show    photo.show
GET /photo/{photo}/edit edit    photo.edit
PUT/PATCH   /photo/{photo}  update  photo.update
DELETE  /photo/{photo}  destroy photo.destroy

but in your case the the method storetask do not match with the above list. So change the name according to the list and try again.

Reference


答:
You can use Object.assign.

var topData = {
  "auth": "1vmPoG22V3qqf43mPeMc",
  "property": "ATL-D406",
  "status": 1,
  "user": "test001@aaa.com",
  "name": "Abraham Denson"
}

var bottomData = {
  "agent": "pusher@agent.com",
  "agency": "Thai Tims Agency",
  "agentCommission": 1000,
  "arrival": "arrive 12pm at condo",
  "departure": "leaving room at 6pm",
}

var completeData = Object.assign(topData, bottomData);
console.log(completeData)```

It return the target object which mean properties from bottomData will be added to topData

Title: Combine two json sections into one json object

Body:
You can use Object.assign.

var topData = {
  "auth": "1vmPoG22V3qqf43mPeMc",
  "property": "ATL-D406",
  "status": 1,
  "user": "test001@aaa.com",
  "name": "Abraham Denson"
}

var bottomData = {
  "agent": "pusher@agent.com",
  "agency": "Thai Tims Agency",
  "agentCommission": 1000,
  "arrival": "arrive 12pm at condo",
  "departure": "leaving room at 6pm",
}

var completeData = Object.assign(topData, bottomData);
console.log(completeData)

It return the target object which mean properties from bottomData will be added to topData


问:
Nginx custom uploads rewrite for WordPress Multisite
I have a WordPress multisite setup with subdomains on Nginx.

I'd like upload urls such as this to work...

```<code>http://mysub.mydomain.com/files/2017/07/myfile.png
</code>```

where the location of the file is...

```<code><web root>/wp-content/uploads/sites/xx/2017/07/myfile.png
</code>```

This is the location rule in the Nginx config:

```<code>location ~ ^/files/(.*)$ {
    try_files /wp-content/uploads/sites/$blogid/$1;
    access_log off; log_not_found off;      expires max;
}
</code>```

It doesn't work and I'm unable to see why.

I have also tried (and numerous variations):

```<code>location ^~ /files {
    internal;
    alias /www/wp-content/uploads/sites/$blogid;
    access_log off; log_not_found off;      expires max;
}
</code>```

If either of these can be confirmed as 'should work' then I'll start looking at rules higher up my code that may be taking precedence (although nothing's jumped out at me yet)...

答:
This is what did work:</p>

```<code>if (!-e $request_filename) {
    rewrite ^/files/(.*) /wp-content/uploads/sites/$blogid/$1 last;
}
</code>```

Body:
I have a WordPress multisite setup with subdomains on Nginx.

I'd like upload urls such as this to work...

http://mysub.mydomain.com/files/2017/07/myfile.png

where the location of the file is...

<web root>/wp-content/uploads/sites/xx/2017/07/myfile.png

This is the location rule in the Nginx config:

location ~ ^/files/(.*)$ {
    try_files /wp-content/uploads/sites/$blogid/$1;
    access_log off; log_not_found off;      expires max;
}

It doesn't work and I'm unable to see why.

I have also tried (and numerous variations):

location ^~ /files {
    internal;
    alias /www/wp-content/uploads/sites/$blogid;
    access_log off; log_not_found off;      expires max;
}

If either of these can be confirmed as 'should work' then I'll start looking at rules higher up my code that may be taking precedence (although nothing's jumped out at me yet)...

Body:
This is what did work:

if (!-e $request_filename) {
    rewrite ^/files/(.*) /wp-content/uploads/sites/$blogid/$1 last;
}


问:
how to use conditional trigger in sql server for update
I have a table like this:

```<code>---------------table1--------------------------------------------
    id    |   name  | lname   |   displayStatus   | delStatus
    1         a         b               1              0
    2         aa        bb              0              0
    3         aaa       bbb             1              0
    4         aaaa      bbbb            0              1

---------------tbl_LOG--------------------------------------------
    id    |   rowData| actType
</code>```

and i have this trigger for update:

```<code>alter trigger tgr_delete
on table1
after update
as
begin
    declare @rowData nvarchar(max), @username nvarchar(50)

    if update(delStatus)
    begin
        if((select delStatus from inserted) = 1)
        begin
            set @rowData = (select CAST((CAST(id as nvarchar(12)) + ' | ' + name) as nvarchar(max)) from inserted)

            exec sp_insert_LOG 'table1', @rowData, 2
        end
        else if((select delStatus from inserted) = 0)
        begin
            set @rowData = (select CAST((CAST(id as nvarchar(12)) + ' | ' + name) as nvarchar(max)) from inserted)

            exec sp_insert_LOG 'table1', @rowData, 3
        end
    end
    else if update(displayStatus)
    begin
        if((delStatus = 0 or delStatus is null) and (select displayStatus from inserted) = 0)
        begin
            set @rowData = (select CAST((CAST(id as nvarchar(12)) + ' | ' + name) as nvarchar(max)) from inserted)

            exec sp_insert_LOG 'table1', @rowData, 4
        end
        else if((delStatus = 0 or delStatus is null) and (select displayStatus from inserted) = 1)
        begin
            set @rowData = (select CAST((CAST(id as nvarchar(12)) + ' | ' + name) as nvarchar(max)) from inserted)

            exec sp_insert_LOG 'table1', @rowData, 5
        end
    end
end
</code>```

and i have 3 stored procedure

first is for update delStatus

second is for update displayStatus

and third is for update all column

now What should I do to avoid interfering with the first two conditions.

答:
This is not a complete answer since I don't know what sp_insert_LOG does, but it should get you started on the right direction:

```<code>CREATE TRIGGER trg_Table1_Update ON Table1
FOR UPDATE
AS

DECLARE @LogData AS TABLE
(
    TableName sysname,
    RowData nvarchar(max),
    ActionType int
)

INSERT INTO @LogData (TableName, RowData, ActionType)
SELECT 'Table1',
       CAST((CAST(id as nvarchar(12)) + ' | ' + name) as nvarchar(max)),
       CASE WHEN i.delStatus = 1 THEN 2
            WHEN i.delStatus = 0 THEN 3
            WHEN ISNULL(i.delStatus, 0) = 0 AND i.displayStatus = 0 THEN 4
            WHEN ISNULL(i.delStatus, 0) = 0 AND i.displayStatus = 1 THEN 5
       END
FROM INSERTED i
INNER JOIN Deleted d ON i.Id = d.Id
WHERE (i.name = d.name OR i.name IS NULL and d.name IS NULL)
AND (i.lname = d.lname OR i.lname IS NULL and d.lname IS NULL)
AND
(
(
    ISNULL(i.delStatus, 0) <> ISNULL(d.delStatus, 0)
    AND ISNULL(i.displayStatus, 0) = ISNULL(d.displayStatus, 0)
)
OR
(
    ISNULL(i.delStatus, 0) = ISNULL(d.delStatus, 0)
    AND ISNULL(i.displayStatus, 0) <> ISNULL(d.displayStatus, 0)
)
)
</code>```

At this point, the @LogData table contains whatever data you would send to sp_insert_LOG. I suggest to create a new stored procedure like sp_insert_log that will accept a table valued parameter and handle this data.

Body:
I have a table like this:

---------------table1--------------------------------------------
    id    |   name  | lname   |   displayStatus   | delStatus
    1         a         b               1              0
    2         aa        bb              0              0
    3         aaa       bbb             1              0
    4         aaaa      bbbb            0              1

---------------tbl_LOG--------------------------------------------
    id    |   rowData| actType

and i have this trigger for update:

alter trigger tgr_delete
on table1
after update
as
begin
    declare @rowData nvarchar(max), @username nvarchar(50)

    if update(delStatus)
    begin
        if((select delStatus from inserted) = 1)
        begin
            set @rowData = (select CAST((CAST(id as nvarchar(12)) + ' | ' + name) as nvarchar(max)) from inserted)

            exec sp_insert_LOG 'table1', @rowData, 2
        end
        else if((select delStatus from inserted) = 0)
        begin
            set @rowData = (select CAST((CAST(id as nvarchar(12)) + ' | ' + name) as nvarchar(max)) from inserted)

            exec sp_insert_LOG 'table1', @rowData, 3
        end
    end
    else if update(displayStatus)
    begin
        if((delStatus = 0 or delStatus is null) and (select displayStatus from inserted) = 0)
        begin
            set @rowData = (select CAST((CAST(id as nvarchar(12)) + ' | ' + name) as nvarchar(max)) from inserted)

            exec sp_insert_LOG 'table1', @rowData, 4
        end
        else if((delStatus = 0 or delStatus is null) and (select displayStatus from inserted) = 1)
        begin
            set @rowData = (select CAST((CAST(id as nvarchar(12)) + ' | ' + name) as nvarchar(max)) from inserted)

            exec sp_insert_LOG 'table1', @rowData, 5
        end
    end
end

and i have 3 stored procedure

first is for update delStatus

second is for update displayStatus

and third is for update all column

now What should I do to avoid interfering with the first two conditions.

Body:
This is not a complete answer since I don't know what sp_insert_LOG does, but it should get you started on the right direction:

CREATE TRIGGER trg_Table1_Update ON Table1
FOR UPDATE
AS

DECLARE @LogData AS TABLE
(
    TableName sysname,
    RowData nvarchar(max),
    ActionType int
)

INSERT INTO @LogData (TableName, RowData, ActionType)
SELECT 'Table1',
       CAST((CAST(id as nvarchar(12)) + ' | ' + name) as nvarchar(max)),
       CASE WHEN i.delStatus = 1 THEN 2
            WHEN i.delStatus = 0 THEN 3
            WHEN ISNULL(i.delStatus, 0) = 0 AND i.displayStatus = 0 THEN 4
            WHEN ISNULL(i.delStatus, 0) = 0 AND i.displayStatus = 1 THEN 5
       END
FROM INSERTED i
INNER JOIN Deleted d ON i.Id = d.Id
WHERE (i.name = d.name OR i.name IS NULL and d.name IS NULL)
AND (i.lname = d.lname OR i.lname IS NULL and d.lname IS NULL)
AND
(
(
    ISNULL(i.delStatus, 0) <> ISNULL(d.delStatus, 0)
    AND ISNULL(i.displayStatus, 0) = ISNULL(d.displayStatus, 0)
)
OR
(
    ISNULL(i.delStatus, 0) = ISNULL(d.delStatus, 0)
    AND ISNULL(i.displayStatus, 0) <> ISNULL(d.displayStatus, 0)
)
)

At this point, the @LogData table contains whatever data you would send to sp_insert_LOG. I suggest to create a new stored procedure like sp_insert_log that will accept a table valued parameter and handle this data.


答:
```<code>var completeData = {...topData, ...bottomData};
</code>```

This is object spread syntax.

Body:
var completeData = {...topData, ...bottomData};

This is object spread syntax.


问:
changing bluetooth low energy gatt timeout or flushing read stream to detect disconnect event quicker
I am looking for an android way to flush the characteristics the app receives from a Ble device, or at least know from the data that the connection has been lost as soon as it actually is except around 15 seconds after it disconnected. If there is a way to change the gatt connection timeout, that would be significantly better.

To repeat in a different form, I would like a solution (or a link that can explain) to detect a disconnect of the BLE device faster than whatever the timeout value currently is, by a means of seeing if the value I am getting is fresh by flushing the characteristic, or changing the disconnect timeout on the gatt side, so I can see within a second of it disconnecting to trigger other code.

答:
Other answers in here may be better than this one, but this was my solution to the problem. Be sure to attempt Emil's answer before using this.

What I did since the time was too slow to wait for it was to check the rssi since it always is changing. If there is a period of time, lets say 3 seconds, where the value stays the same, it disconnects from the device. This goes around the 15 second timeout and adds our own timeout.

This would be what would be needed to check signal strength. This was written a couple of years ago, so some things may need to be changed.

```<code>private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {

    @Override
    public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status){
            //check for signal strength changes. It will stay the same if we
            //are getting no updates
            if(mLastRssi == rssi){
                disconnectCounter++;
                if(disconnectCounter> 140) {
                    //disconnect logic as if we are done with connection
                    //maybe start listening for device again to reconnect
                    disconnectCounter = 0;
                }
            }
            else{
                //we are connected. reset counter
                disconnectCounter = 0;
            }
            //store last value as global for comparison
            mLastRssi= rssi;
    }
}
</code>```

Somewhere in a loop, call

```<code>mBluetoothGatt.readRemoteRssi()
</code>```

Body:
Other answers in here may be better than this one, but this was my solution to the problem. Be sure to attempt Emil's answer before using this.

What I did since the time was too slow to wait for it was to check the rssi since it always is changing. If there is a period of time, lets say 3 seconds, where the value stays the same, it disconnects from the device. This goes around the 15 second timeout and adds our own timeout.

This would be what would be needed to check signal strength. This was written a couple of years ago, so some things may need to be changed.

private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {

    @Override
    public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status){
            //check for signal strength changes. It will stay the same if we
            //are getting no updates
            if(mLastRssi == rssi){
                disconnectCounter++;
                if(disconnectCounter> 140) {
                    //disconnect logic as if we are done with connection
                    //maybe start listening for device again to reconnect
                    disconnectCounter = 0;
                }
            }
            else{
                //we are connected. reset counter
                disconnectCounter = 0;
            }
            //store last value as global for comparison
            mLastRssi= rssi;
    }
}

Somewhere in a loop, call

mBluetoothGatt.readRemoteRssi()


问:
How to migrate a template from Handlebar to React's JSX
I need to migrate my code from backbone view to react view.

I am using Handlebars templates in the backbone view which I need to put in a React component's render method.

Can someone suggest how to move these two utility methods to JSX

with

```<code><div>
  {{#with paymentDescription}}
    <div class="test">
      <p>some text</p>
    </div>
  {{/with}}
</div>
</code>```

unless

```<code><div class="name">
  {{ abc.def.firstName }} {{ abc.def.lastName }}
  {{#unless quote.def}}

  {{/unless}}
</div>
</code>```

答:
Everything inside the unless block will be rendered if the expression returns a falsy value.

Replace it with the following jsx code:

```<code>let unless_block = "";
if (!props.quote.def) { unless_block = " " }
return (
    <div className="name">
    { props.abc.def.firstName } { props.abc.def.lastName }
    {unless_block}
    </div>
);
</code>```

Normally, Handlebars templates are evaluated against the context passed into the compiled method.
The with helper method is used to shift the context for a section of a template.

Borrowing your example, if your props contain values abc.def.firstName and abc.def.lastName, you can just use firstName and lastName inside a {{with abc.def}} block.

There is no variable being used inside your example of a withblock. That's why I modified your example a bit to show how you can use the abbreviated paymentDescription inside jsx expression. Suppose the paymentDescription was originally burried deep inside props.abd.def. Then you can write the following jsx code:

```<code>let paymentDescription = props.abc.def.paymentDescription; //shift the context

return (
    <div>
    <div className="test">
    {paymentDescription}
    </div>
    </div>
);
</code>```

Body:
I need to migrate my code from backbone view to react view.

I am using Handlebars templates in the backbone view which I need to put in a React component's render method.

Can someone suggest how to move these two utility methods to JSX

with

  {{#with paymentDescription}}

some text

  {{/with}}

unless

  {{ abc.def.firstName }} {{ abc.def.lastName }}
  {{#unless quote.def}}

  {{/unless}}

Body:
Everything inside the unless block will be rendered if the expression returns a falsy value.

Replace it with the following jsx code:

let unless_block = "";
if (!props.quote.def) { unless_block = "&nbsp;" }
return (
    <div className="name">
    { props.abc.def.firstName } { props.abc.def.lastName }
    {unless_block}
    </div>
);

Normally, Handlebars templates are evaluated against the context passed into the compiled method.
The with helper method is used to shift the context for a section of a template.

Borrowing your example, if your props contain values abc.def.firstName and abc.def.lastName, you can just use firstName and lastName inside a {{with abc.def}} block.

There is no variable being used inside your example of a withblock. That's why I modified your example a bit to show how you can use the abbreviated paymentDescription inside jsx expression. Suppose the paymentDescription was originally burried deep inside props.abd.def. Then you can write the following jsx code:

let paymentDescription = props.abc.def.paymentDescription; //shift the context

return (
    <div>
    <div className="test">
    {paymentDescription}
    </div>
    </div>
);


问:
I need to to know whether the Bluetooth is on/off regardless of the device
So I am trying to check whether the Bluetooth is on or off on the iOS device when this segment is running on my iPad Air it prints Bluetooth Status: Turned On or Bluetooth Status: Turned Off when I turn the Bluetooth on/off. But when I run this on the iPad 2 it prints Bluetooth Status: Not Supported.

```<code>fileprivate var bluetoothPeripheralManager: CBPeripheralManager?

override init() {
    super.init()
    let options = [CBCentralManagerOptionShowPowerAlertKey:0]
    bluetoothPeripheralManager = CBPeripheralManager(delegate: self, queue: nil, options: options)
}

extension PrintersMonitor: CBPeripheralManagerDelegate{
func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager){
    var statusMessage = ""

    switch peripheral.state {
    case .poweredOn:
        statusMessage = "Bluetooth Status: Turned On"
    case .poweredOff:
        statusMessage = "Bluetooth Status: Turned Off"
    case .resetting:
        statusMessage = "Bluetooth Status: Resetting"
    case .unauthorized:
        statusMessage = "Bluetooth Status: Not Authorized"
    case .unsupported:
        statusMessage = "Bluetooth Status: Not Supported"
        bluetoothPeripheralManager = nil
    default:
        statusMessage = "Bluetooth Status: Unknown"
    }

    log(statusMessage)

    if peripheral.state == .poweredOn{
        if state != .searching{
            resume()
        }
    }else if peripheral.state == .poweredOff{
        pause(isPrinting: false)
    }
}
</code>```

}

Is there something missing from my side!
I need to to know whether the Bluetooth is on/off regardless of the device!

答:
The iPad 2 does not support BLE, which is the Bluetooth that is exposed by Core Bluetooth. This is why you get a status of "not supported". </p>

<p>There are no APIs that provide the power status of legacy Bluetooth. </p>

Body:
So I am trying to check whether the Bluetooth is on or off on the iOS device when this segment is running on my iPad Air it prints Bluetooth Status: Turned On or Bluetooth Status: Turned Off when I turn the Bluetooth on/off. But when I run this on the iPad 2 it prints Bluetooth Status: Not Supported.

fileprivate var bluetoothPeripheralManager: CBPeripheralManager?

override init() {
    super.init()
    let options = [CBCentralManagerOptionShowPowerAlertKey:0]
    bluetoothPeripheralManager = CBPeripheralManager(delegate: self, queue: nil, options: options)
}

extension PrintersMonitor: CBPeripheralManagerDelegate{
func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager){
    var statusMessage = ""

    switch peripheral.state {
    case .poweredOn:
        statusMessage = "Bluetooth Status: Turned On"
    case .poweredOff:
        statusMessage = "Bluetooth Status: Turned Off"
    case .resetting:
        statusMessage = "Bluetooth Status: Resetting"
    case .unauthorized:
        statusMessage = "Bluetooth Status: Not Authorized"
    case .unsupported:
        statusMessage = "Bluetooth Status: Not Supported"
        bluetoothPeripheralManager = nil
    default:
        statusMessage = "Bluetooth Status: Unknown"
    }

    log(statusMessage)

    if peripheral.state == .poweredOn{
        if state != .searching{
            resume()
        }
    }else if peripheral.state == .poweredOff{
        pause(isPrinting: false)
    }
}

}

Is there something missing from my side!
I need to to know whether the Bluetooth is on/off regardless of the device!

Body:
The iPad 2 does not support BLE, which is the Bluetooth that is exposed by Core Bluetooth. This is why you get a status of "not supported".

There are no APIs that provide the power status of legacy Bluetooth.


问:
What are the best use cases for Akka framework
I have heard lots of raving about Akka framework (Java/Scala service platform), but so far have not seen many actual examples of use cases it would be good for. So I would be interested in hearing about things developers have used it succesfully.

Only one limitation: please do not include case of writing a chat server.
(why? since this has been overused as an example for lots of similar things)

答: I've recently implemented the canonical map-reduce example in Akka: Word count. So it's one use case of Akka: better performance. It was more of a experiment of JRuby and Akka's actors than anything else, but it also shows that Akka is not Scala or Java only: it works on all languages on top of JVM.</p>


问:
Error while importing gobblin gradle project into IDE
I am getting this error while I try to import the gobblin distribution into my IDE , I have tried both inteliJ and eclipse , not able to find any luck.
Below are the errors which I get when I try to import.
In Eclipse the error is:</p>

```<code>*org.gradle.tooling.BuildException: Could not run build action using Gradle distribution 'https://services.gradle.org/distributions/gradle-3.3-bin.zip'.
*
For InteliJ
*Cause: startup failed: build file 'C:\Users\sayyad.ghazi\Desktop\gob\gobblin-master\gobblin-restli\gobblin-throttling-service\gobblin-throttling-service-api\build.gradle': 1: unexpected token: .. @ line 1, column 1. ../../api.gradle ^ 1 error*
</code>```

答:
This is because on Windows, Git can not create symbolic link file on non-admins mode. Symbolic link file is created as text file, containing a symbolic link.

Try the following command in Administrator Mode:

```<code>git clone -c core.symlinks=true <URL>
</code>```

Then check the content of symbolic link file, such as "build.gradle" in your description. It should be the same as the content of "../../api.gradle", not just a symbolic link.

See git-for-windows-wiki-Symbolic-Links for more details.

Body:
I am getting this error while I try to import the gobblin distribution into my IDE , I have tried both inteliJ and eclipse , not able to find any luck.
Below are the errors which I get when I try to import.
In Eclipse the error is:

*org.gradle.tooling.BuildException: Could not run build action using Gradle distribution 'https://services.gradle.org/distributions/gradle-3.3-bin.zip'.
*
For InteliJ
*Cause: startup failed: build file 'C:\Users\sayyad.ghazi\Desktop\gob\gobblin-master\gobblin-restli\gobblin-throttling-service\gobblin-throttling-service-api\build.gradle': 1: unexpected token: .. @ line 1, column 1. ../../api.gradle ^ 1 error*

Body:
This is because on Windows, Git can not create symbolic link file on non-admins mode. Symbolic link file is created as text file, containing a symbolic link.

Try the following command in Administrator Mode:

git clone -c core.symlinks=true <URL>

Then check the content of symbolic link file, such as "build.gradle" in your description. It should be the same as the content of "../../api.gradle", not just a symbolic link.

See git-for-windows-wiki-Symbolic-Links for more details.


问:
How to make custom buttons in corona, Lua
I'm trying to make a mobile application with a screen that looks like this:

I'm making this using Corona, it's written in the Lua language

It's a scrollable list of buttons, I somewhat understand the scroll aspect. What I'm having problems now is making a button that can have more than one line of text and also an image. I've literally been searching for hour but haven't found anything (I'm probably bad at finding things). I think I'd have to create a custom button but I have no idea how to do this. I would appreciate some help with this be it a link or just some lines of text explaining it, thank you so much!

答:
use custom view

custom_button_view.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/iconImgV"
        android:layout_alignParentRight="true"
        android:layout_width="100dp"
        android:layout_alignParentTop="true"
        android:background="#ff0000"
        android:layout_height="100dp" />

    <TextView
        android:id="@+id/titleTv"
        android:textSize="18sp"
        android:text="Title"
        android:layout_toLeftOf="@+id/iconImgV"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/descriptionTv"
        android:layout_width="wrap_content"
        android:text="description"
        android:textSize="14sp"
        android:layout_below="@+id/titleTv"
        android:layout_toLeftOf="@+id/iconImgV"
        android:layout_height="wrap_content" />
</RelativeLayout>
</code>```

and CustomButtonView.java

```<code>public class CustomButtonView extends RelativeLayout {

    Context context;

    //view
    ImageView iconImgV;
    TextView titleTv, descriptionTv;

    //value
    int drawableIcon;
    String title,description;

    public CustomButtonView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.context = context;
        init();
    }

    public CustomButtonView(Context context) {
        super(context);
        init();
    }

    public CustomButtonView(Context context, AttributeSet attrs) {
        super(context, attrs);

        this.context = context;
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.customButtonViewAttrs);
        drawableIcon = typedArray.getInt(R.styleable.customButtonViewAttrs_drawableIcon,0);
        title = typedArray.getString(R.styleable.customButtonViewAttrs_title);
        description = typedArray.getString(R.styleable.customButtonViewAttrs_description);
        typedArray.recycle();

        init();
    }

    public void init() {

        if (isInEditMode())
            return;

        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View myView = inflater.inflate(R.layout.custom_button_view, null);

        iconImgV = (ImageView) myView.findViewById(R.id.iconImgV);
        titleTv = (TextView) myView.findViewById(R.id.titleTv);
        descriptionTv = (TextView) myView.findViewById(R.id.descriptionTv);

        titleTv.setText(title);

        addView(myView);
    }
}
</code>```

and value/attrs.xml

```<code><declare-styleable name="customButtonViewAttrs">
    <attr name="title" format="string" />
    <attr name="description" format="string" />
    <attr name="drawableIcon" format="integer" />
</declare-styleable>
</code>```

you can use this way

```<code><com.example.rasoul.testprojectstacj.CustomButtonView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:title = "Car"/>
</code>```

Body:
use custom view

custom_button_view.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/iconImgV"
        android:layout_alignParentRight="true"
        android:layout_width="100dp"
        android:layout_alignParentTop="true"
        android:background="#ff0000"
        android:layout_height="100dp" />

    <TextView
        android:id="@+id/titleTv"
        android:textSize="18sp"
        android:text="Title"
        android:layout_toLeftOf="@+id/iconImgV"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/descriptionTv"
        android:layout_width="wrap_content"
        android:text="description"
        android:textSize="14sp"
        android:layout_below="@+id/titleTv"
        android:layout_toLeftOf="@+id/iconImgV"
        android:layout_height="wrap_content" />
</RelativeLayout>

and CustomButtonView.java

public class CustomButtonView extends RelativeLayout {

    Context context;

    //view
    ImageView iconImgV;
    TextView titleTv, descriptionTv;

    //value
    int drawableIcon;
    String title,description;

    public CustomButtonView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.context = context;
        init();
    }

    public CustomButtonView(Context context) {
        super(context);
        init();
    }

    public CustomButtonView(Context context, AttributeSet attrs) {
        super(context, attrs);

        this.context = context;
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.customButtonViewAttrs);
        drawableIcon = typedArray.getInt(R.styleable.customButtonViewAttrs_drawableIcon,0);
        title = typedArray.getString(R.styleable.customButtonViewAttrs_title);
        description = typedArray.getString(R.styleable.customButtonViewAttrs_description);
        typedArray.recycle();

        init();
    }

    public void init() {

        if (isInEditMode())
            return;

        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View myView = inflater.inflate(R.layout.custom_button_view, null);

        iconImgV = (ImageView) myView.findViewById(R.id.iconImgV);
        titleTv = (TextView) myView.findViewById(R.id.titleTv);
        descriptionTv = (TextView) myView.findViewById(R.id.descriptionTv);

        titleTv.setText(title);

        addView(myView);
    }
}

and value/attrs.xml

<declare-styleable name="customButtonViewAttrs">
    <attr name="title" format="string" />
    <attr name="description" format="string" />
    <attr name="drawableIcon" format="integer" />
</declare-styleable>

you can use this way

<com.example.rasoul.testprojectstacj.CustomButtonView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:title = "Car"/>


问:
"sign" function in Swift
Is there a function that returns +1 for positive numbers and -1 for negatives in Swift?

I looked through the enormous file that appears if you right-click->definitions on a typical function, but if it's in there I don't know it's name.

I did this:

```<code>(num < 0 ? -1 : 1)
</code>```

But I'd rather use a built-in function if there is any--for self-documenting reasons at the minimum.

答:
In Swift-4 floats have a new property:

```<code>public var sign: FloatingPointSign { get }
</code>```

(However this only checks the sign bit, so it’ll fail for some cases like -0 — see that accepted answer above.)

Title: "sign" function in Swift

Body:
Is there a function that returns +1 for positive numbers and -1 for negatives in Swift?

I looked through the enormous file that appears if you right-click->definitions on a typical function, but if it's in there I don't know it's name.

I did this:

(num < 0 ? -1 : 1)

But I'd rather use a built-in function if there is any--for self-documenting reasons at the minimum.

Body:
In Swift-4 floats have a new property:

public var sign: FloatingPointSign { get }

(However this only checks the sign bit, so it’ll fail for some cases like -0 — see that accepted answer above.)