问:
Scrollview not scrolling in Android (AdjustPan)
Here is a my scrollView xml

```<code><android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/myCoordinator"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@drawable/gradient_toolbar"
        android:clickable="true"
        android:orientation="vertical">

        <ImageView
            android:id="@+id/u_back_action"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:layout_marginLeft="8dp"
            android:padding="4dp"
            android:src="@mipmap/arrow_back_blue" />

        <TextView
            android:id="@+id/headerTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:text="@string/u_my_page"
            android:textColor="#ffffff"
            android:textSize="16dp" />

        <TextView
            android:id="@+id/my_profile_edit"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_marginRight="8dp"
            android:gravity="center"
            android:padding="8dp"

            android:singleLine="true"
            android:text="@string/u_save"
            android:textColor="#ffffff"
            android:textSize="14dp"
            android:visibility="gone" />

    </RelativeLayout>

</android.support.design.widget.AppBarLayout>

<android.support.v4.widget.NestedScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:orientation="vertical"

        >

        <LinearLayout
            android:id="@+id/user_header_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="25dp"
            android:gravity="center_vertical"
            android:orientation="vertical">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_marginLeft="16dp"
                android:layout_marginRight="16dp"
                android:layout_marginTop="10dp"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/u_user_fullname"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:maxLines="1"
                    android:singleLine="true"
                    android:textColor="#4d4d4d"
                    android:textSize="@dimen/u_common_text_size"

                    />
            </LinearLayout>

        </LinearLayout>

        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:fillViewport="true">

            <LinearLayout
                android:id="@+id/container"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:fitsSystemWindows="true"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/personal_settings"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerInParent="true"
                    android:layout_marginTop="30dp"
                    android:text="@string/u_personal_settings_txt"
                    android:textColor="#4d4d4d"
                    android:textSize="16dp" />

                <View
                    android:layout_width="match_parent"
                    android:layout_height="1dp"
                    android:background="#cccccc" />

                <android.support.design.widget.TextInputLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_marginTop="16dp"
                    android:background="@drawable/selector_edittext_action"
                    android:textColor="#4d4d4d"

                    android:textColorHint="#b3b3b3">

                    <android.support.design.widget.TextInputEditText
                        android:id="@+id/first_name_lat"
                        android:layout_width="match_parent"
                        android:layout_height="48dp"
                        android:background="@null"
                        android:hint="@string/u_first_name_lat"
                        android:imeOptions="actionNext"

                        android:inputType="textNoSuggestions"
                        android:textColor="#4d4d4d"

                        android:textColorHint="#b3b3b3"
                        android:textCursorDrawable="@null"
                        android:textSize="16dp"
                        app:backgroundTint="@android:color/white" />
                </android.support.design.widget.TextInputLayout>

                <android.support.design.widget.TextInputLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_marginTop="16dp"
                    android:background="@drawable/selector_edittext_action"
                    android:textColor="#4d4d4d"

                    android:textColorHint="#b3b3b3">

                    <android.support.design.widget.TextInputEditText
                        android:id="@+id/last_name_lat"
                        android:layout_width="match_parent"
                        android:layout_height="48dp"
                        android:background="@null"
                        android:hint="@string/u_last_name_lat"
                        android:imeOptions="actionNext"

                        android:inputType="textNoSuggestions"
                        android:textColor="#4d4d4d"

                        android:textColorHint="#b3b3b3"
                        android:textCursorDrawable="@null"
                        android:textSize="16dp"
                        app:backgroundTint="@android:color/white" />
                </android.support.design.widget.TextInputLayout>

                <android.support.design.widget.TextInputLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_marginTop="16dp"
                    android:background="@drawable/selector_edittext_action"
                    android:textColor="#4d4d4d"

                    android:textColorHint="#b3b3b3">

                    <android.support.design.widget.TextInputEditText
                        android:id="@+id/u_address"
                        android:layout_width="match_parent"
                        android:layout_height="48dp"
                        android:background="@null"
                        android:hint="@string/u_address"
                        android:imeOptions="actionNext"

                        android:inputType="textNoSuggestions"
                        android:textColor="#4d4d4d"

                        android:textColorHint="#b3b3b3"
                        android:textCursorDrawable="@null"
                        android:textSize="16dp"
                        app:backgroundTint="@android:color/white" />
                </android.support.design.widget.TextInputLayout>

                <android.support.design.widget.TextInputLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_marginTop="16dp"
                    android:background="@drawable/selector_edittext_action"
                    android:textColor="#4d4d4d"

                    android:textColorHint="#b3b3b3">

                    <android.support.design.widget.TextInputEditText
                        android:id="@+id/u_gender"
                        android:layout_width="match_parent"
                        android:layout_height="48dp"
                        android:background="@null"
                        android:hint="@string/u_gender"
                        android:imeOptions="actionNext"

                        android:inputType="textNoSuggestions"
                        android:textColor="#4d4d4d"

                        android:textColorHint="#b3b3b3"
                        android:textCursorDrawable="@null"
                        android:textSize="16dp"
                        app:backgroundTint="@android:color/white" />
                </android.support.design.widget.TextInputLayout>

            </LinearLayout>

        </ScrollView>
    </LinearLayout>

</android.support.v4.widget.NestedScrollView>
</code>```

In my activity's SoftInputMode is adjustNothing.

As i said my scrollview not working.I search about my problem ,one solution is to change adjustResize,but i don't want this solution, because my AppBarLayout layout moving up.

My questions is that, is it a possible to move scrollview at the moment(adjustNothing).I can't show my last edittext when keyboard is showing.
Or,Is it a possible to disable move up AppBarLayout layout in my xml if I use adjustResize or adjustPan ?
Thanks everyone

答:
Here is a solution

Add this line in NestedScrollView 's child Layout

```<code>android:descendantFocusability="afterDescendants"
</code>```

and manifest file

```<code>android:windowSoftInputMode="adjustResize"
</code>```

Body:
Here is a my scrollView xml

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/myCoordinator"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@drawable/gradient_toolbar"
        android:clickable="true"
        android:orientation="vertical">

        <ImageView
            android:id="@+id/u_back_action"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:layout_marginLeft="8dp"
            android:padding="4dp"
            android:src="@mipmap/arrow_back_blue" />

        <TextView
            android:id="@+id/headerTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:text="@string/u_my_page"
            android:textColor="#ffffff"
            android:textSize="16dp" />

        <TextView
            android:id="@+id/my_profile_edit"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_marginRight="8dp"
            android:gravity="center"
            android:padding="8dp"

            android:singleLine="true"
            android:text="@string/u_save"
            android:textColor="#ffffff"
            android:textSize="14dp"
            android:visibility="gone" />

    </RelativeLayout>

</android.support.design.widget.AppBarLayout>

<android.support.v4.widget.NestedScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:orientation="vertical"

        >

        <LinearLayout
            android:id="@+id/user_header_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="25dp"
            android:gravity="center_vertical"
            android:orientation="vertical">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_marginLeft="16dp"
                android:layout_marginRight="16dp"
                android:layout_marginTop="10dp"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/u_user_fullname"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:maxLines="1"
                    android:singleLine="true"
                    android:textColor="#4d4d4d"
                    android:textSize="@dimen/u_common_text_size"

                    />
            </LinearLayout>

        </LinearLayout>

        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:fillViewport="true">

            <LinearLayout
                android:id="@+id/container"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:fitsSystemWindows="true"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/personal_settings"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerInParent="true"
                    android:layout_marginTop="30dp"
                    android:text="@string/u_personal_settings_txt"
                    android:textColor="#4d4d4d"
                    android:textSize="16dp" />

                <View
                    android:layout_width="match_parent"
                    android:layout_height="1dp"
                    android:background="#cccccc" />

                <android.support.design.widget.TextInputLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_marginTop="16dp"
                    android:background="@drawable/selector_edittext_action"
                    android:textColor="#4d4d4d"

                    android:textColorHint="#b3b3b3">

                    <android.support.design.widget.TextInputEditText
                        android:id="@+id/first_name_lat"
                        android:layout_width="match_parent"
                        android:layout_height="48dp"
                        android:background="@null"
                        android:hint="@string/u_first_name_lat"
                        android:imeOptions="actionNext"

                        android:inputType="textNoSuggestions"
                        android:textColor="#4d4d4d"

                        android:textColorHint="#b3b3b3"
                        android:textCursorDrawable="@null"
                        android:textSize="16dp"
                        app:backgroundTint="@android:color/white" />
                </android.support.design.widget.TextInputLayout>

                <android.support.design.widget.TextInputLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_marginTop="16dp"
                    android:background="@drawable/selector_edittext_action"
                    android:textColor="#4d4d4d"

                    android:textColorHint="#b3b3b3">

                    <android.support.design.widget.TextInputEditText
                        android:id="@+id/last_name_lat"
                        android:layout_width="match_parent"
                        android:layout_height="48dp"
                        android:background="@null"
                        android:hint="@string/u_last_name_lat"
                        android:imeOptions="actionNext"

                        android:inputType="textNoSuggestions"
                        android:textColor="#4d4d4d"

                        android:textColorHint="#b3b3b3"
                        android:textCursorDrawable="@null"
                        android:textSize="16dp"
                        app:backgroundTint="@android:color/white" />
                </android.support.design.widget.TextInputLayout>

                <android.support.design.widget.TextInputLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_marginTop="16dp"
                    android:background="@drawable/selector_edittext_action"
                    android:textColor="#4d4d4d"

                    android:textColorHint="#b3b3b3">

                    <android.support.design.widget.TextInputEditText
                        android:id="@+id/u_address"
                        android:layout_width="match_parent"
                        android:layout_height="48dp"
                        android:background="@null"
                        android:hint="@string/u_address"
                        android:imeOptions="actionNext"

                        android:inputType="textNoSuggestions"
                        android:textColor="#4d4d4d"

                        android:textColorHint="#b3b3b3"
                        android:textCursorDrawable="@null"
                        android:textSize="16dp"
                        app:backgroundTint="@android:color/white" />
                </android.support.design.widget.TextInputLayout>

                <android.support.design.widget.TextInputLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_marginTop="16dp"
                    android:background="@drawable/selector_edittext_action"
                    android:textColor="#4d4d4d"

                    android:textColorHint="#b3b3b3">

                    <android.support.design.widget.TextInputEditText
                        android:id="@+id/u_gender"
                        android:layout_width="match_parent"
                        android:layout_height="48dp"
                        android:background="@null"
                        android:hint="@string/u_gender"
                        android:imeOptions="actionNext"

                        android:inputType="textNoSuggestions"
                        android:textColor="#4d4d4d"

                        android:textColorHint="#b3b3b3"
                        android:textCursorDrawable="@null"
                        android:textSize="16dp"
                        app:backgroundTint="@android:color/white" />
                </android.support.design.widget.TextInputLayout>

            </LinearLayout>

        </ScrollView>
    </LinearLayout>

</android.support.v4.widget.NestedScrollView>

In my activity's SoftInputMode is adjustNothing.

As i said my scrollview not working.I search about my problem ,one solution is to change adjustResize,but i don't want this solution, because my AppBarLayout layout moving up.

My questions is that, is it a possible to move scrollview at the moment(adjustNothing).I can't show my last edittext when keyboard is showing.
Or,Is it a possible to disable move up AppBarLayout layout in my xml if I use adjustResize or adjustPan ?
Thanks everyone

Body:
Here is a solution

Add this line in NestedScrollView 's child Layout

android:descendantFocusability="afterDescendants"

and manifest file

android:windowSoftInputMode="adjustResize"


来源: stackexchange

问:
Angular 2 TypeError: Object doesn't support property or method 'json'
I am building a basic CRUD application that references a SSMS database, using an Angular 2 front end and a MVC back end. I am running into the error when i run my HTTPGet on any browser:

TypeError: Object doesn't support property or method 'json'

I have a debug point set for the service call but it doesn't get there, so I am assuming the issue is in the component somewhere..

I have googled for about a day and a half, and have found a lot of people that have other things in the place of the 'json', but I cannot find anyone else with this issue exactly. Below you will find the could for my Get. If there is any other snippets you need please let me know.

Here is my Get component:

```<code>import { Component, OnInit, ViewChild } from '@angular/core';
import { CorrectionCodeService } from '../Service/correctioncode.service';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal';
import { ICorrectionCode } from '../Models/ICorrectionCode';
import { DBOperation } from '../Shared/enum';
import { Observable } from 'rxjs/Rx';
import { Global } from '../Shared/global';

@Component({

templateUrl: 'app/Components/correctioncode.component.html'

})

`enter code here`export class CorrectionCodeComponent implements OnInit {

@ViewChild('modal') modal: ModalComponent;
corrCodes: ICorrectionCode[];
corrCode: ICorrectionCode;
msg: string;
indLoading: boolean = false;
form: FormGroup;
dbops: DBOperation;
modalTitle: string;
modalBtnTitle: string;

constructor(private fb: FormBuilder,private _corrCodeService: CorrectionCodeService) { }

ngOnInit() {
    this.form = this.fb.group({
        id: [''],
        pgm_code_name: [''],
        rec_act_code: [''],
        rgln_Year: [''],
        rgln_type_name: [''],
        rgln_one_code: [''],
        rgln_two_code: [''],
        rgln_three_code: [''],
        rgln_title_text: [''],
        rgln_desc_text: [''],
        sevrty_code: [''],
        valdtn_value: [''],
        last_updt_dt: [''],
        last_updt_logn_id: [''],
        creat_dt: [''],
        creat_logn_id: [''],
        del_dt: [''],
        del_logn_id: [''],
        prev_rec_id: ['']
    });

    this.getCorrectionCodes();

}
 getCorrectionCodes(): void {
    this.indLoading = true;
    this._corrCodeService.get(Global.BASE_CORRECTION_CODE_ENDPOINT)
        .subscribe(corrCodes => {
            this.corrCodes = corrCodes; this.indLoading = false;
        }, error => this.msg = <any>error);
}
</code>```

And, here is my service:

```<code>import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
@Injectable()
export class CorrectionCodeService {
    constructor(private _http: Http) { }

    get(url: string): Observable<any> {
        let headers = new Headers({ 'accept': 'applicationCache/json' });
        let options = new RequestOptions({ headers: headers });
        return this._http.get(url,options)
            .map((response: Response) => <any>response.json())
            // .do(data => console.log("All: " + JSON.stringify(data)));

    }
</code>```

here is my app.module.ts:

```<code>import { NgModule } from '@angular/core';
import { APP_BASE_HREF } from '@angular/common';
import { BrowserModule } from '@angular/platform-browser';
import { ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { HttpModule } from '@angular/http';
import { routing } from './app.routing';
import { HomeComponent } from './Components/home.component';
import { CorrectionCodeComponent } from './Components/correctioncode.component';
import { Ng2Bs3ModalModule } from 'ng2-bs3-modal/ng2-bs3-modal';
import { CorrectionCodeService } from './Service/correctioncode.service';
import { UploadFileComponent } from './Components/uploadFile.component';
import { UploadFileService } from './Service/uploadFile.service';

@NgModule({
    imports: [BrowserModule, ReactiveFormsModule, HttpModule, routing, Ng2Bs3ModalModule],
    declarations: [AppComponent, CorrectionCodeComponent, HomeComponent,  UploadFileComponent],
    providers: [{ provide: APP_BASE_HREF, useValue: '/' }, CorrectionCodeService, UploadFileService],
    bootstrap: [AppComponent]
})

export class AppModule { }
</code>```

Here is my controller:

```<code>using CorrectionCodeEditor.Models;
using CorrectionCodeEditor.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;

namespace CorrectionCodeEditor.Controllers
{
    public class CorrectionCodeController : BaseAPIController
    {
        string ProgramAreaName = "FAS";
        private CorrectionCodeRepository context;
        public CorrectionCodeController()
        {

            context = new CorrectionCodeRepository();
        }

        [HttpGet]
        public HttpResponseMessage Get()
        {
            var corrCodes = context.GetAllCorrectionCodes(ProgramAreaName).AsEnumerable();
                return ToJson(corrCodes);
        }
</code>```

my ToJson method:

```<code>protected HttpResponseMessage ToJson(dynamic obj)
        {
            var response = Request.CreateResponse(HttpStatusCode.OK);
            response.Content = new StringContent(JsonConvert.SerializeObject(obj), Encoding.UTF8, "application/json");
            return response;
        }
</code>```

and my Contextual DB Repository:

```<code> public IEnumerable<CorrectionCode> GetAllCorrectionCodes(string pgm_area_name)
        {
            using (con)
            {
                 con.Open();
                var dP = new DynamicParameters();
                dP.Add("@ProgramAreaName", pgm_area_name);
                IEnumerable<CorrectionCode> corrCodeList = con.Query<CorrectionCode>("[mobile].[p_get_correction_codes_by_params]", dP, commandType: CommandType.StoredProcedure);
                return corrCodeList;
            }
        }
</code>```

EDIT#1 Compile Tile Error from Google Developer Tools while the screen displays "TypeError: error.json is not a function":

```<code>SyntaxError: Unexpected token < in JSON at position 0
    at JSON.parse (<anonymous>)
    at Response.Body.json (body.ts:36)
    at MapSubscriber.eval [as project] (correctioncode.service.ts:12)
    at MapSubscriber._next (map.ts:75)
    at MapSubscriber.Subscriber.next (Subscriber.ts:95)
    at XMLHttpRequest.onLoad (xhr_backend.ts:104)
    at ZoneDelegate.invokeTask (zone.js:265)
    at Object.onInvokeTask (ng_zone.ts:254)
    at ZoneDelegate.invokeTask (zone.js:264)
    at Zone.runTask (zone.js:154)
</code>```

here is a screenshot of the error readout in IE11 while the screen is saying "TypeError: Object doesn't support property or method 'json'":

答:
Turns out @joshvito was on the right track with the Angular being ok, just not completely correct. The problem is that in the tutorial i was following, it suggested that i edit the RouteConfig.ts to:

```<code> public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
           routes.MapRoute(
                            name: "Default",
                            url: "{*anything}",
                            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
                        );
        }
</code>```

But the example was using Web Api not ASP.net, and because I am so new to Angular, I didn't know that I should have been editing the WebApiConfig.cs, which was expecting an action name that I was not passing in.   so when i changed my get method in my component to this:

```<code>getCorrectionCodes(): void {
        this.indLoading = true;
        this._corrCodeService.get(Global.BASE_CORRECTION_CODE_ENDPOINT+"get")
            .subscribe(corrCodes => {
                this.corrCodes = corrCodes; this.indLoading = false;
            }, error => this.msg = <any>error);
    }
</code>```

Everything started to work as it should.

ContentLicense: CC BY-SA 3.0

Body:
I am building a basic CRUD application that references a SSMS database, using an Angular 2 front end and a MVC back end. I am running into the error when i run my HTTPGet on any browser:

TypeError: Object doesn't support property or method 'json'

I have a debug point set for the service call but it doesn't get there, so I am assuming the issue is in the component somewhere..

I have googled for about a day and a half, and have found a lot of people that have other things in the place of the 'json', but I cannot find anyone else with this issue exactly. Below you will find the could for my Get. If there is any other snippets you need please let me know.

Here is my Get component:

import { Component, OnInit, ViewChild } from '@angular/core';
import { CorrectionCodeService } from '../Service/correctioncode.service';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal';
import { ICorrectionCode } from '../Models/ICorrectionCode';
import { DBOperation } from '../Shared/enum';
import { Observable } from 'rxjs/Rx';
import { Global } from '../Shared/global';

@Component({

templateUrl: 'app/Components/correctioncode.component.html'

})

`enter code here`export class CorrectionCodeComponent implements OnInit {

@ViewChild('modal') modal: ModalComponent;
corrCodes: ICorrectionCode[];
corrCode: ICorrectionCode;
msg: string;
indLoading: boolean = false;
form: FormGroup;
dbops: DBOperation;
modalTitle: string;
modalBtnTitle: string;

constructor(private fb: FormBuilder,private _corrCodeService: CorrectionCodeService) { }

ngOnInit() {
    this.form = this.fb.group({
        id: [''],
        pgm_code_name: [''],
        rec_act_code: [''],
        rgln_Year: [''],
        rgln_type_name: [''],
        rgln_one_code: [''],
        rgln_two_code: [''],
        rgln_three_code: [''],
        rgln_title_text: [''],
        rgln_desc_text: [''],
        sevrty_code: [''],
        valdtn_value: [''],
        last_updt_dt: [''],
        last_updt_logn_id: [''],
        creat_dt: [''],
        creat_logn_id: [''],
        del_dt: [''],
        del_logn_id: [''],
        prev_rec_id: ['']
    });

    this.getCorrectionCodes();

}
 getCorrectionCodes(): void {
    this.indLoading = true;
    this._corrCodeService.get(Global.BASE_CORRECTION_CODE_ENDPOINT)
        .subscribe(corrCodes => {
            this.corrCodes = corrCodes; this.indLoading = false;
        }, error => this.msg = <any>error);
}

And, here is my service:

import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
@Injectable()
export class CorrectionCodeService {
    constructor(private _http: Http) { }

    get(url: string): Observable<any> {
        let headers = new Headers({ 'accept': 'applicationCache/json' });
        let options = new RequestOptions({ headers: headers });
        return this._http.get(url,options)
            .map((response: Response) => <any>response.json())
            // .do(data => console.log("All: " + JSON.stringify(data)));

    }

here is my app.module.ts:

import { NgModule } from '@angular/core';
import { APP_BASE_HREF } from '@angular/common';
import { BrowserModule } from '@angular/platform-browser';
import { ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { HttpModule } from '@angular/http';
import { routing } from './app.routing';
import { HomeComponent } from './Components/home.component';
import { CorrectionCodeComponent } from './Components/correctioncode.component';
import { Ng2Bs3ModalModule } from 'ng2-bs3-modal/ng2-bs3-modal';
import { CorrectionCodeService } from './Service/correctioncode.service';
import { UploadFileComponent } from './Components/uploadFile.component';
import { UploadFileService } from './Service/uploadFile.service';

@NgModule({
    imports: [BrowserModule, ReactiveFormsModule, HttpModule, routing, Ng2Bs3ModalModule],
    declarations: [AppComponent, CorrectionCodeComponent, HomeComponent,  UploadFileComponent],
    providers: [{ provide: APP_BASE_HREF, useValue: '/' }, CorrectionCodeService, UploadFileService],
    bootstrap: [AppComponent]
})

export class AppModule { }

Here is my controller:

using CorrectionCodeEditor.Models;
using CorrectionCodeEditor.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;

namespace CorrectionCodeEditor.Controllers
{
    public class CorrectionCodeController : BaseAPIController
    {
        string ProgramAreaName = "FAS";
        private CorrectionCodeRepository context;
        public CorrectionCodeController()
        {

            context = new CorrectionCodeRepository();
        }

        [HttpGet]
        public HttpResponseMessage Get()
        {
            var corrCodes = context.GetAllCorrectionCodes(ProgramAreaName).AsEnumerable();
                return ToJson(corrCodes);
        }

my ToJson method:

protected HttpResponseMessage ToJson(dynamic obj)
        {
            var response = Request.CreateResponse(HttpStatusCode.OK);
            response.Content = new StringContent(JsonConvert.SerializeObject(obj), Encoding.UTF8, "application/json");
            return response;
        }

and my Contextual DB Repository:

 public IEnumerable<CorrectionCode> GetAllCorrectionCodes(string pgm_area_name)
        {
            using (con)
            {
                 con.Open();
                var dP = new DynamicParameters();
                dP.Add("@ProgramAreaName", pgm_area_name);
                IEnumerable<CorrectionCode> corrCodeList = con.Query<CorrectionCode>("[mobile].[p_get_correction_codes_by_params]", dP, commandType: CommandType.StoredProcedure);
                return corrCodeList;
            }
        }

EDIT#1 Compile Tile Error from Google Developer Tools while the screen displays "TypeError: error.json is not a function":

SyntaxError: Unexpected token < in JSON at position 0
    at JSON.parse (<anonymous>)
    at Response.Body.json (body.ts:36)
    at MapSubscriber.eval [as project] (correctioncode.service.ts:12)
    at MapSubscriber._next (map.ts:75)
    at MapSubscriber.Subscriber.next (Subscriber.ts:95)
    at XMLHttpRequest.onLoad (xhr_backend.ts:104)
    at ZoneDelegate.invokeTask (zone.js:265)
    at Object.onInvokeTask (ng_zone.ts:254)
    at ZoneDelegate.invokeTask (zone.js:264)
    at Zone.runTask (zone.js:154)

here is a screenshot of the error readout in IE11 while the screen is saying "TypeError: Object doesn't support property or method 'json'":

Body:
Turns out @joshvito was on the right track with the Angular being ok, just not completely correct. The problem is that in the tutorial i was following, it suggested that i edit the RouteConfig.ts to:

 public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
           routes.MapRoute(
                            name: "Default",
                            url: "{*anything}",
                            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
                        );
        }

But the example was using Web Api not ASP.net, and because I am so new to Angular, I didn't know that I should have been editing the WebApiConfig.cs, which was expecting an action name that I was not passing in.   so when i changed my get method in my component to this:

getCorrectionCodes(): void {
        this.indLoading = true;
        this._corrCodeService.get(Global.BASE_CORRECTION_CODE_ENDPOINT+"get")
            .subscribe(corrCodes => {
                this.corrCodes = corrCodes; this.indLoading = false;
            }, error => this.msg = <any>error);
    }

Everything started to work as it should.


问:
In a csv file get all values of rows and columns between 2 specific words say start and stop
I have a csv file with time,event and acceleration values(x,y,z) as columns and I want to fetch only the values between the event values start and stop(where in event column there are various words like start stop motion location). I have done using data frame in pandas but I get values of start and stop instead of all the values in between them.

Csv file:

```<code> time   event   earthAcceleration.x earthAcceleration.y earthAcceleration.z

2017-11-22T09:20:13.944 motion  -0.006380   -0.001029   -0.010781

2017-11-22T09:20:13.954 start

2017-11-22T09:20:13.964 motion  0.008521    -0.008223   0.022574

2017-11-22T09:20:13.974 stop

2017-11-22T09:20:13.984 motion  0.016283    0.003181    0.006969
</code>```

Code:

```<code>import pandas as pd
df = pd.read_csv('nehi.csv')
df = df[df['event'].between('start', 'stop', inclusive=True)]
df
</code>```

My output is: values where the words = start and stop

```<code>time    event   earthAccelerationx earthAccelerationy earthAccelerationz

2017-11-22T09:20:13.954 start   NaN NaN NaN

2017-11-22T09:20:13.974 stop    NaN NaN NaN
</code>```

Also tried

```<code>start= event[(event['event']=='start') & (event['event']=='stop')]
start.head()
</code>```

But gives empty values

Desired output is: Values of time and acceleration between the words start and stop.

```<code>time       event    earthAccelerationx  earthAccelerationy earthAccelerationz

2017-11-22T09:20:13.964 motion  0.008521    -0.008223   0.022574
</code>```

Goal: To extract all column and row values between 2 keywords in column named events.

答:
Try this

```<code>start_index = df[df['event'].str.contains('start')].index[0] + 1
stop_index = df[df['event'].str.contains('stop')].index[0] - 1
new_df = df.loc[start_index:stop_index, :]

    time                    event   earthAcceleration.x earthAcceleration.y earthAcceleration.z
2   2017-11-22T09:20:13.964 motion  0.008521            -0.008223   0.022574
</code>```

EDIT: This will give you a list of dataframes with with rows between each start and stop

```<code>start_index = df[df['event'].str.contains('start')].index
stop_index = df[df['event'].str.contains('stop')].index
l_dfs = []
for i in range(len(start_index)):
    l_dfs.append(df.loc[start_index[i]+1:stop_index[i]-1, :])
</code>```

Body:
I have a csv file with time,event and acceleration values(x,y,z) as columns and I want to fetch only the values between the event values start and stop(where in event column there are various words like start stop motion location). I have done using data frame in pandas but I get values of start and stop instead of all the values in between them.

Csv file:

 time   event   earthAcceleration.x earthAcceleration.y earthAcceleration.z

2017-11-22T09:20:13.944 motion  -0.006380   -0.001029   -0.010781

2017-11-22T09:20:13.954 start

2017-11-22T09:20:13.964 motion  0.008521    -0.008223   0.022574

2017-11-22T09:20:13.974 stop

2017-11-22T09:20:13.984 motion  0.016283    0.003181    0.006969

Code:

import pandas as pd
df = pd.read_csv('nehi.csv')
df = df[df['event'].between('start', 'stop', inclusive=True)]
df

My output is: values where the words = start and stop

time    event   earthAccelerationx earthAccelerationy earthAccelerationz

2017-11-22T09:20:13.954 start   NaN NaN NaN

2017-11-22T09:20:13.974 stop    NaN NaN NaN

Also tried

start= event[(event['event']=='start') & (event['event']=='stop')]
start.head()

But gives empty values

Desired output is: Values of time and acceleration between the words start and stop.

time       event    earthAccelerationx  earthAccelerationy earthAccelerationz

2017-11-22T09:20:13.964 motion  0.008521    -0.008223   0.022574

Goal: To extract all column and row values between 2 keywords in column named events.

Body:
Try this

start_index = df[df['event'].str.contains('start')].index[0] + 1
stop_index = df[df['event'].str.contains('stop')].index[0] - 1
new_df = df.loc[start_index:stop_index, :]

    time                    event   earthAcceleration.x earthAcceleration.y earthAcceleration.z
2   2017-11-22T09:20:13.964 motion  0.008521            -0.008223   0.022574

EDIT: This will give you a list of dataframes with with rows between each start and stop

start_index = df[df['event'].str.contains('start')].index
stop_index = df[df['event'].str.contains('stop')].index
l_dfs = []
for i in range(len(start_index)):
    l_dfs.append(df.loc[start_index[i]+1:stop_index[i]-1, :])


问:
C++ code gets strangely skipped with no optimizations. Any ideas why?
I looked for an answer for two days to this with no success. I've never come across this problem before so I'll try my best. Please bear with me.

I returned to a C++ project I created over a year ago, which at the time ran without problems. I came across this interesting and incredibly annoying problem the other day as I was trying to get the same program to run. The code was something like:

file.h

```<code>...
short id;
...
</code>```

file.cc

```<code>id = 0;
while (id < some_large_number)
{
   id = foo();
   if (id == 2)
   {
      //do something
   }
   else if (id == 2900)
   {
      //do something
   }
   else if (id == 30000)
   {
      //do something
   }
   else if (id == 40000)
   {
      //do something
   }
   else if (id == 45000)
   {
      //do something
   }
   else
   {
      //do something else
   }
}
</code>```

The constant numbers were macros in hex notation that I expanded for this example. Turns out that this was truly a bug, but the debugger did not make it easy to discover. Heres what happened:

As I was trying to step through the code using GDB (with no optimizations), I noticed that GDB would jump straight to the else statement after reaching if (id == 30000), everytime. Because the numbers were c macros in hex notation, I did not notice at first that 40000 was beyond the limit of a signed short. This was very misleading, and spent hours trying to figure it out: I recompiled external libraries, reinstalled g++, among other things.

Obviously, making id an unsigned short fixed the problem. The other problem seems like a compiler issue. But I still don't understand, why were those sections of code completely skipped during execution, and with no optimizations? Why would it not go through each if statement and that way I could identify the real problem? Any ideas?

Thanks so much. I hope this is okay for a first question.

答:
GCC is an excellent optimizing compiler, however even when error and warning information is enabled via -Werror, -Wall, etc GCC still doesn't produce the same level of information a diagnostic compile does.  While developing the code I would recommend using Clang, a diagnostic compiler, to help in finding bugs and error.  Clang is intended to compatible with GCC, and with the exception of some more esoteric features I have had no problem changing my CC between the two in my Makefile.

Being an optimizing compiler, I believe GCC by default enable dead-code elimination.  This would cause all branches which the compiler detected impossible, such as those outside the bounds of your id variable, to be eliminated.  You might be able to disable that type of dead-code elimination.

ContentLicense: CC BY-SA 2.5

Body:
I looked for an answer for two days to this with no success. I've never come across this problem before so I'll try my best. Please bear with me.

I returned to a C++ project I created over a year ago, which at the time ran without problems. I came across this interesting and incredibly annoying problem the other day as I was trying to get the same program to run. The code was something like:

file.h

...
short id;
...

file.cc

id = 0;
while (id < some_large_number)
{
   id = foo();
   if (id == 2)
   {
      //do something
   }
   else if (id == 2900)
   {
      //do something
   }
   else if (id == 30000)
   {
      //do something
   }
   else if (id == 40000)
   {
      //do something
   }
   else if (id == 45000)
   {
      //do something
   }
   else
   {
      //do something else
   }
}

The constant numbers were macros in hex notation that I expanded for this example. Turns out that this was truly a bug, but the debugger did not make it easy to discover. Heres what happened:

As I was trying to step through the code using GDB (with no optimizations), I noticed that GDB would jump straight to the else statement after reaching if (id == 30000), everytime. Because the numbers were c macros in hex notation, I did not notice at first that 40000 was beyond the limit of a signed short. This was very misleading, and spent hours trying to figure it out: I recompiled external libraries, reinstalled g++, among other things.

Obviously, making id an unsigned short fixed the problem. The other problem seems like a compiler issue. But I still don't understand, why were those sections of code completely skipped during execution, and with no optimizations? Why would it not go through each if statement and that way I could identify the real problem? Any ideas?

Thanks so much. I hope this is okay for a first question.


问:
SonarQube scan across multiple branches
Scenario: 3 branches in a repository:

'master' -> 'prod' branch which gets pushed to production

'devBranch A' - a development branch - assume single developer

'devBranch B' - a dev branch, same as above.

We have SonarQube (6.x) for static code analysis in a Jenkins CI/CD pipeline kicked off by the creation of a pull request in BitBucket. We use Git Jenkins plugin. Right now, Git is, upon creation of a pull request, doing a checkout from BitBucket as such:

```<code>Checking out Revision cdd7cc6fa787d111bbc6afef2728fa3353aab499 (origin/feature/TestTuesday)
</code>```

I am trying to ensure that only the code from the specific pull request in that specific branch - and not all commits in any branch matching the pattern "origin/feature/*" is analysed by SonarQube - trying to ensure we never get every commit in all branches that match our Git Jenkins plugin 'branch specifier'

So how do I: ensure SonarQube scans only the code in a specific pull request as opposed to all changes in branches that match the branch specifier pattern.

thanks

EDIT: I was tempted to delete this question as I don't feel I've articulated this issue I'm trying to solve in a way that is actually technically relevant...

When the Jenkins/Git plugin checks out that code, it is actually checking out the correct code - that Revision is the Head commit in the repo from which the PR originated... so... this is doing what is expected.

Previously, another issue had been the correct paths to the source code for sonarqube analysis: they needed to be relative to the workspace for the Jenkins job...

Summary: instead of deleting this question, I'm just clarifying my poor wording and giving a brief follow up for anyone who may find any of this edifying.

答: I would suggest to take a look to the git hooks. Probably you can write a hook to check your code in Sonar before it will be pushed to repository. Additionally you can use plugin in your IDE like SonarLint which can be used to analyze code on the fly in IDE according your rules in Sonar, but hook will be more strictly comparing to plugin.

Title: SonarQube scan across multiple branches

Body:
Scenario: 3 branches in a repository:

'master' -> 'prod' branch which gets pushed to production

'devBranch A' - a development branch - assume single developer

'devBranch B' - a dev branch, same as above.

We have SonarQube (6.x) for static code analysis in a Jenkins CI/CD pipeline kicked off by the creation of a pull request in BitBucket. We use Git Jenkins plugin. Right now, Git is, upon creation of a pull request, doing a checkout from BitBucket as such:

Checking out Revision cdd7cc6fa787d111bbc6afef2728fa3353aab499 (origin/feature/TestTuesday)

I am trying to ensure that only the code from the specific pull request in that specific branch - and not all commits in any branch matching the pattern "origin/feature/*" is analysed by SonarQube - trying to ensure we never get every commit in all branches that match our Git Jenkins plugin 'branch specifier'

So how do I: ensure SonarQube scans only the code in a specific pull request as opposed to all changes in branches that match the branch specifier pattern.

thanks

EDIT: I was tempted to delete this question as I don't feel I've articulated this issue I'm trying to solve in a way that is actually technically relevant...

When the Jenkins/Git plugin checks out that code, it is actually checking out the correct code - that Revision is the Head commit in the repo from which the PR originated... so... this is doing what is expected.

Previously, another issue had been the correct paths to the source code for sonarqube analysis: they needed to be relative to the workspace for the Jenkins job...

Summary: instead of deleting this question, I'm just clarifying my poor wording and giving a brief follow up for anyone who may find any of this edifying.


问:
python module import so slow in other IDE but in Spyder it's 20 times faster
I am learning data science, using Python and I suddenly found it take so much time to load these lib like numpy,pandas when I use Pycharm or sublime text3.

But when I use Spyder which has been installed by Anaconda to run my program, it's super fast!

I really want to use Pycharm, how to make it as fast as Spyder?

I also found Spyder will run several Python.exe, Spyder will run 5 python.exe background while sublime just one. Is it the reason that it's so fast?

For example to import these libs:
[import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
from scipy.stats import norm
from sklearn.preprocessing import StandardScaler
from scipy import stats
import warnings
import sympy

]

Then it will take:

sublime 4.1 seconds

Spyder 0.06 seconds

答:
You can use Jupiter Notebooks directly in Pycharm.

See here.

As far as my understanding goes, Spyder uses a Jupyter kernel so it does not have to reload all your imports all the time. Spyder runs the kernel in the background, where Pycharm starts a new Python instance each time you hit run. Each one of those has to load all the dependencies again.


问:
How to buffer and play video in a Android and iOS like Netflix and Iflix
I have a requirement to develop a Android and iOS mobile apps that allow subscribers to view movies like the way Netflix and Iflix does it.

I would like to know if this can be achieved by inbuilt Video playing classes or widgets on the Android and iOS platforms, or if we will need a library or SDK for this.

I came across this URL on how to stream video in Android apps. Would this approach suffice for this requirement?

https://code.tutsplus.com/tutorials/streaming-video-in-android-apps--cms-19888

答:
Netflix and similar systems use ABR to deliver video to mobile devices - ABR allows the client device or player download the video in chunks, e.g 10 second chunks, and select the next chunk from the bit rate most appropriate to the current network conditions. See here for an example:

https://stackoverflow.com/a/42365034/334402

There are several ABR protocols but the two most common at this time are HLS and DASH. HLS must be used to deliver video streams to iOS devices due to the apple guidelines (at this time and for video over 10 mins which may be accessed on a mobile network - the guidelines can change over time) and DASH is probably more common on Android devices, although HLS can be supported on Android also.

Most Android players now can handle ABR - the Android Exoplayer is a good example, is very well used and supports this natively:

https://github.com/google/ExoPlayer

Take a look at the Developers Guide (included in the link above at the time of writing) which shows how to include ExoPlayer in your app.

On iOS the native player supports ABR using HLS.


问:
Get last emitted object from multiple sources
To be more specific, I don't want an array of emitted object.  I want the last object emitted by either source.

Currently, it's working like this

```<code>.withLatestFrom(subject1, subject2)
.switchMap([val1, val2]) => {...}
</code>```

What I want is

```<code>.withLatestFrom(subject1, subject2)
.switchMap(latestVal) => {...}
</code>```

To avoid a possible x=y problem.  What I have is two subjects.  Subject1 and Subject2.

If subject2 has emitted any values, that value will always trump subject1. In my use case once subject 2 has started emitted, this particular module will ignore subject 1.  But subject 1 will be used elsewhere.

But I want a way to feed these two subjects as sources and either get the last emitted value, or the last value of subject 2 if it's not null.  If subject 2 is null then get the last value from subject 1.

答:
Here is an example that I think does what you are looking for:

const first = Rx.Observable.interval(1000).map(x => `first (${x})`);
const second = Rx.Observable.interval(2000).map(x => `second (${x})`);

Rx.Observable.merge(
  first.takeUntil(second),
  second
)
.subscribe(
  x => { console.log('next: ', x); },
  null,
  () => { console.log('complete'); }
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.5/Rx.min.js"></script></code>```

The takeUntil will cause the "first" observable to stop emitting values for this subscription the first time the "second" observable emits.

Body:
To be more specific, I don't want an array of emitted object.  I want the last object emitted by either source.

Currently, it's working like this

.withLatestFrom(subject1, subject2)
.switchMap([val1, val2]) => {...}

What I want is

.withLatestFrom(subject1, subject2)
.switchMap(latestVal) => {...}

To avoid a possible x=y problem.  What I have is two subjects.  Subject1 and Subject2.

If subject2 has emitted any values, that value will always trump subject1. In my use case once subject 2 has started emitted, this particular module will ignore subject 1.  But subject 1 will be used elsewhere.

But I want a way to feed these two subjects as sources and either get the last emitted value, or the last value of subject 2 if it's not null.  If subject 2 is null then get the last value from subject 1.

Body:
Here is an example that I think does what you are looking for:

const first = Rx.Observable.interval(1000).map(x => `first (${x})`);
const second = Rx.Observable.interval(2000).map(x => `second (${x})`);

Rx.Observable.merge(
  first.takeUntil(second),
  second
)
.subscribe(
  x => { console.log('next: ', x); },
  null,
  () => { console.log('complete'); }
);

<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.5/Rx.min.js"></script>

The takeUntil will cause the "first" observable to stop emitting values for this subscription the first time the "second" observable emits.


问:
Hooking API Calls in Current Process?
How do I go about hooking/redirecting a function in a DLL (say, CreateThread from Kernel32.dll) loaded in the current process?

(I don't have control over which pieces of code call CreateThread, so it's not like I can just have the code something else instead.)

The language doesn't matter much; I'm guessing C/C++ would be the best choices for this.

Update:

I forgot to mention: I'm not looking for solutions that require the bundling of extra libraries into my program; I was looking for a manual way of doing the hooking (such as by rewriting the address of the function), not for using an external library to do this.

But thanks to those who mentioned an external library; sorry I didn't say this earlier.

答:
Check out http://easyhook.codeplex.com/

It's an API Hooking framework.
Its open source, very easy to use!

Title: Hooking API Calls in Current Process?


问:
several MYSQL statements in one
I have a place ('place') where I can have some boxes ('box'). In  each box, I can have items ('item'). I can also have items in the place outside of a box.
I want to delete a place, and by so, to delete each boxes in the place, including items in each boxes as well as the items in the place but outside any box.
I got it working with the following separated statements:

1: select the place

```<code>SELECT placeid, placename
FROM place
WHERE userid = (SELECT id
                FROM user
                WHERE username = 'username' AND password ='password')
  AND placename = 'placename'
</code>```

2: select the boxes in that place

```<code>SELECT boxid, boxname
FROM box
WHERE placeid = 'id'
</code>```

3a: for each box, delete the items in it

```<code>DELETE FROM item
WHERE boxid = 'boxid'
</code>```

3b: then delete the box

```<code>DELETE FROM box
WHERE id = 'boxid'
</code>```

4: delete the items in the place not in a box

```<code>DELETE FROM item
WHERE placeid = 'placeid' AND boxid = 0
</code>```

5: delete the place

```<code>DELETE FROM place
WHERE id = placeid
</code>```

This is working but of course this is slow. The error management is also not that nice to work with.

Is there a way of doing all this with fewer SQL statements or even only one?

I got of course the same question for deleting a box in one statement!

edit: mysql with php

Thanks a lot.

答:
Because item and box both have a placeid (per the info in your question) you can simplify this task a bit, but you still need 3 DELETE statements:

```<code>SELECT p.placeid
INTO #PlacesToDelete
FROM place p
INNER JOIN [user] u ON p.userid = u.id
WHERE u.username = 'username'
    AND u.[password] = 'password'
    AND p.placename = 'placename'

DELETE i
FROM item i
INNER JOIN #PlacesToDelete ptd ON i.placeid = ptd.placeid

DELETE b
FROM box b
INNER JOIN #PlacesToDelete ptd ON b.placeid = ptd.placeid

DELETE p
FROM place p
INNER JOIN #PlacesToDelete ptd ON p.placeid = ptd.placeid
</code>```

Or, if this is related to MySQL, you should be able to further simplify and use a single statement:

```<code>DELETE p, b, i
FROM place p
INNER JOIN [user] u ON p.userid = u.id
INNER JOIN box b ON b.placeid = p.placeid
INNER JOIN item i ON i.placeid = p.placeid
WHERE u.username = 'username'
    AND u.[password] = 'password'
    AND p.placename = 'placename'
</code>```

Edit: Based on the comment if an item is in a box, placeid is equal to 0 because it belongs to a box, not a place, here's an updated query that will delete everything you want:

```<code>DELETE i1, i2, b, p
FROM place p
INNER JOIN [user] u ON p.userid = u.id
INNER JOIN box b ON b.placeid = p.placeid
INNER JOIN item i1 ON i1.placeid = p.placeid
INNER JOIN item i2 ON i2.boxid = b.boxid
WHERE u.username = 'username'
    AND u.[password] = 'password'
    AND p.placename = 'placename'
</code>```

Title: several MYSQL statements in one

Body:
I have a place ('place') where I can have some boxes ('box'). In  each box, I can have items ('item'). I can also have items in the place outside of a box.
I want to delete a place, and by so, to delete each boxes in the place, including items in each boxes as well as the items in the place but outside any box.
I got it working with the following separated statements:

1: select the place

SELECT placeid, placename
FROM place
WHERE userid = (SELECT id
                FROM user
                WHERE username = 'username' AND password ='password')
  AND placename = 'placename'

2: select the boxes in that place

SELECT boxid, boxname
FROM box
WHERE placeid = 'id'

3a: for each box, delete the items in it

DELETE FROM item
WHERE boxid = 'boxid'

3b: then delete the box

DELETE FROM box
WHERE id = 'boxid'

4: delete the items in the place not in a box

DELETE FROM item
WHERE placeid = 'placeid' AND boxid = 0

5: delete the place

DELETE FROM place
WHERE id = placeid

This is working but of course this is slow. The error management is also not that nice to work with.

Is there a way of doing all this with fewer SQL statements or even only one?

I got of course the same question for deleting a box in one statement!

edit: mysql with php

Thanks a lot.

Body:
Because item and box both have a placeid (per the info in your question) you can simplify this task a bit, but you still need 3 DELETE statements:

SELECT p.placeid
INTO #PlacesToDelete
FROM place p
INNER JOIN [user] u ON p.userid = u.id
WHERE u.username = 'username'
    AND u.[password] = 'password'
    AND p.placename = 'placename'

DELETE i
FROM item i
INNER JOIN #PlacesToDelete ptd ON i.placeid = ptd.placeid

DELETE b
FROM box b
INNER JOIN #PlacesToDelete ptd ON b.placeid = ptd.placeid

DELETE p
FROM place p
INNER JOIN #PlacesToDelete ptd ON p.placeid = ptd.placeid

Or, if this is related to MySQL, you should be able to further simplify and use a single statement:

DELETE p, b, i
FROM place p
INNER JOIN [user] u ON p.userid = u.id
INNER JOIN box b ON b.placeid = p.placeid
INNER JOIN item i ON i.placeid = p.placeid
WHERE u.username = 'username'
    AND u.[password] = 'password'
    AND p.placename = 'placename'

Edit: Based on the comment if an item is in a box, placeid is equal to 0 because it belongs to a box, not a place, here's an updated query that will delete everything you want:

DELETE i1, i2, b, p
FROM place p
INNER JOIN [user] u ON p.userid = u.id
INNER JOIN box b ON b.placeid = p.placeid
INNER JOIN item i1 ON i1.placeid = p.placeid
INNER JOIN item i2 ON i2.boxid = b.boxid
WHERE u.username = 'username'
    AND u.[password] = 'password'
    AND p.placename = 'placename'


问:
Excel VBA: Generate N Number of Sheets Based on Cel Value

I want to create a macro that will generate N number of template sheets based on the value of a cel. For example, User inputs 4 into this particular cell and it subsequently generates 4 new sheets in the workbook of this template.

I've searched all through Stack overflow for a question that matches mine but none do. The closest I found was this and although the inital headline question asks generally the same question, when going into detail the user who asked this changes their question to"insert number of cells based on a cell value". Still I used this as a starting point.

```<code>Sub CreateSheets()
  Dim facilitiesNum As Integer

   facilitiesNum = Range("B2").Value

  sheetsNeeded = facilitiesNum
  With ThisWorkbook.Sheets

  For i = sheetsNeeded To Master.Range("B2").Value2
  .Item("TemplateSheet").Copy After:=.Item(.Count)
  .Item(.Count).Name = sheetsNeeded
  Next
  End With
End Sub
</code>```

I am new to VBA so I could be very off syntax-wise but in pseudocode my goal is

```<code>      numberOfTemplates = cell value
      numSheetsNeeded = numberOfTemplates

    For i = numSheetsNeeded To NumOfTemp:
    create sheets using numSheetsNeeded as reference for how many need to be
    generated
</code>```

How do I go about doing this?

答:
If you just want to add new sheets this should be enough </p>

```<code>Sub CreateSheets()

   Dim facilitiesNum As Long

   facilitiesNum = Range("B2").Value

   With ThisWorkbook.Sheets
      For i = 1 To facilitiesNum
          .Item("TemplateSheet").Copy After:=.Item(.Count)
          .Item(.Count).Name = i
      Next i
   End With
end sub
</code>```

Body:
I want to create a macro that will generate N number of template sheets based on the value of a cel. For example, User inputs 4 into this particular cell and it subsequently generates 4 new sheets in the workbook of this template.

I've searched all through Stack overflow for a question that matches mine but none do. The closest I found was this and although the inital headline question asks generally the same question, when going into detail the user who asked this changes their question to"insert number of cells based on a cell value". Still I used this as a starting point.

Sub CreateSheets()
  Dim facilitiesNum As Integer

   facilitiesNum = Range("B2").Value

  sheetsNeeded = facilitiesNum
  With ThisWorkbook.Sheets

  For i = sheetsNeeded To Master.Range("B2").Value2
  .Item("TemplateSheet").Copy After:=.Item(.Count)
  .Item(.Count).Name = sheetsNeeded
  Next
  End With
End Sub

I am new to VBA so I could be very off syntax-wise but in pseudocode my goal is

      numberOfTemplates = cell value
      numSheetsNeeded = numberOfTemplates

    For i = numSheetsNeeded To NumOfTemp:
    create sheets using numSheetsNeeded as reference for how many need to be
    generated

How do I go about doing this?

Body:
If you just want to add new sheets this should be enough

Sub CreateSheets()

   Dim facilitiesNum As Long

   facilitiesNum = Range("B2").Value

   With ThisWorkbook.Sheets
      For i = 1 To facilitiesNum
          .Item("TemplateSheet").Copy After:=.Item(.Count)
          .Item(.Count).Name = i
      Next i
   End With
end sub


问:
Add a delay or sleep to an array of promises in nodejs
I have a promise chain problem I have been grappling with.  I make a call out to an external api that returns me data that I need to process and ingest into a mongo database. I am using nodejs and mongodb with express.  Anyway, the calls to the api are working ok, the problem is that I am making tons of them at once.  I want to slow them down, like make all the calls for one set. Wait a minute. Make all the calls for the next set.  If this was a known amount of sets I would just promise chain them.  I dont know how many sets there are so I am looping through them.  I think the closure is the problem but cant work around it. on to the example code!</p>

```<code>  function readApi(carFactory){
    var promise = new Promise(function(resolve, reject) {
      // call out to api, get set of car data from factory1

      console.log(carFactory);
      if (true) {
        console.log('resolved');
        resolve("Stuff worked!"+carFactory);
      }
      else {
        reject(Error("It broke"));
      }
    });
    return promise;
  }

  function manager(){

    //singular call
    readApi("this is a singular test").then(returnedThing=>{
      console.log(returnedThing); //Stuff worked! this is a singular test
    });

    let dynamicList = ["carFactory1", "carFactory2","carFactory3","carFactory..N"];
    let readApiAction = [];
    dynamicList.forEach(carIter=>{
      readApiAction.push(readApi(carIter));
    });
    //ok so now I got an array of promise objects.
    //I want to call the first one, wait 1 minute and then call the next one.

    //originally I was calling promise.all, but there is no way to get at
    //each promise to pause them out so this code is what I am looking to fix
    let results= Promise.all(readApiAction);
    results.then(data=>{
      data.forEach(resolvedData=>{
        console.log(resolvedData); //Stuff worked carFactory1, etc...
      });
    });

    //singular call with timeout, this does not work, each one called at the same time
    let readApiActionTimeouts = [];
    dynamicList.forEach(carIter=>{
      setTimeout(callingTimeout(carIter), 6000);
    });
  }

  //just a function to call the promise in a timeout
  //this fails with this  - TypeError: "callback" argument must be a function
  function callingTimeout(carIter){
    readApi(carIter).then(returnedThing=>{
      console.log("timeout version"+returnedThing);
    });
  }
</code>```

答:
You could use recursion for something like this.

When you call .forEach, each iteration happens immediately.

In the example below, doSomething is not called until the setTimeout occurs, which means each letter is printed 1 second apart.

let letters = ["a", "b", "c"];

function doSomething(arr) {
  console.log(arr[0]);
  if (arr.length > 1) {
    setTimeout(() => doSomething(arr.slice(1)), 1000);
  }
}

doSomething(letters);```
</div>
</div>
</p>

<p>Alternately, for your array of promises:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let promises = [
  Promise.resolve("A"),
  Promise.resolve("B"),
  Promise.resolve("C"),
];

function doSomething(arr) {
  arr[0].then((result) => {
    console.log(result);
    if (arr.length > 1) {
      setTimeout(() => doSomething(arr.slice(1)), 1000);
    }
  })
}

doSomething(promises);</code>```

Body:
I have a promise chain problem I have been grappling with.  I make a call out to an external api that returns me data that I need to process and ingest into a mongo database. I am using nodejs and mongodb with express.  Anyway, the calls to the api are working ok, the problem is that I am making tons of them at once.  I want to slow them down, like make all the calls for one set. Wait a minute. Make all the calls for the next set.  If this was a known amount of sets I would just promise chain them.  I dont know how many sets there are so I am looping through them.  I think the closure is the problem but cant work around it. on to the example code!

  function readApi(carFactory){
    var promise = new Promise(function(resolve, reject) {
      // call out to api, get set of car data from factory1

      console.log(carFactory);
      if (true) {
        console.log('resolved');
        resolve("Stuff worked!"+carFactory);
      }
      else {
        reject(Error("It broke"));
      }
    });
    return promise;
  }

  function manager(){

    //singular call
    readApi("this is a singular test").then(returnedThing=>{
      console.log(returnedThing); //Stuff worked! this is a singular test
    });

    let dynamicList = ["carFactory1", "carFactory2","carFactory3","carFactory..N"];
    let readApiAction = [];
    dynamicList.forEach(carIter=>{
      readApiAction.push(readApi(carIter));
    });
    //ok so now I got an array of promise objects.
    //I want to call the first one, wait 1 minute and then call the next one.

    //originally I was calling promise.all, but there is no way to get at
    //each promise to pause them out so this code is what I am looking to fix
    let results= Promise.all(readApiAction);
    results.then(data=>{
      data.forEach(resolvedData=>{
        console.log(resolvedData); //Stuff worked carFactory1, etc...
      });
    });

    //singular call with timeout, this does not work, each one called at the same time
    let readApiActionTimeouts = [];
    dynamicList.forEach(carIter=>{
      setTimeout(callingTimeout(carIter), 6000);
    });
  }

  //just a function to call the promise in a timeout
  //this fails with this  - TypeError: "callback" argument must be a function
  function callingTimeout(carIter){
    readApi(carIter).then(returnedThing=>{
      console.log("timeout version"+returnedThing);
    });
  }

Body:
You could use recursion for something like this.

When you call .forEach, each iteration happens immediately.

In the example below, doSomething is not called until the setTimeout occurs, which means each letter is printed 1 second apart.

let letters = ["a", "b", "c"];

function doSomething(arr) {
  console.log(arr[0]);
  if (arr.length > 1) {
    setTimeout(() => doSomething(arr.slice(1)), 1000);
  }
}

doSomething(letters);

Alternately, for your array of promises:

let promises = [
  Promise.resolve("A"),
  Promise.resolve("B"),
  Promise.resolve("C"),
];

function doSomething(arr) {
  arr[0].then((result) => {
    console.log(result);
    if (arr.length > 1) {
      setTimeout(() => doSomething(arr.slice(1)), 1000);
    }
  })
}

doSomething(promises);


问:
How to open a file and have the contents be the output of an executed command?
For example:

When open/read /var/command_result.txt would have its contents be the results of executing sysctl -x -B 16 kern.arandom.

So each time /var/command_result.txt is open/read, the content is a different random number.

Thanks

答:
Make /var/command_result.txt a named pipe and have a process that opens and writes to it repeatedly? That won't work well if you need a concurrent processes reading the file, but if it is just for sequential testing or something, no problem.

```<code>$ mknod  /tmp/command_result.txt p
$ perl -we '$a=0;
   while(1){
     open(STDOUT,">","/tmp/command_result.txt");
     print "$a\n";
     $a++;
   }' &
[1] 31811
$ head -1 /tmp/command_result.txt
0
$ head -1 /tmp/command_result.txt
810
$ head -1 /tmp/command_result.txt
2431
$ cat /tmp/command_result.txt | head -1
3397
</code>```

As you can see, head reads more than one line before outputting the results. When I ran the head commands very rapidly after one another I wound up with broken pipe errors on the perl side. A trap could fix that.

Body:
Make /var/command_result.txt a named pipe and have a process that opens and writes to it repeatedly? That won't work well if you need a concurrent processes reading the file, but if it is just for sequential testing or something, no problem.

$ mknod  /tmp/command_result.txt p
$ perl -we '$a=0;
   while(1){
     open(STDOUT,">","/tmp/command_result.txt");
     print "$a\n";
     $a++;
   }' &
[1] 31811
$ head -1 /tmp/command_result.txt
0
$ head -1 /tmp/command_result.txt
810
$ head -1 /tmp/command_result.txt
2431
$ cat /tmp/command_result.txt | head -1
3397

As you can see, head reads more than one line before outputting the results. When I ran the head commands very rapidly after one another I wound up with broken pipe errors on the perl side. A trap could fix that.


问:
Returning a 4D array from a function in MATLAB
I am trying to return a 4D array of image data from a function call in MATLAB. I'm not very advanced in MATLAB and I don't know what type of data I have to return from the function. Here is my function:

```<code>function classimg = loadImages(classdir,ext)
    % create array of all images in directory
    neg = dir([classdir ext]);
    % get size of array (to loop through images)
    numFileNeg = max(size(neg));
    % create a 4D array to store our images
    classimg = zeros(51,51,3,numFileNeg);
    % loop through directory
    for i=1:numFileNeg
        classimg(:,:,:,i) = imread([myDir neg(i).name]);
    end
end
</code>```

Here is the function call:

```<code>negativeImgs = loadImages("C:\Users\example\Documents\TrainingImages\negatives\","*.jpg");
</code>```

I cannot find any online documentation for the return type? Does anyone know what this would be? classimg is populated correctly so the code inner works.

答:
As Mike correctly points out, since you initialize classimg using zeros, and the default data type is double, your image data will be converted to double from whatever data type imread returns (often uint8).

If you would like classimg to be the same data type as your images (which I'm assuming all have the same type), you can load one image, get its class, and initialize classimg with that specific class. Here's how you could rewrite your function:

```<code>function classimg = loadImages(classdir, ext)
  neg = dir(fullfile(classdir, ext));
  numFileNeg = numel(neg);
  tempImage = imread(fullfile(classdir, neg(1).name));
  classimg = zeros(51, 51, 3, numFileNeg, class(tempImage));
  classimg(:, :, :, 1) = tempImage;
  for i = 2:numFileNeg
    classimg(:, :, :, i) = imread(fullfile(classdir, neg(i).name));
  end
end
</code>```

Note that I made a couple of other changes. I used fullfile instead of concatenation of the directory and file names, since it handles any issues with file separators for you. I also used numel to get the number of files as Justin suggested in a comment.

Body:
I am trying to return a 4D array of image data from a function call in MATLAB. I'm not very advanced in MATLAB and I don't know what type of data I have to return from the function. Here is my function:

function classimg = loadImages(classdir,ext)
    % create array of all images in directory
    neg = dir([classdir ext]);
    % get size of array (to loop through images)
    numFileNeg = max(size(neg));
    % create a 4D array to store our images
    classimg = zeros(51,51,3,numFileNeg);
    % loop through directory
    for i=1:numFileNeg
        classimg(:,:,:,i) = imread([myDir neg(i).name]);
    end
end

Here is the function call:

negativeImgs = loadImages("C:\Users\example\Documents\TrainingImages\negatives\","*.jpg");

I cannot find any online documentation for the return type? Does anyone know what this would be? classimg is populated correctly so the code inner works.

Body:
As Mike correctly points out, since you initialize classimg using zeros, and the default data type is double, your image data will be converted to double from whatever data type imread returns (often uint8).

If you would like classimg to be the same data type as your images (which I'm assuming all have the same type), you can load one image, get its class, and initialize classimg with that specific class. Here's how you could rewrite your function:

function classimg = loadImages(classdir, ext)
  neg = dir(fullfile(classdir, ext));
  numFileNeg = numel(neg);
  tempImage = imread(fullfile(classdir, neg(1).name));
  classimg = zeros(51, 51, 3, numFileNeg, class(tempImage));
  classimg(:, :, :, 1) = tempImage;
  for i = 2:numFileNeg
    classimg(:, :, :, i) = imread(fullfile(classdir, neg(i).name));
  end
end

Note that I made a couple of other changes. I used fullfile instead of concatenation of the directory and file names, since it handles any issues with file separators for you. I also used numel to get the number of files as Justin suggested in a comment.


问:
Openpyxl charts - data series from random unconnected cells possible?
I'm currently experimenting with the python module openpyxl, trying to automate some tasks at work and generate spreadsheets automatically. For one of the required sheets I need to generate a scatter chart from tabulated data. However, the scatter chart should consist from multiple lines connecting two points each, so each of the individual x/y series in the scatter chart should connect two points only.

Generally I found from the openpyxl documentation that scatter charts are generated like in this small example:

```<code>from openpyxl import Workbook
from openpyxl.chart import (
    ScatterChart,
    Reference,
    Series,
)

wb = Workbook()
ws = wb.active

rows = [
    ['Size', 'Batch 1', 'Batch 2'],
    [2, 40, 30],
    [3, 40, 25],
    [4, 50, 30],
    [5, 30, 25],
    [6, 25, 35],
    [7, 20, 40],
]

for row in rows:
    ws.append(row)

chart = ScatterChart()
chart.title = "Scatter Chart"
chart.style = 13
chart.x_axis.title = 'Size'
chart.y_axis.title = 'Percentage'

xvalues = Reference(ws, min_col=1, min_row=2, max_row=7)
for i in range(2, 4):
    values = Reference(ws, min_col=i, min_row=1, max_row=7)
    series = Series(values, xvalues, title_from_data=True)
    chart.series.append(series)

ws.add_chart(chart, "A10")

wb.save("scatter.xlsx")
</code>```

However, the x (and y) coordinates of the two points I would like to connect in the scatter points are not located in adjacent cells.
So when I import the data series manually in excel by holding 'ctrl' and select two cells I get something like this:

'Sheet!$A$4;Sheet!$A$6'

instead of

'Sheet!$A$4:$A$6'

when dragging the cursor to select a range of cells.

For only two individual not-adjacent cells this means that I do not have a clear min_row/min_col/max_row etc.. but only a list of cell pairs (for both x and y). Is there a way create a data series in openpyxl as a list of cells instead of a connected/adjacent range?

Help would be much appreciated! :)

答:
Are you sure this doesn't work?
I've modified the example for a situation like yours and it seems to work for me:

```<code>from openpyxl import Workbook
from openpyxl.chart import (
    ScatterChart,
    Reference,
    Series,
)

wb = Workbook()
ws = wb.active

rows = [
    ['Size'],
    [2, 'Batch 1', 'Batch 2'],
    [3, 40, 30],
    [4, 40, 25],
    [5, 50, 30],
    [6, 30, 25],
    [7, 25, 35],
    [None, 20, 40],
]

for row in rows:
    ws.append(row)

chart = ScatterChart()
chart.title = "Scatter Chart"
chart.style = 13
chart.x_axis.title = 'Size'
chart.y_axis.title = 'Percentage'

xvalues = Reference(ws, min_col=1, min_row=2, max_row=7)
for i in range(2, 4):
    values = Reference(ws, min_col=i, min_row=2, max_row=8)
    series = Series(values, xvalues, title_from_data=True)
    chart.series.append(series)

ws.add_chart(chart, "A10")

wb.save("scatter.xlsx")
</code>```

Result:

Body:
I'm currently experimenting with the python module openpyxl, trying to automate some tasks at work and generate spreadsheets automatically. For one of the required sheets I need to generate a scatter chart from tabulated data. However, the scatter chart should consist from multiple lines connecting two points each, so each of the individual x/y series in the scatter chart should connect two points only.

Generally I found from the openpyxl documentation that scatter charts are generated like in this small example:

from openpyxl import Workbook
from openpyxl.chart import (
    ScatterChart,
    Reference,
    Series,
)

wb = Workbook()
ws = wb.active

rows = [
    ['Size', 'Batch 1', 'Batch 2'],
    [2, 40, 30],
    [3, 40, 25],
    [4, 50, 30],
    [5, 30, 25],
    [6, 25, 35],
    [7, 20, 40],
]

for row in rows:
    ws.append(row)

chart = ScatterChart()
chart.title = "Scatter Chart"
chart.style = 13
chart.x_axis.title = 'Size'
chart.y_axis.title = 'Percentage'

xvalues = Reference(ws, min_col=1, min_row=2, max_row=7)
for i in range(2, 4):
    values = Reference(ws, min_col=i, min_row=1, max_row=7)
    series = Series(values, xvalues, title_from_data=True)
    chart.series.append(series)

ws.add_chart(chart, "A10")

wb.save("scatter.xlsx")

However, the x (and y) coordinates of the two points I would like to connect in the scatter points are not located in adjacent cells.
So when I import the data series manually in excel by holding 'ctrl' and select two cells I get something like this:

'Sheet!$A$4;Sheet!$A$6'

instead of

'Sheet!$A$4:$A$6'

when dragging the cursor to select a range of cells.

For only two individual not-adjacent cells this means that I do not have a clear min_row/min_col/max_row etc.. but only a list of cell pairs (for both x and y). Is there a way create a data series in openpyxl as a list of cells instead of a connected/adjacent range?

Help would be much appreciated! :)

Body:
Are you sure this doesn't work?
I've modified the example for a situation like yours and it seems to work for me:

from openpyxl import Workbook
from openpyxl.chart import (
    ScatterChart,
    Reference,
    Series,
)

wb = Workbook()
ws = wb.active

rows = [
    ['Size'],
    [2, 'Batch 1', 'Batch 2'],
    [3, 40, 30],
    [4, 40, 25],
    [5, 50, 30],
    [6, 30, 25],
    [7, 25, 35],
    [None, 20, 40],
]

for row in rows:
    ws.append(row)

chart = ScatterChart()
chart.title = "Scatter Chart"
chart.style = 13
chart.x_axis.title = 'Size'
chart.y_axis.title = 'Percentage'

xvalues = Reference(ws, min_col=1, min_row=2, max_row=7)
for i in range(2, 4):
    values = Reference(ws, min_col=i, min_row=2, max_row=8)
    series = Series(values, xvalues, title_from_data=True)
    chart.series.append(series)

ws.add_chart(chart, "A10")

wb.save("scatter.xlsx")

Result:


问:
How to find mean for subset using R?
Using the pre-installed dataset in R, mtcars, I'm trying to find the mean of the "mpg" variable for only Mercedes cars. I am new to R and learning on my own. I've figured out the average for mpg of all cars using the following:

read.csv ("mtcars.csv")
mean(mtcars$mpg)

I thought of using something like a GROUP BY, to group only the 'Mercedes cars, but can't seem to figure it out. I'm sure it's really simple so I'm a little frustrated I'm not seeing what to do here next....

This is what the file looks like: https://gist.github.com/seankross/a412dfbd88b3db70b74b

答:
You can do this data.table way too. Use this code:-

```<code>library(data.table)

dt <- mtcars
dt <- setDT(dt, keep.rownames = T)
dt <- dt[, merc := grepl("Merc", rn)]
dt <- dt[, merc := ifelse(merc == T, 1L, 0L)]
dt <- dt[merc == 1, merc_mean := mean(mpg), by = merc]
</code>```

merc_mean column will have mean for all the Merc cars in their records.

Title: How to find mean for subset using R?

Body:
You can do this data.table way too. Use this code:-

library(data.table)

dt <- mtcars
dt <- setDT(dt, keep.rownames = T)
dt <- dt[, merc := grepl("Merc", rn)]
dt <- dt[, merc := ifelse(merc == T, 1L, 0L)]
dt <- dt[merc == 1, merc_mean := mean(mpg), by = merc]

merc_mean column will have mean for all the Merc cars in their records.


问:
Setting up buttons in SKScene
I'm discovering that UIButtons don't work very well with SKScene, So I'm attempting to subclass SKNode to make a button in SpriteKit.

The way I would like it to work is that if I initialize a button in SKScene and enable touch events, then the button will call a method in my SKScene when it is pressed.

I'd appreciate any advice that would lead me to finding the solution to this problem. Thanks.

答: I wasn't convinced of any of the above options, so based on the latest Swift4 I created my own solution.</p>

Title: Setting up buttons in SKScene


问:
CSS media query for whether a physical keyboard is attached
Suppose I have a site with keyboard shortcuts, where I want to display said keyboard shortcuts visually as part of whatever element they apply to.

On a touch interface, especially a phone, I don't want to bother because:

nobody would use a soft-keyboard this way even if they could

the visual display of the keyboard shortcut takes up valuable real-estate

it's perhaps confusing, or at least inelegant, to display keyboard shortcuts in a keyboardless context

However, the media query documentation doesn't seem to mention anything about this.

It's 2016, is this still impossible?

答:
Unfortunately there is no query in Media Queries 4 to identify the existence of a keyboard.
There are other new queries though that might be helpful.

In my own application I'm assuming that a keyboard exists when there is a mouse or a touchpad as primary input. You can query for that with

@media (hover: hover) and (pointer: fine) { ... }

This query would go false for devices with a touchscreen, stylus devices and also exotic devices like camera input.

Note that with this query you're querying for primary input devices. You can query all input devices with
any-hover and any-pointer.

Also note that as of date, the adoption for MQ4 is 81% of all browsers, but no Firefox: https://caniuse.com/#feat=css-media-interaction


问:
Only run script if not Internet Explorer
How would I go about running a script in every browser except for Internet Explorer?

I'm using queryloader2 on my site, and (for whatever reason) it takes around a minute to load in IE9, I'm assuming the same or worse in older versions of IE. In any other browser, it's just a few seconds. Due to this, I'd like to just not have the script run at all in any version of IE (it doesn't truly hurt the functionality of the site).

答:
The conditional comments in all the other answers (at the time of this posting) are incorrect, and will be interpreted as either (invalid) HTML or completely ignored as an HTML comment in non-IE browsers.

It is important to understand that as far as any browser other than IE is concerned (and even newer versions of IE), the "conditional HTML comment" is just a comment. In other words, something like the upvoted answer's suggestion:

```<code><!--[if !IE]>
    <script src="myScript.js" type="text/javascript"></script>
<![endif]-->
</code>```

Is, as far as anything other than IE is concerned, just one long comment, starting at the  on line 3, just like any other HTML comment.

To get a chunk of HTML to be ignored by IE, you have to take advantage of the fact that HTML comments do not support nesting, i.e.  something --> is a comment that ends at the first --> and not the second, meaning something --> will be parsed as HTML and not considered part of the comment.

So what we can do is use something like this instead:

```<code><!--[if !IE]-->
    <script type="text/javascript" src="script.js"></script>
<!--<![endif]-->
</code>```

Here, non-IE browsers will see two separate comments (on the 1st and 3rd lines, respectively) and regular HTML in the middle. But a browser parsing these tags will see a comment starting on the first line, then ignore everything until encountering <![endif]--> on the 3rd line. This gives us a block of code that will be executed by non-IE/modern browsers, but will be ignored by old versions of IE supporting conditional HTML.

Body:
The conditional comments in all the other answers (at the time of this posting) are incorrect, and will be interpreted as either (invalid) HTML or completely ignored as an HTML comment in non-IE browsers.

It is important to understand that as far as any browser other than IE is concerned (and even newer versions of IE), the "conditional HTML comment" is just a comment. In other words, something like the upvoted answer's suggestion:

<!--[if !IE]>
    <script src="myScript.js" type="text/javascript"></script>
<![endif]-->

Is, as far as anything other than IE is concerned, just one long comment, starting at the <!-- on line 1 and ending at the --> on line 3, just like any other HTML comment.

To get a chunk of HTML to be ignored by IE, you have to take advantage of the fact that HTML comments do not support nesting, i.e. <!-- <!-- --> something --> is a comment that ends at the first --> and not the second, meaning something --> will be parsed as HTML and not considered part of the comment.

So what we can do is use something like this instead:

<!--[if !IE]-->
    <script type="text/javascript" src="script.js"></script>
<!--<![endif]-->

Here, non-IE browsers will see two separate comments (on the 1st and 3rd lines, respectively) and regular HTML in the middle. But a browser parsing these tags will see a comment starting on the first line, then ignore everything until encountering <![endif]--> on the 3rd line. This gives us a block of code that will be executed by non-IE/modern browsers, but will be ignored by old versions of IE supporting conditional HTML.


问:
HTML Rmarkdown Report Changing Plots
When I go line by line through my code, I get the following plot:

But then when I render rmarkdown to HTML report, the plot looks like this:

I am unable to give reproducible code to create the plots as the code is property of my company. But they are created using three functions, the first adds the circle points, the second adds a layer for the the star points, and the final adds the black line.

Somehow, when rmarkdown is rendering the report, the first layer of the plot is condensed to the bottom.

The chunk options are set to:

{r, echo = FALSE, message = FALSE, results = "asis"}

答:
Following up on my comment, I think it's likely that somehow the data in the circles data frame is being converted to factor class. I don't know why it's happening with rmarkdown compilation and not interactively (assuming you're running the rmarkdown code chunks interactively, rather than a separate script containing what is believed to be the same code). In the absence of additional inspiration, we'll need to see code and data to answer that question. For now, here's an example that produces output analogous to your problem graph:

Set up two data frames using the built-in mtcars data:

```<code>data(mtcars)
dat1 = mtcars[1:10,]
dat2 = mtcars[11:20, ]

# Convert the `mpg` and `wt` columns to factor in `dat1` only:
dat1$mpg = factor(dat1$mpg)
dat1$wt = factor(dat1$wt)

# Increase the values of dat2$wt so they'll plot to the right of the values in dat1$wt
dat2$wt = dat2$wt * 10
</code>```

Now for the plot: The plot looks the way it does because the values in dat1 are treated as categorical. So the axis labels are equal to the values of the points, but the locations (the x-y coordinates) where they are plotted are equal to the integers 1 through n where n is the number of points.

The continuous values in dat2 are plotted at locations equal to their actual values (i.e., at their "correct" locations) on the same scale, but without any tick marks.

```<code>ggplot() +
  geom_point(data=dat1, aes(wt, mpg)) +
  geom_point(data=dat2, aes(wt, mpg)) +
  theme_classic()
</code>```

Title: HTML Rmarkdown Report Changing Plots

Body:
Following up on my comment, I think it's likely that somehow the data in the circles data frame is being converted to factor class. I don't know why it's happening with rmarkdown compilation and not interactively (assuming you're running the rmarkdown code chunks interactively, rather than a separate script containing what is believed to be the same code). In the absence of additional inspiration, we'll need to see code and data to answer that question. For now, here's an example that produces output analogous to your problem graph:

Set up two data frames using the built-in mtcars data:

data(mtcars)
dat1 = mtcars[1:10,]
dat2 = mtcars[11:20, ]

# Convert the `mpg` and `wt` columns to factor in `dat1` only:
dat1$mpg = factor(dat1$mpg)
dat1$wt = factor(dat1$wt)

# Increase the values of dat2$wt so they'll plot to the right of the values in dat1$wt
dat2$wt = dat2$wt * 10

Now for the plot: The plot looks the way it does because the values in dat1 are treated as categorical. So the axis labels are equal to the values of the points, but the locations (the x-y coordinates) where they are plotted are equal to the integers 1 through n where n is the number of points.

The continuous values in dat2 are plotted at locations equal to their actual values (i.e., at their "correct" locations) on the same scale, but without any tick marks.

ggplot() +
  geom_point(data=dat1, aes(wt, mpg)) +
  geom_point(data=dat2, aes(wt, mpg)) +
  theme_classic()


问:
load different js files for different pages or load together?
I have 3 pages of site.

Page 1: 19 kb of JS

  Page 2: 26 kb of JS

  Page 3: 10 kb of JS

  Total : 55 kb of JS

These javascript files are non repeating, means the JS needed on page 1 is not needed on page 2 and I have expiry headers set 1 month.

Still I would like to know what will be best way to load these files, should I load separate file for each page or I load these all together?

答: I'd mash them all together in one JS file, minify that with Google's Closure Compiler set on "advanced optimizations", and load it once with a bunch of cache directives. If you do use the Closure Compiler set on advanced, you'll have to make sure there is no inline JavaScript in your HTML files (which is generally not a good practice anyway), because the function and variable names (even the global functions and variable names) won't be the same afterward.</p>


问:
Script does not exist at specified location
"Script does not exist at specified location: /opt/codedeploy-agent/deployment-root/76b33ccc-594b-4d58-a1b8-e40d054c64b7/d-AVYMCK28I/deployment-archive/scripts/Applicationstoptest.sh"

This is the error I am getting can any one please help me how to resolve this issue

答:
I found my answer here: https://stackoverflow.com/a/27925591/1056283

The application stop hook uses a previous deployment to look for the script to invoke, so if the structure of your deploy package changes, there may not be a script to call at the specified location yet. The deploy fails and the script never arrives at the new location. Look in the linked answer for the steps to resolve it.