问:
I Cant select from spinner
after i click on the item in the spinner  nothing selected.

```<code>    public  void getSpinnerItems(){

    StringRequest stringRequest = new StringRequest(Request.Method.POST,ToolsUtils.STOP_CODE_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {

                    try {

                        JSONArray jsonArray = new JSONArray(response);
                        JSONObject jsonObject=new JSONObject();
                        for(int i=0;i<jsonArray.length();i++) {
                             jsonObject=jsonArray.getJSONObject(i);
                            String s=jsonObject.getString("stopDesc");
                            eque_array.add(s);
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    //displaying the error in toast if occurrs
                    error.printStackTrace();
                    Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });
</code>```

//creating a request queue
        RequestQueue requestQueue = Volley.newRequestQueue(this);

//adding the string request to request queue
        requestQueue.add(stringRequest);

//fill the spinner

```<code>    ArrayAdapter<String> arr=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item,eque_array);
    spinner.setAdapter(arr);
}
</code>```

I use this listener to return the selected item

```<code> spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

         String   selected_item =spinner.getItemAtPosition( position).toString();
            ((TextView) view).setTextColor(Color.RED);
           validator.setText(spinner);
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
            stop_code="nothing" ;
            validator.setText(spinner );
        }
    });
</code>```

I click on the itme but it not return any thing.

答:
You can try this
first create spinner in your layout xml like

```<code>                    <Spinner
                        android:id="@+id/spinner"
                        android:layout_width="fill_parent"
                        android:layout_height="48dp"
                        android:background="@drawable/border"
                        android:dropDownVerticalOffset="50dp"
                        android:gravity="center_vertical"
                        android:padding="3dp"
                        android:prompt="@string/country_prompt"
                        android:spinnerMode="dropdown" />

create a spinner_items file in layout folder like

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    style="?android:attr/spinnerItemStyle"
    android:singleLine="true"
    android:layout_width="match_parent"
    android:layout_height="48dp"
    android:layout_gravity="center"
    android:gravity="center"
    android:ellipsize="marquee"
    android:background="@drawable/spinner_item_divider"
    android:textAlignment="inherit"/>
</code>```

and call this method from after getting response and do changes according to your requirement

```<code>private void intializeAdapter(ArrayList<String>arrList) {

        final ArrayAdapter<String> spinnerArrayAdapter = new
         ArrayAdapter<String>(this, R.layout.spinner_items, arrList) {
            @Override
            public boolean isEnabled(int position) {
                if (position == 0) {
                    return false;
                } else {

                    return true;
                }
            }

            @Override
            public View getDropDownView(int position, View convertView, ViewGroup parent) {
                View view = super.getDropDownView(position, convertView, parent);
                 tv = (TextView) view;
                TextView tv1 = (TextView) view;
                if (position == 0) {
                    // Set the hint text color gray
                    tv.setTextColor(Color.GRAY);

                } else {
                    tv.setTextColor(Color.BLACK);

                   // tv.setText(numberValue);

                    // tv.setBackgroundColor(Color.BLACK);
                }
                return view;
            }
        };
        spinnerArrayAdapter.setDropDownViewResource(R.layout.spinner_items);
        spinner.setAdapter(spinnerArrayAdapter);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String selectedItemText = (String) parent.getItemAtPosition(position);
                if (position > 0) {
                    result = selectedItemText;
                    textView=(TextView) view;
                    numberValue=selectedItemText;
                    if(numberValue.equals("other")){
                         openAlertDialog();
                    }else if(numberValue.equals("Andet")){
                        openAlertDialog();
                    }

                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

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

Title: I Cant select from spinner

Body:
after i click on the item in the spinner  nothing selected.

    public  void getSpinnerItems(){

    StringRequest stringRequest = new StringRequest(Request.Method.POST,ToolsUtils.STOP_CODE_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {

                    try {

                        JSONArray jsonArray = new JSONArray(response);
                        JSONObject jsonObject=new JSONObject();
                        for(int i=0;i<jsonArray.length();i++) {
                             jsonObject=jsonArray.getJSONObject(i);
                            String s=jsonObject.getString("stopDesc");
                            eque_array.add(s);
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    //displaying the error in toast if occurrs
                    error.printStackTrace();
                    Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });

//creating a request queue
        RequestQueue requestQueue = Volley.newRequestQueue(this);

//adding the string request to request queue
        requestQueue.add(stringRequest);

//fill the spinner

    ArrayAdapter<String> arr=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item,eque_array);
    spinner.setAdapter(arr);
}

I use this listener to return the selected item

 spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

         String   selected_item =spinner.getItemAtPosition( position).toString();
            ((TextView) view).setTextColor(Color.RED);
           validator.setText(spinner);
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
            stop_code="nothing" ;
            validator.setText(spinner );
        }
    });

I click on the itme but it not return any thing.

Body:
You can try this
first create spinner in your layout xml like

                    <Spinner
                        android:id="@+id/spinner"
                        android:layout_width="fill_parent"
                        android:layout_height="48dp"
                        android:background="@drawable/border"
                        android:dropDownVerticalOffset="50dp"
                        android:gravity="center_vertical"
                        android:padding="3dp"
                        android:prompt="@string/country_prompt"
                        android:spinnerMode="dropdown" />

create a spinner_items file in layout folder like

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    style="?android:attr/spinnerItemStyle"
    android:singleLine="true"
    android:layout_width="match_parent"
    android:layout_height="48dp"
    android:layout_gravity="center"
    android:gravity="center"
    android:ellipsize="marquee"
    android:background="@drawable/spinner_item_divider"
    android:textAlignment="inherit"/>

and call this method from after getting response and do changes according to your requirement

private void intializeAdapter(ArrayList<String>arrList) {

        final ArrayAdapter<String> spinnerArrayAdapter = new
         ArrayAdapter<String>(this, R.layout.spinner_items, arrList) {
            @Override
            public boolean isEnabled(int position) {
                if (position == 0) {
                    return false;
                } else {

                    return true;
                }
            }

            @Override
            public View getDropDownView(int position, View convertView, ViewGroup parent) {
                View view = super.getDropDownView(position, convertView, parent);
                 tv = (TextView) view;
                TextView tv1 = (TextView) view;
                if (position == 0) {
                    // Set the hint text color gray
                    tv.setTextColor(Color.GRAY);

                } else {
                    tv.setTextColor(Color.BLACK);

                   // tv.setText(numberValue);

                    // tv.setBackgroundColor(Color.BLACK);
                }
                return view;
            }
        };
        spinnerArrayAdapter.setDropDownViewResource(R.layout.spinner_items);
        spinner.setAdapter(spinnerArrayAdapter);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String selectedItemText = (String) parent.getItemAtPosition(position);
                if (position > 0) {
                    result = selectedItemText;
                    textView=(TextView) view;
                    numberValue=selectedItemText;
                    if(numberValue.equals("other")){
                         openAlertDialog();
                    }else if(numberValue.equals("Andet")){
                        openAlertDialog();
                    }

                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }


来源: stackexchange

问:
Android gradle sync issue
This app was running perfectly OK without any issue. Suddenly i saw this gradle sync problems.I'm really stuck and need help. What to do now? I've uninstalled and reinstalled android support repository from SDK manager.

```<code>C:\Users\DELL\AndroidStudioProjects\Prokriti\app\build.gradle
    Error:Error:Failed to resolve: com.android.support:support-annotations:27.0.1
Install Repository and sync project
    Error:Error:Failed to resolve: com.android.support:appcompat-v7:27.0.1
Install Repository and sync project
    Error:Error:Failed to resolve: com.android.support:customtabs:27.0.1
Install Repository and sync project
    Error:Error:Failed to resolve: com.android.support:cardview-v7:27.0.1
Install Repository and sync project
    Error:Error:Failed to resolve: com.android.support:support-v4:27.0.1
Install Repository and sync project
    Error:Error:Failed to resolve: com.android.support:support-core-utils:27.0.1
Install Repository and sync project
</code>```

build.gradle  (app)

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

android {
    compileSdkVersion 25
    buildToolsVersion "26.0.1"
    defaultConfig {
        applicationId "com.avtro.prokriti.prokriti"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true

    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:cardview-v7:25.3.1'
    compile 'com.android.support:design:25.3.1'
    compile 'com.android.support:support-core-utils:25.3.1'
    compile 'com.android.support:support-annotations:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.google.android.gms:play-services-auth:11.0.4'
    compile 'com.google.firebase:firebase-core:11.0.2'
    compile 'com.google.firebase:firebase-messaging:11.0.2'
    compile 'com.google.firebase:firebase-database:11.0.2'
    compile 'com.google.firebase:firebase-auth:11.0.2'
    compile 'com.google.firebase:firebase-ads:11.0.2'
    compile 'com.afollestad.material-dialogs:core:0.9.4.5'
    compile 'com.wang.avi:library:2.1.3'
    compile 'com.google.android.gms:play-services-ads:11.0.4'
    compile 'de.hdodenhof:circleimageview:2.1.0'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.survivingwithandroid:weatherlib:1.6.0'
    compile 'com.amitshekhar.android:android-networking:1.0.0'
    compile 'com.android.support:multidex:1.0.1'
    compile 'com.squareup.okhttp:okhttp:2.0.0'
    compile 'com.facebook.android:facebook-android-sdk:[4,5)'
    compile 'com.google.firebase:firebase-storage:11.0.2'
    androidTestCompile 'junit:junit:4.12'
    compile 'javax.inject:javax.inject:1'
    compile 'com.android.support:support-v4:25.3.1'
    compile 'com.github.bumptech.glide:glide:3.8.0'
}
apply plugin: 'com.google.gms.google-services'
</code>```

build.gradle  (project)

```<code>buildscript {
    repositories {
        jcenter()
    }
dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'
        classpath 'com.google.gms:google-services:3.0.0'
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

i didnt update android studio or gradle. Android support repository is installed.

答:
'com.facebook.android:facebook-android-sdk:[4,5)'
or

'com.facebook.android:facebook-android-sdk:4.+'

above replace with below

'com.facebook.android:facebook-android-sdk:4.26.0'

ContentLicense: CC BY-SA 3.0

Title: Android gradle sync issue

Body:
This app was running perfectly OK without any issue. Suddenly i saw this gradle sync problems.I'm really stuck and need help. What to do now? I've uninstalled and reinstalled android support repository from SDK manager.

C:\Users\DELL\AndroidStudioProjects\Prokriti\app\build.gradle
    Error:Error:Failed to resolve: com.android.support:support-annotations:27.0.1
Install Repository and sync project
    Error:Error:Failed to resolve: com.android.support:appcompat-v7:27.0.1
Install Repository and sync project
    Error:Error:Failed to resolve: com.android.support:customtabs:27.0.1
Install Repository and sync project
    Error:Error:Failed to resolve: com.android.support:cardview-v7:27.0.1
Install Repository and sync project
    Error:Error:Failed to resolve: com.android.support:support-v4:27.0.1
Install Repository and sync project
    Error:Error:Failed to resolve: com.android.support:support-core-utils:27.0.1
Install Repository and sync project

build.gradle  (app)

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "26.0.1"
    defaultConfig {
        applicationId "com.avtro.prokriti.prokriti"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true

    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:cardview-v7:25.3.1'
    compile 'com.android.support:design:25.3.1'
    compile 'com.android.support:support-core-utils:25.3.1'
    compile 'com.android.support:support-annotations:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.google.android.gms:play-services-auth:11.0.4'
    compile 'com.google.firebase:firebase-core:11.0.2'
    compile 'com.google.firebase:firebase-messaging:11.0.2'
    compile 'com.google.firebase:firebase-database:11.0.2'
    compile 'com.google.firebase:firebase-auth:11.0.2'
    compile 'com.google.firebase:firebase-ads:11.0.2'
    compile 'com.afollestad.material-dialogs:core:0.9.4.5'
    compile 'com.wang.avi:library:2.1.3'
    compile 'com.google.android.gms:play-services-ads:11.0.4'
    compile 'de.hdodenhof:circleimageview:2.1.0'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.survivingwithandroid:weatherlib:1.6.0'
    compile 'com.amitshekhar.android:android-networking:1.0.0'
    compile 'com.android.support:multidex:1.0.1'
    compile 'com.squareup.okhttp:okhttp:2.0.0'
    compile 'com.facebook.android:facebook-android-sdk:[4,5)'
    compile 'com.google.firebase:firebase-storage:11.0.2'
    androidTestCompile 'junit:junit:4.12'
    compile 'javax.inject:javax.inject:1'
    compile 'com.android.support:support-v4:25.3.1'
    compile 'com.github.bumptech.glide:glide:3.8.0'
}
apply plugin: 'com.google.gms.google-services'

build.gradle  (project)

buildscript {
    repositories {
        jcenter()
    }
dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'
        classpath 'com.google.gms:google-services:3.0.0'
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

i didnt update android studio or gradle. Android support repository is installed.


问:
Angular Material 2 Card Header Buttons set Right
I use the Angular Material 2 and I want in a card-header icon buttons. How can I set the buttons to the right side?

My plan:

Current Website:

I want to set the buttons rop right in the header. How can i do it?
I exlude the category code because there is no problem. In the typescript code is only a for loop to add more cards and a dummy method for click on a card.

.healthy-search {
    width: 100%
}

.healthy-card {
    margin-right: 5px;
    margin-bottom: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="flex-container" fxLayout="row" fxLayout.xs="column" fxLayoutAlign="center center" fxLayoutAlign.xs="start">
  <div class="flex-item" fxFlex="90%" fxFlex.xs="90%">
    <mat-form-field class="healthy-search">
      <textarea matInput placeholder="Suche"></textarea>
    </mat-form-field>
  </div>
</div>
<div class="flex-container" fxLayout="row" fxLayout.xs="column" fxLayoutAlign="center center" fxLayoutAlign.xs="start">
  <div class="flex-item" fxFlex="85%" fxFlex.xs="85%">
    <mat-expansion-panel>

     <!-- Here is the Category -->

     <!--Elements of Category -->

      <div class="flex-container" fxLayoutWrap fxLayout="row" fxLayout.xs="column" fxLayoutAlign="center center" fxLayoutAlign.xs="start">
        <div class="flex-item healthy-card" fxFlex="400px" *ngFor="let number of numbers" (click)="cardClick()">
          <mat-card class="example-card">
            <mat-card-header>
              <mat-card-title>Title {{number}}</mat-card-title>
              <button mat-icon-button fxLayoutAlign="right">
                <mat-icon aria-label="Example icon-button with a heart icon">Edit</mat-icon>
              </button>
              <button mat-icon-button fxLayoutAlign="right">
                <mat-icon aria-label="Example icon-button with a heart icon">Delete</mat-icon>
              </button>
            </mat-card-header>
            <img mat-card-image src="https://material.angular.io/assets/img/examples/shiba2.jpg" alt="Photo of a Shiba Inu">
            <mat-card-content>
              <p>
                The Shiba Inu is the smallest of the six original and distinct spitz breeds of dog from Japan. A small, agile dog that copes
                very well with mountainous terrain, the Shiba Inu was originally bred for hunting.
              </p>
            </mat-card-content>
          </mat-card>
        </div>
      </div>
    </mat-expansion-panel>
  </div>
</div></code>```

Lyror

答:
First take away the fxLayoutAlign="right" from the buttons.
fxLayoutAlign is for containers.

You need to at a div or some other placeholder with fxFlex between the title and the buttons. This will push the buttons to the end.

```<code><md-card-header fxLayout="row">
  <md-card-title >Title </md-card-title>
  <div fxFlex></div>
  <button md-button>Something</button>
</md-card-header>
</code>```

Body:
I use the Angular Material 2 and I want in a card-header icon buttons. How can I set the buttons to the right side?

My plan:

Current Website:

I want to set the buttons rop right in the header. How can i do it?
I exlude the category code because there is no problem. In the typescript code is only a for loop to add more cards and a dummy method for click on a card.

.healthy-search {
    width: 100%
}

.healthy-card {
    margin-right: 5px;
    margin-bottom: 5px;
}

    <mat-form-field class="healthy-search">
      <textarea matInput placeholder="Suche"></textarea>
    </mat-form-field>

    <mat-expansion-panel>

          <mat-card class="example-card">
            <mat-card-header>
              <mat-card-title>Title {{number}}</mat-card-title>
              <button mat-icon-button fxLayoutAlign="right">
                <mat-icon aria-label="Example icon-button with a heart icon">Edit</mat-icon>
              </button>
              <button mat-icon-button fxLayoutAlign="right">
                <mat-icon aria-label="Example icon-button with a heart icon">Delete</mat-icon>
              </button>
            </mat-card-header>

            <mat-card-content>

                The Shiba Inu is the smallest of the six original and distinct spitz breeds of dog from Japan. A small, agile dog that copes
                very well with mountainous terrain, the Shiba Inu was originally bred for hunting.

            </mat-card-content>
          </mat-card>

    </mat-expansion-panel>

Lyror

Body:
First take away the fxLayoutAlign="right" from the buttons.
fxLayoutAlign is for containers.

You need to at a div or some other placeholder with fxFlex between the title and the buttons. This will push the buttons to the end.

<md-card-header fxLayout="row">
  <md-card-title >Title </md-card-title>
  <div fxFlex></div>
  <button md-button>Something</button>
</md-card-header>


问:
Adding a WEB API method ruins my SWAGGER UI
This first method is fine. But when I add the second method the body of the SWAGGER UI is a bunch of html gibberish. And I creating the route the wrong way?

```<code>// GET api/checklist/1288
        [HttpGet("{id}")]
        public async Task<IActionResult> Get(int id)
        {
            var model = _checkListService.Get(id);
            return Ok(model);
        }

    // http://localhost:64783/api/checklist/GetDelinquentItems?id=1288
    [Route("GetDelinquentItems")]
    public async Task<IActionResult> GetDelinquentItems(int id)
    {
        var model = _checkListService.GetDelinquentItems(id);
        return Ok(model);
    }
</code>```

答:
That 'html gibberish' (indeed not the most elegant way to show an error) still contains some useful information. The first line says:

500 internal server error

and in the last three lines you can read:

Ambiguos HTTP method for action...CheckListController.GetDelinquentItems... Actions require explicit HttpMethod binding for Swagger

therefore another

[HttpGet("{id}")]

before the GetDelinquentItems() method should solve the problem.

Body:
This first method is fine. But when I add the second method the body of the SWAGGER UI is a bunch of html gibberish. And I creating the route the wrong way?

// GET api/checklist/1288
        [HttpGet("{id}")]
        public async Task<IActionResult> Get(int id)
        {
            var model = _checkListService.Get(id);
            return Ok(model);
        }

    // http://localhost:64783/api/checklist/GetDelinquentItems?id=1288
    [Route("GetDelinquentItems")]
    public async Task<IActionResult> GetDelinquentItems(int id)
    {
        var model = _checkListService.GetDelinquentItems(id);
        return Ok(model);
    }


问:
Duplicate key in YAML configuaration file
I have the following in YAML:

```<code>key1
  key2: "value"

key1
  key2
    key3: "value2"
</code>```

Get exception duplicate key key1.

```<code>Caused by: org.yaml.snakeyaml.parser.ParserException: while parsing MappingNode
</code>```

Tried various combinations but was unable to parse it correctly.

答:
Your YAML is syntactically invalid, but I am assuming it actually looks like this:

```<code>key1:
  key2: "value"

key1:
  key2:
    key3: "value2"
</code>```

Your error is that key1 is used two times as mapping key in the root node. This is illegal as per YAML spec:

The content of a mapping node is an unordered set of key: value node pairs, with the restriction that each of the keys is unique.

The solution is to make all keys of the same mapping unique:

```<code>key11:
  key2: "value"

key12:
  key2:
    key3: "value2"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have the following in YAML:

key1
  key2: "value"

key1
  key2
    key3: "value2"

Get exception duplicate key key1.

Caused by: org.yaml.snakeyaml.parser.ParserException: while parsing MappingNode

Tried various combinations but was unable to parse it correctly.

Body:
Your YAML is syntactically invalid, but I am assuming it actually looks like this:

key1:
  key2: "value"

key1:
  key2:
    key3: "value2"

Your error is that key1 is used two times as mapping key in the root node. This is illegal as per YAML spec:

The content of a mapping node is an unordered set of key: value node pairs, with the restriction that each of the keys is unique.

The solution is to make all keys of the same mapping unique:

key11:
  key2: "value"

key12:
  key2:
    key3: "value2"


问:
Func to get the property instead of just the value
Is it possible to input an object and a second parameter to a method so that the second parameter can be used (without using strings and reflection) to get the a property of the object and use the property to both read and write the value?

I've written two methods below that I can use but each one has drawbacks. The first DoStuff is typesafe ("good") but it needs three parameters ("bad"). The second needs two parameters (optimal), but it is not typesafe ("bad") as it relies on a string to specify the property. Maybe there is some solution using Expression that I have not thought of?

Background: The usecase is that I want to be able to "extend" the value of any object (in my case I have lists of objects from several object reposites and these objects may have serveral properties containing userids as strings. another repository conatins the users and I want add info about the user to the strings in the previous repositories)

```<code>public class Foo
{
    public string Bar {get; set;}
}

void Main()
{
    var x = new Foo { Bar = "hello" };
    Console.WriteLine(x.Bar); // prints "hello"

    // the second paramter (Func<..>) gets the value, the third parameter Action<...>) sets the value
    DoStuff(x, y => y.Bar, (z, val) => z.Bar = val);
    Console.WriteLine(x.Bar); // prints "hello  goodbye"

    // just one parameter to get the property, but I would like this to be more type safe, preferably a Func
    DoStuff2(x, nameof(x.Bar));
    Console.WriteLine(x.Bar); // prints "hello  goodbye again"
}

public void DoStuff<T>(
    T obj,
    Func<T, string> getProp,
    Action<T, string> setProp)
{
    var x = getProp(obj);
    setProp(obj, x + " goodbye");
}

public void DoStuff2<T>(
    T obj,
    string propName)
{
    var propInfo = typeof(T).GetProperty(propName);
    var currValue = propInfo.GetValue(obj) as string;
    propInfo.SetValue(obj, currValue + " again");
}
</code>```

答:
Well i did something like that awhile ago. here is an example:

```<code> public void SetValue<T, TP>(T obj, Expression<Func<T, TP>> action, TP value) where T : class
 {
      var member = action.Body is UnaryExpression
                 ? ((MemberExpression)((UnaryExpression)action.Body).Operand)
                 : (action.Body is MethodCallExpression
                     ? ((MemberExpression)((MethodCallExpression)action.Body).Object)
                     : (MemberExpression)action.Body);

     var key = member?.Member.Name;
     typeof(T).GetProperty(key).SetValue(obj, value);

 }
</code>```

You call it like this.

```<code>SetValue<User>(x=> x.UserName, "Admin");
</code>```

Body:
Is it possible to input an object and a second parameter to a method so that the second parameter can be used (without using strings and reflection) to get the a property of the object and use the property to both read and write the value?

I've written two methods below that I can use but each one has drawbacks. The first DoStuff is typesafe ("good") but it needs three parameters ("bad"). The second needs two parameters (optimal), but it is not typesafe ("bad") as it relies on a string to specify the property. Maybe there is some solution using Expression that I have not thought of?

Background: The usecase is that I want to be able to "extend" the value of any object (in my case I have lists of objects from several object reposites and these objects may have serveral properties containing userids as strings. another repository conatins the users and I want add info about the user to the strings in the previous repositories)

public class Foo
{
    public string Bar {get; set;}
}

void Main()
{
    var x = new Foo { Bar = "hello" };
    Console.WriteLine(x.Bar); // prints "hello"

    // the second paramter (Func<..>) gets the value, the third parameter Action<...>) sets the value
    DoStuff(x, y => y.Bar, (z, val) => z.Bar = val);
    Console.WriteLine(x.Bar); // prints "hello  goodbye"

    // just one parameter to get the property, but I would like this to be more type safe, preferably a Func
    DoStuff2(x, nameof(x.Bar));
    Console.WriteLine(x.Bar); // prints "hello  goodbye again"
}

public void DoStuff<T>(
    T obj,
    Func<T, string> getProp,
    Action<T, string> setProp)
{
    var x = getProp(obj);
    setProp(obj, x + " goodbye");
}

public void DoStuff2<T>(
    T obj,
    string propName)
{
    var propInfo = typeof(T).GetProperty(propName);
    var currValue = propInfo.GetValue(obj) as string;
    propInfo.SetValue(obj, currValue + " again");
}

Body:
Well i did something like that awhile ago. here is an example:

 public void SetValue<T, TP>(T obj, Expression<Func<T, TP>> action, TP value) where T : class
 {
      var member = action.Body is UnaryExpression
                 ? ((MemberExpression)((UnaryExpression)action.Body).Operand)
                 : (action.Body is MethodCallExpression
                     ? ((MemberExpression)((MethodCallExpression)action.Body).Object)
                     : (MemberExpression)action.Body);

     var key = member?.Member.Name;
     typeof(T).GetProperty(key).SetValue(obj, value);

 }

You call it like this.

SetValue<User>(x=> x.UserName, "Admin");


问:
Q: How to get key value from a HashMap of a ComboBox and save it to the database

I am trying to get the Key value of my HashMap from a ComboBox, but every time I use the variable of my ComboBox it just returns the name of the ComboBox: cmbCourse. I want the code to get the key value and save it into my database.

Here is my insertion code

```<code>String query2 = ("INSERT INTO tblcourseinfo (user_id, course_id, school_id) VALUES (?,?,?)");
            QueryCourses qc = new QueryCourses();
            HashMap<String, Integer> map = qc.hashMap();
            stmt = conn.prepareStatement(query2);
            System.out.println(cmbCourse);
            System.out.println(cmbSchool);
            stmt.setInt(1, key);
            stmt.setObject(2, cmbCourse.getValue());
            stmt.setObject(3, cmbSchool.getValue());
            stmt.executeUpdate();
</code>```

this is how I call the HashMap to populate the ComboBoxes

```<code>public void populateCourse() throws SQLException, ClassNotFoundException {
    QueryCourses qc = new QueryCourses();
    HashMap<String, Integer> map = qc.hashMap();

    cmbCourse.getItems().setAll(map.keySet());
}

public void populateSchool() throws SQLException {
    QuerySchools qs = new QuerySchools();
    HashMap<String, Integer> map = qs.hashMap();

    cmbSchool.getItems().setAll(map.keySet());
}
</code>```

and here is the query to populate it

```<code>public class QueryCourses {
public static ArrayList<Courses> getCourses() throws ClassNotFoundException, SQLException {
    String queryCourses = "SELECT course_id, course_title FROM tblcourses";
    Connection conn = DbConnection.ConnectDB();
    Statement stmt = conn.createStatement();
    ResultSet rs;
    rs = stmt.executeQuery(queryCourses);
    ArrayList<Courses> courseList = new ArrayList<>();
    while (rs.next()) {
        Courses crse = new Courses(rs.getInt("course_id"), rs.getString("course_title"));
        courseList.add(crse);
    }
    return courseList;
}

public HashMap<String, Integer> hashMap() throws SQLException, ClassNotFoundException{
    HashMap<String, Integer> map = new HashMap<>();
    try {
        for (Courses crse : getCourses()) {
            map.put(crse.getCourseTitle(), crse.getCourseId());
        }
    } catch (SQLException ex) {
        Logger.getLogger(NewStudentController.class.getName()).log(Level.SEVERE, null, ex);
    }
    return map;
}
}
</code>```

答:
Focusing on the primary issue

How to get the ID of the selected item

This is most easily solved by not using a HashMap and instead, adding the Course object directly to the ComboBox ObservableList and changing the way that the items are rendered.

In this way, you don't need to worry about providing lookups or other fancy pancy solutions, as all the information you need is stored in the Course object itself.

So, I don't have access to your code, so I had to make a few things up, starting with the Course object...

```<code>public class Course {

    private long id;
    private String title;

    public Course(long id, String title) {
        this.id = id;
        this.title = title;
    }

    public long getId() {
        return id;
    }

    public String getTitle() {
        return title;
    }

    @Override
    public String toString() {
        return "Course{" + "id=" + id + ", title=" + title + '}';
    }

}
</code>```

When that in hand we can create a custom ListCell...

```<code>public class CourseCell extends ListCell<Course> {

    @Override
    protected void updateItem(Course item, boolean empty) {
        super.updateItem(item, empty);
        if (item != null) {
            setText(item.getTitle());
        } else {
            setText(null);
        }
    }
}
</code>```

Then we need to apply the data and renderers together...

```<code>// I can imagine this been loaded from a ResultSet
ObservableList<Course> options = FXCollections.observableArrayList(
                new Course(0, "JavaFX"),
                new Course(1, "Swing"),
                new Course(2, "Objective C"),
                new Course(3, "Swift")
);
ComboBox<Course> comboBox = new ComboBox<Course>(options);
comboBox.setCellFactory(new Callback<ListView<Course>, ListCell<Course>>() {
    @Override
    public ListCell<Course> call(ListView<Course> courses) {
        return new CourseCell();
    }
});
comboBox.setButtonCell(new CourseCell());
</code>```

Then at some point, we need to get the selected value...

```<code>Course course = comboBox.getValue();
if (course != null) {
    System.out.println(course);
    System.out.println(course.getId());
}
</code>```

getValue will now return a Course object, including the title and id, convenient.

Remember, you're dealing with a OO language, where ever possible, maintain the encapsulation of the data, it just makes life so much simpler.

Runnable Example...

This is like only the third JavaFX app I've written, and most of it was gleamed from tutorials, other answers and some blogs, so forgive me any glaring mistakes, I tried to focus on the ListCell implementation

```<code>import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.HPos;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
import javafx.util.Callback;

public class Test extends Application {

    @Override
    public void start(Stage primaryStage) {

        GridPane gridPane = new GridPane();

        ObservableList<Course> options = FXCollections.observableArrayList(
                        new Course(0, "JavaFX"),
                        new Course(1, "Swing"),
                        new Course(2, "Objective C"),
                        new Course(3, "Swift")
        );
        ComboBox<Course> comboBox = new ComboBox<Course>(options);
        comboBox.setCellFactory(new Callback<ListView<Course>, ListCell<Course>>() {
            @Override
            public ListCell<Course> call(ListView<Course> courses) {
                return new CourseCell();
            }
        });
        comboBox.setButtonCell(new CourseCell());

        Button btn = new Button();
        btn.setText("Use");
        btn.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent event) {
                Course course = comboBox.getValue();
                if (course != null) {
                    System.out.println(course);
                    System.out.println(course.getId());
                }
            }
        });

        GridPane.setHalignment(comboBox, HPos.CENTER);
        GridPane.setHalignment(btn, HPos.CENTER);

        gridPane.setAlignment(Pos.CENTER);

        gridPane.add(comboBox, 0, 0);
        gridPane.add(btn, 0, 1);

        Scene scene = new Scene(gridPane, 300, 250);

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }

    public class CourseCell extends ListCell<Course> {

        @Override
        protected void updateItem(Course item, boolean empty) {
            super.updateItem(item, empty);
            if (item != null) {
                setText(item.getTitle());
            } else {
                setText(null);
            }
        }
    }

    public class Course {

        private long id;
        private String title;

        public Course(long id, String title) {
            this.id = id;
            this.title = title;
        }

        public long getId() {
            return id;
        }

        public String getTitle() {
            return title;
        }

        @Override
        public String toString() {
            return "Course{" + "id=" + id + ", title=" + title + '}';
        }

    }

}
</code>```

Body:
I am trying to get the Key value of my HashMap from a ComboBox, but every time I use the variable of my ComboBox it just returns the name of the ComboBox: cmbCourse. I want the code to get the key value and save it into my database.

Here is my insertion code

String query2 = ("INSERT INTO tblcourseinfo (user_id, course_id, school_id) VALUES (?,?,?)");
            QueryCourses qc = new QueryCourses();
            HashMap<String, Integer> map = qc.hashMap();
            stmt = conn.prepareStatement(query2);
            System.out.println(cmbCourse);
            System.out.println(cmbSchool);
            stmt.setInt(1, key);
            stmt.setObject(2, cmbCourse.getValue());
            stmt.setObject(3, cmbSchool.getValue());
            stmt.executeUpdate();

this is how I call the HashMap to populate the ComboBoxes

public void populateCourse() throws SQLException, ClassNotFoundException {
    QueryCourses qc = new QueryCourses();
    HashMap<String, Integer> map = qc.hashMap();

    cmbCourse.getItems().setAll(map.keySet());
}

public void populateSchool() throws SQLException {
    QuerySchools qs = new QuerySchools();
    HashMap<String, Integer> map = qs.hashMap();

    cmbSchool.getItems().setAll(map.keySet());
}

and here is the query to populate it

public class QueryCourses {
public static ArrayList<Courses> getCourses() throws ClassNotFoundException, SQLException {
    String queryCourses = "SELECT course_id, course_title FROM tblcourses";
    Connection conn = DbConnection.ConnectDB();
    Statement stmt = conn.createStatement();
    ResultSet rs;
    rs = stmt.executeQuery(queryCourses);
    ArrayList<Courses> courseList = new ArrayList<>();
    while (rs.next()) {
        Courses crse = new Courses(rs.getInt("course_id"), rs.getString("course_title"));
        courseList.add(crse);
    }
    return courseList;
}

public HashMap<String, Integer> hashMap() throws SQLException, ClassNotFoundException{
    HashMap<String, Integer> map = new HashMap<>();
    try {
        for (Courses crse : getCourses()) {
            map.put(crse.getCourseTitle(), crse.getCourseId());
        }
    } catch (SQLException ex) {
        Logger.getLogger(NewStudentController.class.getName()).log(Level.SEVERE, null, ex);
    }
    return map;
}
}

Body:
Focusing on the primary issue

How to get the ID of the selected item

This is most easily solved by not using a HashMap and instead, adding the Course object directly to the ComboBox ObservableList and changing the way that the items are rendered.

In this way, you don't need to worry about providing lookups or other fancy pancy solutions, as all the information you need is stored in the Course object itself.

So, I don't have access to your code, so I had to make a few things up, starting with the Course object...

public class Course {

    private long id;
    private String title;

    public Course(long id, String title) {
        this.id = id;
        this.title = title;
    }

    public long getId() {
        return id;
    }

    public String getTitle() {
        return title;
    }

    @Override
    public String toString() {
        return "Course{" + "id=" + id + ", title=" + title + '}';
    }

}

When that in hand we can create a custom ListCell...

public class CourseCell extends ListCell<Course> {

    @Override
    protected void updateItem(Course item, boolean empty) {
        super.updateItem(item, empty);
        if (item != null) {
            setText(item.getTitle());
        } else {
            setText(null);
        }
    }
}

Then we need to apply the data and renderers together...

// I can imagine this been loaded from a ResultSet
ObservableList<Course> options = FXCollections.observableArrayList(
                new Course(0, "JavaFX"),
                new Course(1, "Swing"),
                new Course(2, "Objective C"),
                new Course(3, "Swift")
);
ComboBox<Course> comboBox = new ComboBox<Course>(options);
comboBox.setCellFactory(new Callback<ListView<Course>, ListCell<Course>>() {
    @Override
    public ListCell<Course> call(ListView<Course> courses) {
        return new CourseCell();
    }
});
comboBox.setButtonCell(new CourseCell());

Then at some point, we need to get the selected value...

Course course = comboBox.getValue();
if (course != null) {
    System.out.println(course);
    System.out.println(course.getId());
}

getValue will now return a Course object, including the title and id, convenient.

Remember, you're dealing with a OO language, where ever possible, maintain the encapsulation of the data, it just makes life so much simpler.

Runnable Example...

This is like only the third JavaFX app I've written, and most of it was gleamed from tutorials, other answers and some blogs, so forgive me any glaring mistakes, I tried to focus on the ListCell implementation

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.HPos;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
import javafx.util.Callback;

public class Test extends Application {

    @Override
    public void start(Stage primaryStage) {

        GridPane gridPane = new GridPane();

        ObservableList<Course> options = FXCollections.observableArrayList(
                        new Course(0, "JavaFX"),
                        new Course(1, "Swing"),
                        new Course(2, "Objective C"),
                        new Course(3, "Swift")
        );
        ComboBox<Course> comboBox = new ComboBox<Course>(options);
        comboBox.setCellFactory(new Callback<ListView<Course>, ListCell<Course>>() {
            @Override
            public ListCell<Course> call(ListView<Course> courses) {
                return new CourseCell();
            }
        });
        comboBox.setButtonCell(new CourseCell());

        Button btn = new Button();
        btn.setText("Use");
        btn.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent event) {
                Course course = comboBox.getValue();
                if (course != null) {
                    System.out.println(course);
                    System.out.println(course.getId());
                }
            }
        });

        GridPane.setHalignment(comboBox, HPos.CENTER);
        GridPane.setHalignment(btn, HPos.CENTER);

        gridPane.setAlignment(Pos.CENTER);

        gridPane.add(comboBox, 0, 0);
        gridPane.add(btn, 0, 1);

        Scene scene = new Scene(gridPane, 300, 250);

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }

    public class CourseCell extends ListCell<Course> {

        @Override
        protected void updateItem(Course item, boolean empty) {
            super.updateItem(item, empty);
            if (item != null) {
                setText(item.getTitle());
            } else {
                setText(null);
            }
        }
    }

    public class Course {

        private long id;
        private String title;

        public Course(long id, String title) {
            this.id = id;
            this.title = title;
        }

        public long getId() {
            return id;
        }

        public String getTitle() {
            return title;
        }

        @Override
        public String toString() {
            return "Course{" + "id=" + id + ", title=" + title + '}';
        }

    }

}


问:
Fragment getArgument() right location
Playing around with Fragments, I came to wonder about the right way to populate my fragments.

As the doc says, I use the newInstance() pattern to add arguments to my fragments :

```<code>public static ItemFragment newInstance(ItemRealm item, AnnaleModel model) {
    ItemFragment fragment = new ItemFragment();
    Bundle args = new Bundle();
    args.putString(MyPagerAdapter.KEY_ITEM, item.getId());
    args.putParcelable(MyPagerAdapter.KEY_MODEL, model);
    fragment.setArguments(args);
    return fragment;
}
</code>```

But then, there is several behaviours I can see happening on the net.

The most seen it to put getArguments() in the onCreateView() method and put the results in fields :

```<code>protected String itemId;
protected Model mModel ;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    Bundle args = getArguments();
    if (args == null || (!args.containsKey(MyPagerAdapter.KEY_ITEM) || !args.containsKey(MyPagerAdapter.KEY_MODEL))) {
        Log.e("TAG", "incorrect Bundle");
        return null;
    }
    itemId = args.getString(MyPagerAdapter.KEY_ITEM);
    mModel = args.getParcelable(MyPagerAdapter.KEY_MODEL);
}
</code>```

I can see on some other places to put the same exact thing in the Fragment.onCreate() method instead of onCreateView().

And the last behaviour is to call getArguments() in the getter.

```<code>private Model getModel(){
    if (getArguments() != null) {
        return getArguments().getParcelable(AnnalePagerAdapter.KEY_MODEL);
    }
    Log.e("Dan", "ItemFragment :: getModel (279): model==null !!");
    return null;
}//I can also think about some lazyloading is needed
</code>```

The questions are then :

Is there now a consensus on which pattern to use (these 3 or even another) ?

Is there some contexts I should rather use one than another ?

答:
Don't use a getter. That just complicates things imo. Why include fragment logic in the the Model class, right?

As for onCreateView() vs onCreate(), I call getArguments() in onCreate() because this method is called before the view is created. So, if you have any calculations or other stuff then you can do it here. Save it in global vars and set them in onCreateView. But instead of doing that, you can just do it in onCreateView, right? So what's the difference then? It helps to keep the logic separated. Initialize/update the view in onCreateView and do pre-calculations stuff in onCreate

Example from google's samples

Title: Fragment getArgument() right location

Body:
Playing around with Fragments, I came to wonder about the right way to populate my fragments.

As the doc says, I use the newInstance() pattern to add arguments to my fragments :

public static ItemFragment newInstance(ItemRealm item, AnnaleModel model) {
    ItemFragment fragment = new ItemFragment();
    Bundle args = new Bundle();
    args.putString(MyPagerAdapter.KEY_ITEM, item.getId());
    args.putParcelable(MyPagerAdapter.KEY_MODEL, model);
    fragment.setArguments(args);
    return fragment;
}

But then, there is several behaviours I can see happening on the net.

The most seen it to put getArguments() in the onCreateView() method and put the results in fields :

protected String itemId;
protected Model mModel ;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    Bundle args = getArguments();
    if (args == null || (!args.containsKey(MyPagerAdapter.KEY_ITEM) || !args.containsKey(MyPagerAdapter.KEY_MODEL))) {
        Log.e("TAG", "incorrect Bundle");
        return null;
    }
    itemId = args.getString(MyPagerAdapter.KEY_ITEM);
    mModel = args.getParcelable(MyPagerAdapter.KEY_MODEL);
}

I can see on some other places to put the same exact thing in the Fragment.onCreate() method instead of onCreateView().

And the last behaviour is to call getArguments() in the getter.

private Model getModel(){
    if (getArguments() != null) {
        return getArguments().getParcelable(AnnalePagerAdapter.KEY_MODEL);
    }
    Log.e("Dan", "ItemFragment :: getModel (279): model==null !!");
    return null;
}//I can also think about some lazyloading is needed

The questions are then :

Is there now a consensus on which pattern to use (these 3 or even another) ?

Is there some contexts I should rather use one than another ?


问:
How to find the session id of running jobs
Trying to get the session id of executing jobs

```<code>;with JobDetails as
(
select Job_Id = left(intr1,charindex(':',intr1)-1),
       Step = substring(intr1,charindex(':',intr1)+1,charindex(')',intr1)-charindex(':',intr1)-1),
       SessionId = spid
    from master.dbo.sysprocesses x
    cross apply (select replace(x.program_name,'SQLAgent - TSQL JobStep (Job ','')) cs (intr1)
    where spid > 50 and x.program_name like 'SQLAgent - TSQL JobStep (Job %'
)
select *
    from msdb.dbo.sysjobs j
    inner join JobDetails jd on j.job_id = jd.Job_Id
</code>```

but it throws the following error

Msg 8169, Level 16, State 2, Line 47 Conversion failed when converting
  from a character string to uniqueidentifier.

I tried to cast the job_id to varbinary but it produces no result

```<code>;with JobDetails as
(
select Job_Id = left(intr1,charindex(':',intr1)-1),
       Step = substring(intr1,charindex(':',intr1)+1,charindex(')',intr1)-charindex(':',intr1)-1),
       SessionId = spid
    from master.dbo.sysprocesses x
    cross apply (select replace(x.program_name,'SQLAgent - TSQL JobStep (Job ','')) cs (intr1)
    where spid > 50 and x.program_name like 'SQLAgent - TSQL JobStep (Job %'
)
select *
    from msdb.dbo.sysjobs j
    inner join JobDetails jd on cast(j.job_id as varbinary) = jd.Job_Id
</code>```

but when I copy paste a job_id from cte like this

```<code>select job_id, name
    from msdb..sysjobs
    where job_id = 0x128A47A31EAB8F4DA1AD852093D815F5
</code>```

it works. Any idea how to fix this query

答:
You can use this script</p>

```<code>USE msdb
GO
SET NOCOUNT ON
SET ANSI_PADDING ON
SET QUOTED_IDENTIFIER ON
DECLARE @record_id int, @SQLProcessUtilization int, @CPU int,@EventTime datetime--,@MaxCPUAllowed int
select  top 1  @record_id =record_id,
      @EventTime=dateadd(ms, -1 * ((SELECT ms_ticks from sys.dm_os_sys_info) - [timestamp]), GetDate()),-- as EventTime,
      @SQLProcessUtilization=SQLProcessUtilization,
      --SystemIdle,
      --100 - SystemIdle - SQLProcessUtilization as OtherProcessUtilization,
      @CPU=SQLProcessUtilization + (100 - SystemIdle - SQLProcessUtilization) --as CPU_Usage
from (
      select
            record.value('(./Record/@id)[1]', 'int') as record_id,
            record.value('(./Record/SchedulerMonitorEvent/SystemHealth/SystemIdle)[1]', 'int') as SystemIdle,
            record.value('(./Record/SchedulerMonitorEvent/SystemHealth/ProcessUtilization)[1]', 'int') as SQLProcessUtilization,
            timestamp
      from (
            select timestamp, convert(xml, record) as record
            from sys.dm_os_ring_buffers
            where ring_buffer_type = N'RING_BUFFER_SCHEDULER_MONITOR'
            and record like '%<SystemHealth>%') as x
      ) as y
order by record_id desc
SELECT
            x.session_id as [Sid],
            COALESCE(x.blocking_session_id, 0) as BSid,
            @CPU as CPU,
            @SQLProcessUtilization as SQL,

            x.Status,
            x.TotalCPU as [T.CPU],
            x.Start_time,
            CONVERT(nvarchar(30), getdate()-x.Start_time, 108) as Elap_time, --x.totalElapsedTime as ElapTime,
            x.totalReads as [T.RD], -- total reads
            x.totalWrites as [T.WR], --total writes
            x.Writes_in_tempdb as [W.TDB],
            (
                  SELECT substring(text,x.statement_start_offset/2,
                        (case when x.statement_end_offset = -1
                        then len(convert(nvarchar(max), text)) * 2
                        else x.statement_end_offset end - x.statement_start_offset+3)/2)
                  FROM sys.dm_exec_sql_text(x.sql_handle)
                  FOR XML PATH(''), TYPE
            ) AS Sql_text,
            db_name(x.database_id) as dbName,
            (SELECT object_name(objectid) FROM sys.dm_exec_sql_text(x.sql_handle)) as object_name,
            x.Wait_type,
            x.Login_name,
            x.Host_name,
            CASE LEFT(x.program_name,15)
            WHEN 'SQLAgent - TSQL' THEN
            (     select top 1 'SQL Job = '+j.name from msdb.dbo.sysjobs (nolock) j
                  inner join msdb.dbo.sysjobsteps (nolock) s on j.job_id=s.job_id
                  where right(cast(s.job_id as nvarchar(50)),10) = RIGHT(substring(x.program_name,30,34),10) )
            WHEN 'SQL Server Prof' THEN 'SQL Server Profiler'
            ELSE x.program_name
            END as Program_name,
            x.percent_complete,
            x.percent_complete,
            (
                  SELECT
                        p.text
                  FROM
                  (
                        SELECT
                             sql_handle,statement_start_offset,statement_end_offset
                        FROM sys.dm_exec_requests r2
                        WHERE
                             r2.session_id = x.blocking_session_id
                  ) AS r_blocking
                  CROSS APPLY
                  (
                  SELECT substring(text,r_blocking.statement_start_offset/2,
                        (case when r_blocking.statement_end_offset = -1
                        then len(convert(nvarchar(max), text)) * 2
                        else r_blocking.statement_end_offset end - r_blocking.statement_start_offset+3)/2)
                  FROM sys.dm_exec_sql_text(r_blocking.sql_handle)
                  FOR XML PATH(''), TYPE
                  ) p (text)
            )  as blocking_text,
            (SELECT object_name(objectid) FROM sys.dm_exec_sql_text(
            (select top 1 sql_handle FROM sys.dm_exec_requests r3 WHERE r3.session_id = x.blocking_session_id))) as blocking_obj

      FROM
      (
            SELECT
                  r.session_id,
                  s.host_name,
                  s.login_name,
                  r.start_time,
                  r.sql_handle,
                  r.database_id,
                  r.blocking_session_id,
                  r.wait_type,
                  r.status,
                  r.statement_start_offset,
                  r.statement_end_offset,
                  s.program_name,
                  r.percent_complete,
                  SUM(cast(r.total_elapsed_time as bigint)) /1000 as totalElapsedTime, --CAST AS BIGINT to fix invalid data convertion when high activity
                  SUM(cast(r.reads as bigint)) AS totalReads,
                  SUM(cast(r.writes as bigint)) AS totalWrites,
                  SUM(cast(r.cpu_time as bigint)) AS totalCPU,
                  SUM(tsu.user_objects_alloc_page_count + tsu.internal_objects_alloc_page_count) AS writes_in_tempdb
            FROM sys.dm_exec_requests r
            JOIN sys.dm_exec_sessions s ON s.session_id = r.session_id
            JOIN sys.dm_db_task_space_usage tsu ON s.session_id = tsu.session_id and r.request_id = tsu.request_id
            WHERE r.status IN ('running', 'runnable', 'suspended')
            GROUP BY
                  r.session_id,
                  s.host_name,
                  s.login_name,
                  r.start_time,
                  r.sql_handle,
                  r.database_id,
                  r.blocking_session_id,
                  r.wait_type,
                  r.status,
                  r.statement_start_offset,
                  r.statement_end_offset,
                  s.program_name,
                  r.percent_complete
      ) x
      where x.session_id <> @@spid
      order by x.totalCPU desc
GO
</code>```

Body:
Trying to get the session id of executing jobs

;with JobDetails as
(
select Job_Id = left(intr1,charindex(':',intr1)-1),
       Step = substring(intr1,charindex(':',intr1)+1,charindex(')',intr1)-charindex(':',intr1)-1),
       SessionId = spid
    from master.dbo.sysprocesses x
    cross apply (select replace(x.program_name,'SQLAgent - TSQL JobStep (Job ','')) cs (intr1)
    where spid > 50 and x.program_name like 'SQLAgent - TSQL JobStep (Job %'
)
select *
    from msdb.dbo.sysjobs j
    inner join JobDetails jd on j.job_id = jd.Job_Id

but it throws the following error

Msg 8169, Level 16, State 2, Line 47 Conversion failed when converting
  from a character string to uniqueidentifier.

I tried to cast the job_id to varbinary but it produces no result

;with JobDetails as
(
select Job_Id = left(intr1,charindex(':',intr1)-1),
       Step = substring(intr1,charindex(':',intr1)+1,charindex(')',intr1)-charindex(':',intr1)-1),
       SessionId = spid
    from master.dbo.sysprocesses x
    cross apply (select replace(x.program_name,'SQLAgent - TSQL JobStep (Job ','')) cs (intr1)
    where spid > 50 and x.program_name like 'SQLAgent - TSQL JobStep (Job %'
)
select *
    from msdb.dbo.sysjobs j
    inner join JobDetails jd on cast(j.job_id as varbinary) = jd.Job_Id

but when I copy paste a job_id from cte like this

select job_id, name
    from msdb..sysjobs
    where job_id = 0x128A47A31EAB8F4DA1AD852093D815F5

it works. Any idea how to fix this query

Body:
You can use this script

USE msdb
GO
SET NOCOUNT ON
SET ANSI_PADDING ON
SET QUOTED_IDENTIFIER ON
DECLARE @record_id int, @SQLProcessUtilization int, @CPU int,@EventTime datetime--,@MaxCPUAllowed int
select  top 1  @record_id =record_id,
      @EventTime=dateadd(ms, -1 * ((SELECT ms_ticks from sys.dm_os_sys_info) - [timestamp]), GetDate()),-- as EventTime,
      @SQLProcessUtilization=SQLProcessUtilization,
      --SystemIdle,
      --100 - SystemIdle - SQLProcessUtilization as OtherProcessUtilization,
      @CPU=SQLProcessUtilization + (100 - SystemIdle - SQLProcessUtilization) --as CPU_Usage
from (
      select
            record.value('(./Record/@id)[1]', 'int') as record_id,
            record.value('(./Record/SchedulerMonitorEvent/SystemHealth/SystemIdle)[1]', 'int') as SystemIdle,
            record.value('(./Record/SchedulerMonitorEvent/SystemHealth/ProcessUtilization)[1]', 'int') as SQLProcessUtilization,
            timestamp
      from (
            select timestamp, convert(xml, record) as record
            from sys.dm_os_ring_buffers
            where ring_buffer_type = N'RING_BUFFER_SCHEDULER_MONITOR'
            and record like '%<SystemHealth>%') as x
      ) as y
order by record_id desc
SELECT
            x.session_id as [Sid],
            COALESCE(x.blocking_session_id, 0) as BSid,
            @CPU as CPU,
            @SQLProcessUtilization as SQL,

            x.Status,
            x.TotalCPU as [T.CPU],
            x.Start_time,
            CONVERT(nvarchar(30), getdate()-x.Start_time, 108) as Elap_time, --x.totalElapsedTime as ElapTime,
            x.totalReads as [T.RD], -- total reads
            x.totalWrites as [T.WR], --total writes
            x.Writes_in_tempdb as [W.TDB],
            (
                  SELECT substring(text,x.statement_start_offset/2,
                        (case when x.statement_end_offset = -1
                        then len(convert(nvarchar(max), text)) * 2
                        else x.statement_end_offset end - x.statement_start_offset+3)/2)
                  FROM sys.dm_exec_sql_text(x.sql_handle)
                  FOR XML PATH(''), TYPE
            ) AS Sql_text,
            db_name(x.database_id) as dbName,
            (SELECT object_name(objectid) FROM sys.dm_exec_sql_text(x.sql_handle)) as object_name,
            x.Wait_type,
            x.Login_name,
            x.Host_name,
            CASE LEFT(x.program_name,15)
            WHEN 'SQLAgent - TSQL' THEN
            (     select top 1 'SQL Job = '+j.name from msdb.dbo.sysjobs (nolock) j
                  inner join msdb.dbo.sysjobsteps (nolock) s on j.job_id=s.job_id
                  where right(cast(s.job_id as nvarchar(50)),10) = RIGHT(substring(x.program_name,30,34),10) )
            WHEN 'SQL Server Prof' THEN 'SQL Server Profiler'
            ELSE x.program_name
            END as Program_name,
            x.percent_complete,
            x.percent_complete,
            (
                  SELECT
                        p.text
                  FROM
                  (
                        SELECT
                             sql_handle,statement_start_offset,statement_end_offset
                        FROM sys.dm_exec_requests r2
                        WHERE
                             r2.session_id = x.blocking_session_id
                  ) AS r_blocking
                  CROSS APPLY
                  (
                  SELECT substring(text,r_blocking.statement_start_offset/2,
                        (case when r_blocking.statement_end_offset = -1
                        then len(convert(nvarchar(max), text)) * 2
                        else r_blocking.statement_end_offset end - r_blocking.statement_start_offset+3)/2)
                  FROM sys.dm_exec_sql_text(r_blocking.sql_handle)
                  FOR XML PATH(''), TYPE
                  ) p (text)
            )  as blocking_text,
            (SELECT object_name(objectid) FROM sys.dm_exec_sql_text(
            (select top 1 sql_handle FROM sys.dm_exec_requests r3 WHERE r3.session_id = x.blocking_session_id))) as blocking_obj

      FROM
      (
            SELECT
                  r.session_id,
                  s.host_name,
                  s.login_name,
                  r.start_time,
                  r.sql_handle,
                  r.database_id,
                  r.blocking_session_id,
                  r.wait_type,
                  r.status,
                  r.statement_start_offset,
                  r.statement_end_offset,
                  s.program_name,
                  r.percent_complete,
                  SUM(cast(r.total_elapsed_time as bigint)) /1000 as totalElapsedTime, --CAST AS BIGINT to fix invalid data convertion when high activity
                  SUM(cast(r.reads as bigint)) AS totalReads,
                  SUM(cast(r.writes as bigint)) AS totalWrites,
                  SUM(cast(r.cpu_time as bigint)) AS totalCPU,
                  SUM(tsu.user_objects_alloc_page_count + tsu.internal_objects_alloc_page_count) AS writes_in_tempdb
            FROM sys.dm_exec_requests r
            JOIN sys.dm_exec_sessions s ON s.session_id = r.session_id
            JOIN sys.dm_db_task_space_usage tsu ON s.session_id = tsu.session_id and r.request_id = tsu.request_id
            WHERE r.status IN ('running', 'runnable', 'suspended')
            GROUP BY
                  r.session_id,
                  s.host_name,
                  s.login_name,
                  r.start_time,
                  r.sql_handle,
                  r.database_id,
                  r.blocking_session_id,
                  r.wait_type,
                  r.status,
                  r.statement_start_offset,
                  r.statement_end_offset,
                  s.program_name,
                  r.percent_complete
      ) x
      where x.session_id <> @@spid
      order by x.totalCPU desc
GO


问:
Rounding of Timestamp(9) in Oracle 11g stored procedure
The following procedure rounds the Timestamp(9) to a Timestamp(6):

```<code>CREATE
    TABLE MY_TABLE
    (
        MY_TIMESTAMP TIMESTAMP(9) NOT NULL
    )

CREATE OR REPLACE PROCEDURE "DB"."INSERT_ROW"
(myTimestamp IN TIMESTAMP)
AS
v_sys_error NUMBER := 0;
v_err INTEGER;
v_rc INTEGER;
BEGIN

BEGIN
    INSERT
INTO
    DB.INSERT_ROW
    (
        MY_TIMESTAMP
    )
    VALUES
    (
        myTimestamp
    );
EXCEPTION
WHEN OTHERS THEN
v_sys_error := SQLCODE;
v_err := v_sys_error;
v_rc := SQL%ROWCOUNT;
RAISE;
END;

END;
</code>```

The call below will insert: 2007-12-12 12:23:45.123457000

```<code>@call DB.INSERT_ROW(TIMESTAMP '2007-12-12 12:23:45.123456789');
</code>```

Whereas the code below will insert this: 2007-12-12 12:23:45.123456789

```<code>INSERT
INTO
    DB.MY_TABLE
    (
        MY_TIMESTAMP
    )
    VALUES
    (
        TIMESTAMP '2007-12-12 12:23:45.123456789'
    );
</code>```

How do I prevent this?  Using (myTimestamp IN TIMESTAMP(9)) fails to validate.

答:
```<code>CREATE
    TABLE MY_TABLE
    (
        MY_TIMESTAMP TIMESTAMP(9) NOT NULL
    )

CREATE OR REPLACE PROCEDURE "DB"."INSERT_ROW"
(myTimestamp IN MY_TABLE.MY_TIMESTAMP%TYPE)
...
</code>```

This should do the trick. Numerically constrained types are not permitted in a parameter list.

ContentLicense: CC BY-SA 2.5

Body:
The following procedure rounds the Timestamp(9) to a Timestamp(6):

CREATE
    TABLE MY_TABLE
    (
        MY_TIMESTAMP TIMESTAMP(9) NOT NULL
    )

CREATE OR REPLACE PROCEDURE "DB"."INSERT_ROW"
(myTimestamp IN TIMESTAMP)
AS
v_sys_error NUMBER := 0;
v_err INTEGER;
v_rc INTEGER;
BEGIN

BEGIN
    INSERT
INTO
    DB.INSERT_ROW
    (
        MY_TIMESTAMP
    )
    VALUES
    (
        myTimestamp
    );
EXCEPTION
WHEN OTHERS THEN
v_sys_error := SQLCODE;
v_err := v_sys_error;
v_rc := SQL%ROWCOUNT;
RAISE;
END;

END;

The call below will insert: 2007-12-12 12:23:45.123457000

@call DB.INSERT_ROW(TIMESTAMP '2007-12-12 12:23:45.123456789');

Whereas the code below will insert this: 2007-12-12 12:23:45.123456789

INSERT
INTO
    DB.MY_TABLE
    (
        MY_TIMESTAMP
    )
    VALUES
    (
        TIMESTAMP '2007-12-12 12:23:45.123456789'
    );

How do I prevent this?  Using (myTimestamp IN TIMESTAMP(9)) fails to validate.

Body:
CREATE
    TABLE MY_TABLE
    (
        MY_TIMESTAMP TIMESTAMP(9) NOT NULL
    )

CREATE OR REPLACE PROCEDURE "DB"."INSERT_ROW"
(myTimestamp IN MY_TABLE.MY_TIMESTAMP%TYPE)
...

This should do the trick. Numerically constrained types are not permitted in a parameter list.


问:
ef core select records from tableA with matching fields in tableB
I'm trying to translate a query from raw sql to linq statement in EF Core 2

Query is something like this

```<code>SELECT * FROM TableA
WHERE FieldA = ConditionA
AND FieldB IN (SELECT FieldC FROM TableB WHERE FieldD = ConditionB)
</code>```

FieldA and FieldB are from TableA, FieldC and FieldD are from TableB

I need all fields from TableA and none from TableB returned, so it should be something like

```<code>return Context.TableA
    .Where(x => x.FieldA == ConditionA)
    .[ some code here ]
    .ToList()
</code>```

my current solution is to get two distinct result sets and join them in code, something like this

```<code>var listA = Context.TableA
    .Where(x => x.FieldA == ConditionA).ToList();
var listB = Context.TableB
    .Where(x => x.FieldD == ConditionB).Select(x => x.FieldC).ToList();
listA.RemoveAll(x => !listB.Contains(x.FieldB);
return listA;
</code>```

i hope it works, i still have to run tests on it, but i'm looking for a better solution (if anything exists)

答:
It's a simple join that needs to be applied - </p>

```<code>var result = (from a in Context.TableA.Where(x => x.FieldA == ConditionA )
         join b in Context.TableB.Where(x => x.FieldD == ConditionB) on a.FieldB equals b.FieldC
         select new {a}
         ).ToList();
</code>```

Body:
I'm trying to translate a query from raw sql to linq statement in EF Core 2

Query is something like this

SELECT * FROM TableA
WHERE FieldA = ConditionA
AND FieldB IN (SELECT FieldC FROM TableB WHERE FieldD = ConditionB)

FieldA and FieldB are from TableA, FieldC and FieldD are from TableB

I need all fields from TableA and none from TableB returned, so it should be something like

return Context.TableA
    .Where(x => x.FieldA == ConditionA)
    .[ some code here ]
    .ToList()

my current solution is to get two distinct result sets and join them in code, something like this

var listA = Context.TableA
    .Where(x => x.FieldA == ConditionA).ToList();
var listB = Context.TableB
    .Where(x => x.FieldD == ConditionB).Select(x => x.FieldC).ToList();
listA.RemoveAll(x => !listB.Contains(x.FieldB);
return listA;

i hope it works, i still have to run tests on it, but i'm looking for a better solution (if anything exists)

Body:
It's a simple join that needs to be applied -

var result = (from a in Context.TableA.Where(x => x.FieldA == ConditionA )
         join b in Context.TableB.Where(x => x.FieldD == ConditionB) on a.FieldB equals b.FieldC
         select new {a}
         ).ToList();


问:
Angular material mat-error cannot show message
I have 2 datetime picker, endDate cannot be less than startDate

```<code>endDateAfterOrEqualValidator(formGroup): any {
    var startDateTimestamp: number;
    var endDateTimestamp: number;
    startDateTimestamp = Date.parse(formGroup.controls['startDateForm'].value);
    endDateTimestamp = Date.parse(formGroup.controls['endDateForm'].value);
    return (endDateTimestamp < startDateTimestamp) ? { endDateLessThanStartDate: true } : null;
  }
</code>```

in html:

```<code><mat-form-field>
    <input matInput  name="endDate" id="endDate" formControlName="endDateForm" [(ngModel)]="endDate" [matDatepicker]="toDatePicker"
    placeholder="To Date">
    <mat-datepicker-toggle matSuffix [for]="toDatePicker"></mat-datepicker-toggle>
    <mat-datepicker disabled="false" #toDatePicker></mat-datepicker>
    <mat-error *ngIf="trainingDetail.hasError('endDateLessThanStartDate')">Not valid<mat-error>
</mat-form-field>
</code>```

with "mat-error", the message does not display. I try to change by "small"

```<code><small *ngIf="trainingDetail.hasError('endDateLessThanStartDate')">Not valid</small>
</code>```

the message well. Please advice me how to using mat-error

答:
a mat-error only shows when a FormControl is invalid, but you have the validation on your formgroup. So in that case you need to use a ErrorStateMatcher

In your case it would look like this:

export class MyErrorStateMatcher implements ErrorStateMatcher {
  isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
    const invalidCtrl = !!(control && control.invalid);
    const invalidParent = !!(control && control.parent && control.parent.invalid);

    return (invalidCtrl || invalidParent);
  }
}
```

<p>Also worth mentioning, it's not recommended to have two bindings, i.e <code>formControl</code> and <code>ngModel</code>. Remove the <code>ngModel</code> and utilize the form control instead. If you receive your start date and end date at a later point, you can use <code>patchValue</code> (just set some values to form) or <code>setValue</code> (set all values to form)</p>

<p>mark in component the errorstatematcher:</p>

<pre class="lang-ts prettyprint-override"><code>matcher = new MyErrorStateMatcher();
</code>```

As for your custom validator, you don't need to parse the dates, just check if end date is smaller than start date:

checkDates(group: FormGroup) {
  if (group.controls.endDate.value < group.controls.startDate.value) {
    return { endDateLessThanStartDate: true }
  }
  return null;
}
```

<p>and then mark the error state matcher in your template:</p>

<pre class="lang-html prettyprint-override"><code><mat-form-field>
  <input matInput [matDatepicker]="picker2" type="text" formControlName="endDate" [errorStateMatcher]="matcher">
  <mat-datepicker-toggle matSuffix [for]="picker2"></mat-datepicker-toggle>
  <mat-datepicker #picker2></mat-datepicker>
  <mat-error *ngIf="myForm.hasError('endDateLessThanStartDate')">End date cannot be earlier than start date</mat-error>
</mat-form-field>
</code>```

Here's a StackBlitz

Body:
I have 2 datetime picker, endDate cannot be less than startDate

endDateAfterOrEqualValidator(formGroup): any {
    var startDateTimestamp: number;
    var endDateTimestamp: number;
    startDateTimestamp = Date.parse(formGroup.controls['startDateForm'].value);
    endDateTimestamp = Date.parse(formGroup.controls['endDateForm'].value);
    return (endDateTimestamp < startDateTimestamp) ? { endDateLessThanStartDate: true } : null;
  }

in html:

<mat-form-field>
    <input matInput  name="endDate" id="endDate" formControlName="endDateForm" [(ngModel)]="endDate" [matDatepicker]="toDatePicker"
    placeholder="To Date">
    <mat-datepicker-toggle matSuffix [for]="toDatePicker"></mat-datepicker-toggle>
    <mat-datepicker disabled="false" #toDatePicker></mat-datepicker>
    <mat-error *ngIf="trainingDetail.hasError('endDateLessThanStartDate')">Not valid<mat-error>
</mat-form-field>

with "mat-error", the message does not display. I try to change by "small"

Not valid

the message well. Please advice me how to using mat-error

Body:
a mat-error only shows when a FormControl is invalid, but you have the validation on your formgroup. So in that case you need to use a ErrorStateMatcher

In your case it would look like this:

export class MyErrorStateMatcher implements ErrorStateMatcher {
  isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
    const invalidCtrl = !!(control && control.invalid);
    const invalidParent = !!(control && control.parent && control.parent.invalid);

    return (invalidCtrl || invalidParent);
  }
}

Also worth mentioning, it's not recommended to have two bindings, i.e formControl and ngModel. Remove the ngModel and utilize the form control instead. If you receive your start date and end date at a later point, you can use patchValue (just set some values to form) or setValue (set all values to form)

mark in component the errorstatematcher:

matcher = new MyErrorStateMatcher();

As for your custom validator, you don't need to parse the dates, just check if end date is smaller than start date:

checkDates(group: FormGroup) {
  if (group.controls.endDate.value < group.controls.startDate.value) {
    return { endDateLessThanStartDate: true }
  }
  return null;
}

and then mark the error state matcher in your template:

<mat-form-field>
  <input matInput [matDatepicker]="picker2" type="text" formControlName="endDate" [errorStateMatcher]="matcher">
  <mat-datepicker-toggle matSuffix [for]="picker2"></mat-datepicker-toggle>
  <mat-datepicker #picker2></mat-datepicker>
  <mat-error *ngIf="myForm.hasError('endDateLessThanStartDate')">End date cannot be earlier than start date</mat-error>
</mat-form-field>

Here's a StackBlitz


问:
How to get an integer value to a complex dictionary
Here the value of abc is an integer and total is a dictionary which contains another dictionaries.But when I run this line,

```<code>    total[div]['total_transport_allowance'] = abc
</code>```

This error is shown : "KeyError: None"
Please Help

What I want from this statement is to get the abc's value to the key 'total_transport_allowance'

def print_excel_report(self,cr,uid,ids,data,context=None):
    result = self._get_lines(cr,uid,ids,data)
    filename= 'PayrollRegister.xls'
    workbook= xlwt.Workbook(encoding="UTF-8")
    sheet= workbook.add_sheet('Payroll Register',cell_overwrite_ok=True)
    style = xlwt.easyxf('font:height 400, bold True, name Arial; align: horiz center, vert center;borders: top medium,right medium,bottom medium,left medium')
    a = range(1,10)
    row = 1
    col =0
    header = ['Division','Basic','Transport Allowance']
    style2 = xlwt.easyxf('font: bold 1')
    total = {}

    for index,data in enumerate(result):
        div = data.get('Division',False)
        abc = data.get('transport_allowance',False) or 0

        if div:
            if div in total:
                total[div]['total_basic'] = total[div]['total_basic'] +  data.get('basic',0)
                total[div]['total_transport_allowance'] = total[div]['total_transport_allowance'] +  abc
            else:
                total[div] = {}
                total[div]['total_basic'] =  data.get('basic',0)
                total[div]['total_transport_allowance'] = abc

        else:
            if 'Undefined' in total:
                total['Undefined']['total_basic'] = total['Undefined']['total_basic'] +  data.get('basic',0)
                total[div]['total_transport_allowance'] = total[div]['total_transport_allowance'] + abc

            else:
                total['Undefined'] = {}
                total['Undefined']['total_basic'] =  data.get('basic',0)
                total[div]['total_transport_allowance'] = abc
        .......
        .....
```

答:
To try and rescue something from all the downvotes:

You have an if statment checking the truthy of div. In the falsey case you then use div to access total.

ie you have:

```<code>if div:
    # stuff
else:
    # stuff
    total[div]['total_transport_allowance'] = abc
</code>```

As total doesn't have the key div, this doesn't work.

you need something like total[div] = {}

Body:
Here the value of abc is an integer and total is a dictionary which contains another dictionaries.But when I run this line,

    total[div]['total_transport_allowance'] = abc

This error is shown : "KeyError: None"
Please Help

What I want from this statement is to get the abc's value to the key 'total_transport_allowance'

def print_excel_report(self,cr,uid,ids,data,context=None):
    result = self._get_lines(cr,uid,ids,data)
    filename= 'PayrollRegister.xls'
    workbook= xlwt.Workbook(encoding="UTF-8")
    sheet= workbook.add_sheet('Payroll Register',cell_overwrite_ok=True)
    style = xlwt.easyxf('font:height 400, bold True, name Arial; align: horiz center, vert center;borders: top medium,right medium,bottom medium,left medium')
    a = range(1,10)
    row = 1
    col =0
    header = ['Division','Basic','Transport Allowance']
    style2 = xlwt.easyxf('font: bold 1')
    total = {}

    for index,data in enumerate(result):
        div = data.get('Division',False)
        abc = data.get('transport_allowance',False) or 0

        if div:
            if div in total:
                total[div]['total_basic'] = total[div]['total_basic'] +  data.get('basic',0)
                total[div]['total_transport_allowance'] = total[div]['total_transport_allowance'] +  abc
            else:
                total[div] = {}
                total[div]['total_basic'] =  data.get('basic',0)
                total[div]['total_transport_allowance'] = abc

        else:
            if 'Undefined' in total:
                total['Undefined']['total_basic'] = total['Undefined']['total_basic'] +  data.get('basic',0)
                total[div]['total_transport_allowance'] = total[div]['total_transport_allowance'] + abc

            else:
                total['Undefined'] = {}
                total['Undefined']['total_basic'] =  data.get('basic',0)
                total[div]['total_transport_allowance'] = abc
        .......
        .....

Body:
To try and rescue something from all the downvotes:

You have an if statment checking the truthy of div. In the falsey case you then use div to access total.

ie you have:

if div:
    # stuff
else:
    # stuff
    total[div]['total_transport_allowance'] = abc

As total doesn't have the key div, this doesn't work.

you need something like total[div] = {}


问:
SplashScreen approach defined in xml (without activity) does not appear
I have defined splash screen like many other without external activity, but it doesn't works for me, I don't understand why.

Is there any limitations for images? Also tried for many other images
This is my splash.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android"
    android:opacity="opaque">
    <item>
        <bitmap
            android:gravity="center"
            android:src="@drawable/splash_logo" />
    </item>
</layer-list>
</code>```

Here preview for splash.xml file in android studio looks like perfectly.
Than I have created style like that

```<code><style name="AppTheme.Launcher">
    <item name="android:windowBackground">@drawable/splash</item>
</style>
</code>```

and assigned it to activity theme inside manifest

```<code> <activity
        android:theme="@style/AppTheme.Launcher"
        android:name=".MainActivity"
        android:screenOrientation="portrait">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</code>```

this is my activity's

```<code>override fun onCreate(savedInstanceState: Bundle?) {
    setTheme(R.style.AppTheme)
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
}
</code>```

when activity is loaded blank white screen is shown instead of image, maybe for a one second. I searched this approach and seems that it is the same what others were done. Don't understand what's wrong

EDIT:
I have tested it for another device OS 5.0 and it works, but for 6.0 doesn't

答: This should be a comment. But i cannot put a comment. I have faced the same problem. Please check your size of image. Try to compress the image and try again it may help you. Please do let me know.</p>

Body:
I have defined splash screen like many other without external activity, but it doesn't works for me, I don't understand why.

Is there any limitations for images? Also tried for many other images
This is my splash.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android"
    android:opacity="opaque">
    <item>
        <bitmap
            android:gravity="center"
            android:src="@drawable/splash_logo" />
    </item>
</layer-list>

Here preview for splash.xml file in android studio looks like perfectly.
Than I have created style like that

and assigned it to activity theme inside manifest

 <activity
        android:theme="@style/AppTheme.Launcher"
        android:name=".MainActivity"
        android:screenOrientation="portrait">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

this is my activity's

override fun onCreate(savedInstanceState: Bundle?) {
    setTheme(R.style.AppTheme)
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
}

when activity is loaded blank white screen is shown instead of image, maybe for a one second. I searched this approach and seems that it is the same what others were done. Don't understand what's wrong

EDIT:
I have tested it for another device OS 5.0 and it works, but for 6.0 doesn't


问:
Bash Script (awk-sed-grep) to check whether numbers in every next line are 1 more than previous line
I have a file:

```<code>Time= 12:40:41, value = 1, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 2, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 3, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 4, data=2, data2=4,timeEnter=12:34:34
...
...
Time= 12:40:41, value = 123456, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 123457, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 123458, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 123459, data=2, data2=4,timeEnter=12:34:34
</code>```

I want to read this file using Cat | grep awk.
And want to be able to run a command using combination of these to check if every number in the 'value' section increased by 1 in every next line.
if this was not followed in any case I want to be able to see that point.

Till now: I am stuck at:
$ Cat FileName | awk -F "= " '{print $4}'

Thanks

答:
Consider the input file so.txt has the following content:

```<code>Time= 12:40:41, value = 1, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 2, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 3, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 4, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 7, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 8, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 9, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 10, data=2, data2=4,timeEnter=12:34:34
</code>```

Here is a possible solution:

```<code>cat so.txt | awk {'print $5'} | tr -d , | awk '$1!=p+1{print "values from "p+1" to "$1-1" are missing"}{p=$1}'
</code>```

This will output:

```<code>values from 5 to 6 are missing
</code>```

If there are no gaps in the values field, the command will output nothing.

How this works?

The command can be broken as:

cat so.txt will output the file content on stdout

awk {'print $5'} will print the 5th column (which is the value field),

tr -d , to remove the comma separator

The final awk expression has:

$1 is the first column from current input line

p is the previous value of the last line

so ($1!=p+1) is a condition : if $1 is different than previous value +1, then :

this part is executed : {print "values from "p+1" to "$1-1" are missing"} : print previous value +1 and the first columns +1 are missing

{p=$1} is executed for each lines : p is assigned to the current 1st column.

Body:
I have a file:

Time= 12:40:41, value = 1, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 2, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 3, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 4, data=2, data2=4,timeEnter=12:34:34
...
...
Time= 12:40:41, value = 123456, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 123457, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 123458, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 123459, data=2, data2=4,timeEnter=12:34:34

I want to read this file using Cat | grep awk.
And want to be able to run a command using combination of these to check if every number in the 'value' section increased by 1 in every next line.
if this was not followed in any case I want to be able to see that point.

Till now: I am stuck at:
$ Cat FileName | awk -F "= " '{print $4}'

Thanks

Body:
Consider the input file so.txt has the following content:

Time= 12:40:41, value = 1, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 2, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 3, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 4, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 7, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 8, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 9, data=2, data2=4,timeEnter=12:34:34
Time= 12:40:41, value = 10, data=2, data2=4,timeEnter=12:34:34

Here is a possible solution:

cat so.txt | awk {'print $5'} | tr -d , | awk '$1!=p+1{print "values from "p+1" to "$1-1" are missing"}{p=$1}'

This will output:

values from 5 to 6 are missing

If there are no gaps in the values field, the command will output nothing.

How this works?

The command can be broken as:

cat so.txt will output the file content on stdout

awk {'print $5'} will print the 5th column (which is the value field),

tr -d , to remove the comma separator

The final awk expression has:

$1 is the first column from current input line

p is the previous value of the last line

so ($1!=p+1) is a condition : if $1 is different than previous value +1, then :

this part is executed : {print "values from "p+1" to "$1-1" are missing"} : print previous value +1 and the first columns +1 are missing

{p=$1} is executed for each lines : p is assigned to the current 1st column.